Example usage for javax.servlet.http HttpServletRequest getCookies

List of usage examples for javax.servlet.http HttpServletRequest getCookies

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getCookies.

Prototype

public Cookie[] getCookies();

Source Link

Document

Returns an array containing all of the Cookie objects the client sent with this request.

Usage

From source file:aaf.vhr.idp.http.VhrRemoteUserAuthServlet.java

/** {@inheritDoc} */
@Override// w  w w  . j  a va 2 s  .  c o  m
protected void service(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse)
        throws ServletException, IOException {

    try {
        // key to ExternalAuthentication session
        String key = null;
        boolean isVhrReturn = false;
        boolean isForceAuthn = false;
        DateTime authnStart = null; // when this authentication started at the IdP
        // array to use as return parameter when calling VhrSessionValidator
        DateTime authnInstantArr[] = new DateTime[1];

        if (httpRequest.getParameter(REDIRECT_REQ_PARAM_NAME) != null) {
            // we have come back from the VHR
            isVhrReturn = true;
            key = httpRequest.getParameter(REDIRECT_REQ_PARAM_NAME);
            HttpSession hs = httpRequest.getSession();

            if (hs != null && hs.getAttribute(AUTHN_INIT_INSTANT_ATTR_NAME + key) != null) {
                authnStart = (DateTime) hs.getAttribute(AUTHN_INIT_INSTANT_ATTR_NAME + key);
                // remove the attribute from the session so that we do not attempt to reuse it...
                hs.removeAttribute(AUTHN_INIT_INSTANT_ATTR_NAME);
            }
            ;

            if (hs != null && hs.getAttribute(IS_FORCE_AUTHN_ATTR_NAME + key) != null) {
                isForceAuthn = ((Boolean) hs.getAttribute(IS_FORCE_AUTHN_ATTR_NAME + key)).booleanValue();
                // remove the attribute from the session so that we do not attempt to reuse it...
                hs.removeAttribute(AUTHN_INIT_INSTANT_ATTR_NAME);
            }
            ;

        } else {
            // starting a new SSO request
            key = ExternalAuthentication.startExternalAuthentication(httpRequest);

            // check if forceAuthn is set
            Object forceAuthnAttr = httpRequest.getAttribute(ExternalAuthentication.FORCE_AUTHN_PARAM);
            if (forceAuthnAttr != null && forceAuthnAttr instanceof java.lang.Boolean) {
                log.debug("Loading foceAuthn value");
                isForceAuthn = ((Boolean) forceAuthnAttr).booleanValue();
            }

            // check if we can see when authentication was initiated
            final AuthenticationContext authCtx = ExternalAuthentication
                    .getProfileRequestContext(key, httpRequest)
                    .getSubcontext(AuthenticationContext.class, false);
            if (authCtx != null) {
                log.debug("Authentication initiation is {}", authCtx.getInitiationInstant());
                authnStart = new DateTime(authCtx.getInitiationInstant(), DateTimeZone.UTC);
                log.debug("AuthnStart is {}", authnStart);
            }
            ;

        }
        ;
        log.debug("forceAuthn is {}, authnStart is {}", isForceAuthn, authnStart);

        if (key == null) {
            log.error("No ExternalAuthentication sesssion key found");
            throw new ServletException("No ExternalAuthentication sesssion key found");
        }
        ;
        // we now have a key - either:
        // * we started new authentication
        // * or we have returned from VHR and loaded the key from the HttpSession

        String username = null;

        // We may have a cookie - either as part of return or from previous session
        // Attempt to locate VHR SessionID
        String vhrSessionID = null;
        Cookie[] cookies = httpRequest.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(SSO_COOKIE_NAME)) {
                vhrSessionID = cookie.getValue();
                break;
            }
        }

        if (vhrSessionID != null) {
            log.info("Found vhrSessionID from {}. Establishing validity.", httpRequest.getRemoteHost());
            username = vhrSessionValidator.validateSession(vhrSessionID, (isForceAuthn ? authnStart : null),
                    authnInstantArr);
        }
        ;

        // If we do not have a username yet (no Vhr session cookie or did not validate),
        // we redirect to VHR - but only if we are not returning from the VHR
        // Reason: (i) we do not want to loop and (ii) we do not have the full context otherwise initialized by
        // ExternalAuthentication.startExternalAuthentication()
        if (username == null && !isVhrReturn) {

            URLCodec codec = new URLCodec();
            String relyingParty = (String) httpRequest.getAttribute("relyingParty");
            String serviceName = "";

            log.info("No vhrSessionID found from {}. Directing to VHR authentication process.",
                    httpRequest.getRemoteHost());
            log.debug("Relying party which initiated the SSO request was: {}", relyingParty);

            // try getting a RelyingPartyUIContext
            // we should pass on the request for consent revocation
            final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(key, httpRequest);
            final RelyingPartyUIContext rpuiCtx = prc.getSubcontext(AuthenticationContext.class, true)
                    .getSubcontext(RelyingPartyUIContext.class, false);
            if (rpuiCtx != null) {
                serviceName = rpuiCtx.getServiceName();
                log.debug("RelyingPartyUIContext received, ServiceName is {}", serviceName);
            }
            ;

            // save session *key*
            HttpSession hs = httpRequest.getSession(true);
            hs.setAttribute(IS_FORCE_AUTHN_ATTR_NAME + key, new Boolean(isForceAuthn));
            hs.setAttribute(AUTHN_INIT_INSTANT_ATTR_NAME + key, authnStart);

            try {
                httpResponse.sendRedirect(String.format(vhrLoginEndpoint,
                        codec.encode(httpRequest.getRequestURL().toString() + "?" + REDIRECT_REQ_PARAM_NAME
                                + "=" + codec.encode(key)),
                        codec.encode(relyingParty), codec.encode(serviceName)));
            } catch (EncoderException e) {
                log.error("Could not encode VHR redirect params");
                throw new IOException(e);
            }
            return; // we issued a redirect - return now
        }
        ;

        if (username == null) {
            log.warn("VirtualHome authentication failed: no username received");
            httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                    "VirtualHome authentication failed: no username received");
            ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
            return;
        }

        // check if consent revocation was requested
        String consentRevocationParam = httpRequest.getParameter(consentRevocationParamName);
        if (consentRevocationParam != null) {
            // we should pass on the request for consent revocation
            final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(key, httpRequest);
            final ConsentManagementContext consentCtx = prc.getSubcontext(ConsentManagementContext.class, true);
            log.debug("Consent revocation request received, setting revokeConsent in consentCtx");
            consentCtx.setRevokeConsent(consentRevocationParam.equalsIgnoreCase("true"));
        }
        ;

        // Set authnInstant to timestamp returned by VHR
        if (authnInstantArr[0] != null) {
            log.debug("Response from VHR includes authenticationInstant time {}, passing this back to IdP",
                    authnInstantArr[0]);
            httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_INSTANT_KEY, authnInstantArr[0]);
        }
        ;

        httpRequest.setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, username);

        ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);

    } catch (final ExternalAuthenticationException e) {
        throw new ServletException("Error processing external authentication request", e);
    }
}

From source file:nl.nn.adapterframework.http.rest.ApiListenerServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    /**// w  ww  .j  a  va 2s. c  o m
     * Initiate and populate messageContext
     */
    PipeLineSessionBase messageContext = new PipeLineSessionBase();
    messageContext.put(IPipeLineSession.HTTP_REQUEST_KEY, request);
    messageContext.put(IPipeLineSession.HTTP_RESPONSE_KEY, response);
    messageContext.put(IPipeLineSession.SERVLET_CONTEXT_KEY, getServletContext());
    messageContext.setSecurityHandler(new HttpSecurityHandler(request));

    try {
        String uri = request.getPathInfo();
        String method = request.getMethod().toUpperCase();
        log.trace("ApiListenerServlet dispatching uri [" + uri + "] and method [" + method + "]");

        if (uri == null) {
            response.setStatus(400);
            log.warn("Aborting request with status [400], empty uri");
            return;
        }

        if (uri.startsWith("/"))
            uri = uri.substring(1);
        if (uri.endsWith("/"))
            uri = uri.substring(0, uri.length() - 1);

        ApiDispatchConfig config = dispatcher.findConfigForUri(uri);
        if (config == null) {
            response.setStatus(404);
            log.trace("Aborting request with status [404], no ApiListener configured for [" + uri + "]");
            return;
        }

        /**
         * Handle Cross-Origin Resource Sharing
         * TODO make this work behind loadbalancers/reverse proxies
         * TODO check if request ip/origin header matches allowOrigin property
         */
        String origin = request.getHeader("Origin");
        if (method.equals("OPTIONS") || origin != null) {
            response.setHeader("Access-Control-Allow-Origin", CorsAllowOrigin);
            String headers = request.getHeader("Access-Control-Request-Headers");
            if (headers != null)
                response.setHeader("Access-Control-Allow-Headers", headers);
            response.setHeader("Access-Control-Expose-Headers", CorsExposeHeaders);

            StringBuilder methods = new StringBuilder();
            for (String mtd : config.getMethods()) {
                methods.append(", ").append(mtd);
            }
            response.setHeader("Access-Control-Allow-Methods", methods.toString());

            //Only cut off OPTIONS (aka preflight) requests
            if (method.equals("OPTIONS")) {
                response.setStatus(200);
                log.trace("Aborting preflight request with status [200], method [" + method + "]");
                return;
            }
        }

        /**
         * Get serviceClient
         */
        ApiListener listener = config.getApiListener(method);
        if (listener == null) {
            response.setStatus(405);
            log.trace("Aborting request with status [405], method [" + method + "] not allowed");
            return;
        }

        log.trace("ApiListenerServlet calling service [" + listener.getName() + "]");

        /**
         * Check authentication
         */
        ApiPrincipal userPrincipal = null;

        if (listener.getAuthenticationMethod() != null) {

            String authorizationToken = null;
            Cookie authorizationCookie = null;
            if (listener.getAuthenticationMethod().equals("COOKIE")) {

                Cookie[] cookies = request.getCookies();
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("authenticationToken")) {
                        authorizationToken = cookie.getValue();
                        authorizationCookie = cookie;
                        authorizationCookie.setPath("/");
                    }
                }
            } else if (listener.getAuthenticationMethod().equals("HEADER")) {
                authorizationToken = request.getHeader("Authorization");
            }

            if (authorizationToken != null && cache.containsKey(authorizationToken))
                userPrincipal = (ApiPrincipal) cache.get(authorizationToken);

            if (userPrincipal == null || !userPrincipal.isLoggedIn()) {
                cache.remove(authorizationToken);
                if (authorizationCookie != null) {
                    authorizationCookie.setMaxAge(0);
                    response.addCookie(authorizationCookie);
                }

                response.setStatus(401);
                log.trace("Aborting request with status [401], no (valid) credentials supplied");
                return;
            }

            if (authorizationCookie != null) {
                authorizationCookie.setMaxAge(authTTL);
                response.addCookie(authorizationCookie);
            }
            userPrincipal.updateExpiry();
            userPrincipal.setToken(authorizationToken);
            cache.put(authorizationToken, userPrincipal, authTTL);
            messageContext.put("authorizationToken", authorizationToken);
        }
        messageContext.put("remoteAddr", request.getRemoteAddr());
        messageContext.put(IPipeLineSession.API_PRINCIPAL_KEY, userPrincipal);
        messageContext.put("uri", uri);

        /**
         * Evaluate preconditions
         */
        String accept = request.getHeader("Accept");
        if (accept != null && !accept.isEmpty() && !accept.equals("*/*")) {
            if (!listener.getProduces().equals("ANY") && !accept.contains(listener.getContentType())) {
                response.setStatus(406);
                response.getWriter().print("It appears you expected the MediaType [" + accept
                        + "] but I only support the MediaType [" + listener.getContentType() + "] :)");
                log.trace("Aborting request with status [406], client expects [" + accept + "] got ["
                        + listener.getContentType() + "] instead");
                return;
            }
        }

        if (request.getContentType() != null && !listener.isConsumable(request.getContentType())) {
            response.setStatus(415);
            log.trace("Aborting request with status [415], did not match consumes [" + listener.getConsumes()
                    + "] got [" + request.getContentType() + "] instead");
            return;
        }

        String etagCacheKey = ApiCacheManager.buildCacheKey(uri);
        log.debug("Evaluating preconditions for listener[" + listener.getName() + "] etagKey[" + etagCacheKey
                + "]");
        if (cache.containsKey(etagCacheKey)) {
            String cachedEtag = (String) cache.get(etagCacheKey);
            log.debug("found etag value[" + cachedEtag + "] for key[" + etagCacheKey + "]");

            if (method.equals("GET")) {
                String ifNoneMatch = request.getHeader("If-None-Match");
                if (ifNoneMatch != null && ifNoneMatch.equals(cachedEtag)) {
                    response.setStatus(304);
                    log.trace(
                            "Aborting request with status [304], matched if-none-match [" + ifNoneMatch + "]");
                    return;
                }
            } else {
                String ifMatch = request.getHeader("If-Match");
                if (ifMatch != null && !ifMatch.equals(cachedEtag)) {
                    response.setStatus(412);
                    log.trace("Aborting request with status [412], matched if-match [" + ifMatch + "] method ["
                            + method + "]");
                    return;
                }
            }
        }
        messageContext.put("updateEtag", listener.getUpdateEtag());

        /**
         * Check authorization
         */
        //TODO: authentication implementation

        /**
         * Map uriIdentifiers into messageContext 
         */
        String patternSegments[] = listener.getUriPattern().split("/");
        String uriSegments[] = uri.split("/");
        int uriIdentifier = 0;
        for (int i = 0; i < patternSegments.length; i++) {
            String segment = patternSegments[i];
            if (segment.startsWith("{") && segment.endsWith("}")) {
                String name;
                if (segment.equals("*"))
                    name = "uriIdentifier_" + uriIdentifier;
                else
                    name = segment.substring(1, segment.length() - 1);

                uriIdentifier++;
                log.trace("setting uriSegment [" + name + "] to [" + uriSegments[i] + "]");
                messageContext.put(name, uriSegments[i]);
            }
        }

        /**
         * Map queryParameters into messageContext
         */
        Enumeration<?> paramnames = request.getParameterNames();
        while (paramnames.hasMoreElements()) {
            String paramname = (String) paramnames.nextElement();
            String paramvalue = request.getParameter(paramname);

            log.trace("setting queryParameter [" + paramname + "] to [" + paramvalue + "]");
            messageContext.put(paramname, paramvalue);
        }

        /**
         * Map multipart parts into messageContext
         */
        if (ServletFileUpload.isMultipartContent(request)) {
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            List<FileItem> items = servletFileUpload.parseRequest(request);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();
                    log.trace("setting multipart formField [" + fieldName + "] to [" + fieldValue + "]");
                    messageContext.put(fieldName, fieldValue);
                } else {
                    // Process form file field (input type="file").
                    String fieldName = item.getFieldName();
                    String fieldNameName = fieldName + "Name";
                    String fileName = FilenameUtils.getName(item.getName());
                    log.trace("setting multipart formFile [" + fieldNameName + "] to [" + fileName + "]");
                    messageContext.put(fieldNameName, fileName);
                    log.trace(
                            "setting parameter [" + fieldName + "] to input stream of file [" + fileName + "]");
                    messageContext.put(fieldName, item.getInputStream());
                }
            }
        }

        /**
         * Compile Allow header
         */
        StringBuilder methods = new StringBuilder();
        methods.append("OPTIONS, ");
        for (String mtd : config.getMethods()) {
            methods.append(mtd + ", ");
        }
        messageContext.put("allowedMethods", methods.substring(0, methods.length() - 2));

        /**
         * Process the request through the pipeline
         */

        String body = "";
        if (!ServletFileUpload.isMultipartContent(request)) {
            body = Misc.streamToString(request.getInputStream(), "\n", false);
        }
        String result = listener.processRequest(null, body, messageContext);

        /**
         * Calculate an eTag over the processed result and store in cache
         */
        if (messageContext.get("updateEtag", true)) {
            log.debug("calculating etags over processed result");
            String cleanPattern = listener.getCleanPattern();
            if (result != null && method.equals("GET")) {
                String eTag = ApiCacheManager.buildEtag(cleanPattern, result.hashCode());
                log.debug("adding/overwriting etag with key[" + etagCacheKey + "] value[" + eTag + "]");
                cache.put(etagCacheKey, eTag);
                response.addHeader("etag", eTag);
            } else {
                log.debug("removing etag with key[" + etagCacheKey + "]");
                cache.remove(etagCacheKey);

                // Not only remove the eTag for the selected resources but also the collection
                String key = ApiCacheManager.getParentCacheKey(listener, uri);
                if (key != null) {
                    log.debug("removing parent etag with key[" + key + "]");
                    cache.remove(key);
                }
            }
        }

        /**
         * Add headers
         */
        response.addHeader("Allow", (String) messageContext.get("allowedMethods"));

        String contentType = listener.getContentType() + "; charset=utf-8";
        if (listener.getProduces().equals("ANY")) {
            contentType = messageContext.get("contentType", contentType);
        }
        response.setHeader("Content-Type", contentType);

        /**
         * Check if an exitcode has been defined or if a statuscode has been added to the messageContext.
         */
        int statusCode = messageContext.get("exitcode", 0);
        if (statusCode > 0)
            response.setStatus(statusCode);

        /**
         * Finalize the pipeline and write the result to the response
         */
        if (result != null)
            response.getWriter().print(result);
        log.trace("ApiListenerServlet finished with statusCode [" + statusCode + "] result [" + result + "]");
    } catch (Exception e) {
        log.warn("ApiListenerServlet caught exception, will rethrow as ServletException", e);
        try {
            response.flushBuffer();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (IllegalStateException ex) {
            //We're only informing the end user(s), no need to catch this error...
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:com.google.gsa.Kerberos.java

/**
 * Servlet's doPost: processes a POST request. Controls the overall 
 * kerberos silent authentication process. It supports both the Security 
 * Framework's SAML and Forms Based interface.
 * <p>/*from w w  w.ja v  a 2  s.  c o  m*/
 * You can find more information on the Security Framework's Kerberos guide 
 * about the scenarios implemented here
 * 
 * @param request HTTP request
 * @param response HTTP response
 * 
 * @throws ServletException
 * @throws IOException
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    logger.debug("Kerberos servlet");

    if (gsaValveConfigPath == null) {
        if (request.getAttribute("gsaValveConfigPath") == null) {
            //Read parameter from config file: SAML
            gsaValveConfigPath = readValveConfigPath();
        } else {
            gsaValveConfigPath = request.getAttribute("gsaValveConfigPath").toString();
        }
    }

    logger.debug("Valve Config Path is: " + gsaValveConfigPath);

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    //Authentication Processes 
    AuthenticationProcessImpl authenticationProcessCls = null;
    KerberosAuthenticationProcess krbAuthN = new KerberosAuthenticationProcess();

    //Initialize cookies vars
    Cookie gsaRefererCookie = null;
    Cookie gsaAuthCookie = null;

    //Session Cookie arrays
    Vector<Cookie> krbCookies = new Vector<Cookie>();
    Vector<Cookie> nonKrbCookies = new Vector<Cookie>();

    //user agent
    String userAgent = null;

    //user credentials
    Credentials creds = null;

    //User Session and Session ID vars definition
    UserSession userSession = null;
    String sessionID = null;
    String encodedSessionID = null;

    //Create the credentials store
    try {
        this.valveConf = ValveConfigurationInstance.getValveConfig(gsaValveConfigPath);
    } catch (ValveConfigurationException e) {
        logger.error("Valve Config instantiation error: " + e);
    }

    logger.debug("Creating the credentials store");
    creds = new Credentials();
    String username = null;

    //Setting Valve parameters
    logger.debug("Setting Valve params");
    setValveParams(request);

    //Protection
    if ((!isKerberos) || (!isNegotiate)) {
        logger.error(
                "Configuration error: if you want to use Kerberos silent AuthN, isKerberos and isNegotiate config vars have to be set to true");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Configuration error - Kerberos is not set properly");
        return;
    }

    Cookie cookies[] = null;

    // Retrieve cookies
    cookies = request.getCookies();

    // Protection: look for auth and referer cookies
    if (cookies != null) {

        // Look for the referer cookie
        for (int i = 0; i < cookies.length; i++) {

            // Look for the referer cookie
            if ((cookies[i].getName()).equals(refererCookieName)) {

                // Cache cookie
                gsaRefererCookie = cookies[i];

                logger.debug("Referer cookie already exists: " + gsaRefererCookie.getValue());

            } else {
                // Look for the auth cookie
                if ((cookies[i].getName()).equals(authCookieName)) {

                    // Cache cookie
                    gsaAuthCookie = cookies[i];

                    logger.debug("Auth cookie already exists: " + gsaAuthCookie.getValue());

                }
            }

            if ((gsaRefererCookie != null) && (gsaAuthCookie != null)) {
                // Exit
                break;
            }

        }

    }

    // Protection
    if (!isSAML) {
        if (gsaRefererCookie == null) {

            // Raise error
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "The GSA authentication servlet couldn't read the referer cookie");

            // Log error
            logger.error(
                    "The GSA authentication servlet couldn't read the referer cookie, pls. check the cookie domain value");

            // Return
            return;

        }
    } else {
        //SAML

        //Get SAML Params
        relayState = request.getParameter("RelayState");
        samlRequest = request.getParameter("SAMLRequest");
        //String relayStateCookie = valveConf.getSAMLConfig().getRelayStateCookie();
        boolean noParams = false;
        boolean cookieExist = true;

        //Protection
        if ((relayState == null) || (relayState.equals(""))) {
            noParams = true;
        } else {
            if ((samlRequest == null) || (samlRequest.equals(""))) {
                noParams = true;
            }
        }

        createRefererCookie(gsaRefererCookie);

        //if ((noParams)&&(!cookieExist)) {
        if (noParams) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request");
            return;
        }
    }

    logger.debug("Let's validate if gsaAuthCookie is present");

    if (gsaAuthCookie != null) {

        if (!isSAML) {
            //redirect
            String redirect = gsaRefererCookie.getValue();

            logger.debug("redirect is " + redirect);
            //redirect only if the URL is different than the login one                    
            if (!redirect.equals(loginUrl)) {

                //user properly authenticated
                logger.debug("The user was properly authenticated. Lets redirect to..." + redirect);

                // Redirect
                response.sendRedirect(redirect);

            } else {
                logger.debug("It's the login URL. No redirect");
            }
        } else {
            logger.debug("As this is SAML. Let's obviate the previous authentication cookie");
            gsaAuthCookie = null;
        }
    }

    userSession = new UserSession();

    Sessions sessions = Sessions.getInstance();
    sessions.setMaxSessionAgeMinutes(maxSessionAge);
    sessions.setSessionTimeoutMinutes(sessionTimeout);

    if (gsaAuthCookie == null) {

        logger.debug("gsaAuthCookie does not exist");

        isNegotiate = true;

        // Read User-Agent header
        userAgent = request.getHeader("User-Agent");

        logger.debug("userAgent is... " + userAgent);

        //check if user is gsa-crawler
        if (userAgent.startsWith(GSA_CRAWLER_USER)) {

            logger.debug("User is " + GSA_CRAWLER_USER);

            //check if user is gsa-crawler and have to authenticate it thru a form                                  
            if (KrbUsrPwdCrawler) {

                logger.debug("gsa-crawler has to access thru username and password");

                //check if crawler already provided credentials

                if (request.getParameter("UserIDKrb") == null) {

                    //the login page have to be filled in by the admin user before reaching here. Return error
                    logger.error("The login page [" + KrbUsrPwdCrawlerUrl
                            + "] has to be invoked and its credentials fields filled in before reaching here");
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "It means the GSA Valve Kerberos configuration is not done properly or you just forgot to fill in the Kerberos credentials in the login page");
                    return;

                } else {

                    //user already submits credentials
                    logger.debug("Crawler has already sent credentials");
                    //set isNegotiate equal false (it authenticates the user thru username and pwd credentials)                                                                                    
                    isNegotiate = false;

                    //set Crawler credentials
                    setCrawlerCredentials(request, creds, KrbAdditionalAuthN);

                    //authenticate user
                    statusCode = krbAuthentication(request, response, krbAuthN, krbCookies,
                            gsaRefererCookie.getValue(), creds, isNegotiate);

                    // Protection: check status code
                    if (statusCode != HttpServletResponse.SC_OK) {

                        // Raise error
                        response.sendError(statusCode, "Authentication process failed!");

                        // Debug
                        if (logger.isDebugEnabled())
                            logger.debug("Krb Authentication process failed with code: " + statusCode);

                        if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
                            logger.debug(
                                    "Note: this 401 could not be an error as sending 401 could be part of the Negotiation process");
                        }

                        // Return
                        return;

                    }

                    //check if the additional authN method is available. If so, start authN with these creds as well
                    //N: modification for always lanching the root authN process. Comment out the following line
                    //if (KrbAdditionalAuthN) {

                    statusCode = nonKrbAuthentication(request, response, authenticationProcessCls,
                            nonKrbCookies, gsaRefererCookie.getValue(), creds);

                    //check if the status code is indeterminate
                    if (statusCode == -1) {
                        //the process could not determinate the authorization
                        //as there is no pattern that matches with any repository
                        statusCode = HttpServletResponse.SC_UNAUTHORIZED;
                    }

                    // Protection: check status code
                    if (statusCode != HttpServletResponse.SC_OK) {

                        // Raise error
                        response.sendError(statusCode, "Authentication process failed!");

                        // Debug
                        if (logger.isDebugEnabled())
                            logger.debug("Non Krb Authentication process failed with code: " + statusCode);

                        // Return
                        return;

                    }

                    //}

                }
            } else { // end KrbUsrPwdCrawler is set. 
                //If KrbUsrPwdCrawler is not set to true, then do nothing (assume content is feeded)
                //just send back the error as a configuration one (we shouldn't configure Froms-based crawling)
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Configuration error. Review your configuration as you can not define this rule if it's not set properly (see doc on how to set it up using Kerberos config attributes)");
                return;
            }

        } else { //User is not Crawler

            logger.debug("User is NOT crawler");

            //check if we have double AuthN or not
            if (!KrbAdditionalAuthN) {

                logger.debug("Krb silent authN only");

                //set isNegotiate equal true (it authenticates the user thru kerberos ticket)                                                                                    
                isNegotiate = true;

                String refererCookieValue = null;
                if (gsaRefererCookie != null) {
                    refererCookieValue = new String(gsaRefererCookie.getValue());
                }

                //authenticate user
                statusCode = krbAuthentication(request, response, krbAuthN, krbCookies, refererCookieValue,
                        creds, isNegotiate);

                // Protection: check status code
                if (statusCode != HttpServletResponse.SC_OK) {

                    // Raise error
                    response.sendError(statusCode, "Authentication process failed!");

                    // Debug
                    if (logger.isDebugEnabled())
                        logger.debug("Krb Authentication process failed with code: " + statusCode);

                    if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
                        logger.debug(
                                "Note: this 401 could not be an error as sending 401 could be part of the Negotiation process");
                    }

                    // Return
                    return;

                } else {

                    boolean doesKrbSubjectExist = lookForKrbCreds(creds);

                    if (!doesKrbSubjectExist) {
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Credentials not valid. Try to close your browser and try it again");

                        // Log error
                        logger.error("Kerberos Subject is not present when authenticating");

                        // Return
                        return;
                    }

                    //N: call rootAuthN once we have the Kerberos creds
                    //N: Begin update
                    if (!KrbAdditionalAuthN) {
                        statusCode = nonKrbAuthentication(request, response, authenticationProcessCls,
                                nonKrbCookies, refererCookieValue, creds);

                        //check if the status code is indeterminate
                        if (statusCode == -1) {
                            //the process could not determinate the authorization
                            //as there is no pattern that matches with any repository
                            statusCode = HttpServletResponse.SC_UNAUTHORIZED;
                        }

                        // Protection: check status code
                        if (statusCode != HttpServletResponse.SC_OK) {

                            // Raise error
                            response.sendError(statusCode, "Authentication process failed!");

                            // Debug
                            if (logger.isDebugEnabled())
                                logger.debug("Non Krb Authentication process failed with code: " + statusCode);

                            // Return
                            return;
                        }

                    }
                    //N:End update

                }

            } else { //Double AuthN required. So that apart from the Krb silent authN, we authN the user as well thru username and pwd

                logger.debug("Krb and Forms based AuthN mechanisms");

                //check if Krb credentials are already set
                Cookie gsaKrbCookie = getCookie(request, KRB_COOKIE_NAME);

                //if (gsaKrbCookie != null) { //Kerberos cookie set
                if (!isKrbProcess(gsaKrbCookie)) { //Kerberos cookie set    

                    logger.debug("Krb cookie is set. Krb AuthN already in place");

                    Subject krbSubj = getKrbSubject(gsaKrbCookie.getValue());

                    //Protection
                    if (krbSubj == null) { // couldn't localize the subject. 

                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Credentials not valid. Try to close your browser and try it again");

                        // Log error
                        logger.error("Kerberos Subject is not present when authenticating");

                        // Return
                        return;
                    } else {

                        logger.debug("The Krb subject exists. This is the Forms based AuthN part");

                        //check if parameters are present
                        if (request.getParameter("UserIDKrb") == null) {

                            logger.debug("Login page has not been already invoked");

                            String redirectUrl = contructKrbLoginURL();

                            logger.debug("Redirecting to...." + redirectUrl);

                            //redirect to the login page
                            response.sendRedirect(response.encodeRedirectURL(redirectUrl));

                            // Return
                            return;

                        } else {

                            //user already submits credentials
                            logger.debug("User has already sent credentials");

                            createCredsDoubleAuthN(request, creds, krbSubj);

                            logger.debug("User Credentials created. Let's authenticate the user without Krb");

                            statusCode = nonKrbAuthentication(request, response, authenticationProcessCls,
                                    nonKrbCookies, gsaRefererCookie.getValue(), creds);

                            //check if the status code is indeterminate
                            if (statusCode == -1) {
                                //the process could not determinate the authorization
                                //as there is no pattern that matches with any repository
                                statusCode = HttpServletResponse.SC_UNAUTHORIZED;
                            }

                            // Protection: check status code
                            if (statusCode != HttpServletResponse.SC_OK) {

                                // Raise error
                                response.sendError(statusCode, "Authentication process failed!");

                                // Debug
                                if (logger.isDebugEnabled())
                                    logger.debug(
                                            "Non Krb Authentication process failed with code: " + statusCode);

                                // Return
                                return;

                            }
                            boolean resultDelete = deleteKrbSubject(gsaKrbCookie.getValue());
                            if (!resultDelete) {
                                logger.error("Not KrbSubj found when deleting it");
                            }

                        }
                    }

                } else { //Krb cookie does not exist
                    logger.debug(
                            "Krb cookie does not exist. Let's silently authenticate the user thru Krb firstly");
                    logger.debug("Krb silent authN only");

                    //set isNegotiate equal true (it authenticates the user thru kerberos ticket)                                                                                    
                    isNegotiate = true;

                    //authenticate user
                    statusCode = krbAuthentication(request, response, krbAuthN, krbCookies,
                            gsaRefererCookie.getValue(), creds, isNegotiate);

                    // Protection: check status code
                    if (statusCode != HttpServletResponse.SC_OK) {

                        // Raise error
                        response.sendError(statusCode, "Authentication process failed!");

                        // Debug
                        if (logger.isDebugEnabled())
                            logger.debug("Krb Authentication process failed with code: " + statusCode);

                        if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
                            logger.debug(
                                    "Note: this 401 could not be an error as sending 401 could be part of the Negotiation process");
                        }

                        // Return
                        return;

                    } else {
                        Cookie krbCookie = krbCookies.elementAt(0);
                        String krbAuthCookieValue = krbCookie.getValue();

                        logger.debug("Krb cookie value: " + krbAuthCookieValue);
                        if (krbAuthCookieValue == null) {
                            logger.error("Krb cookie not present");
                            // Raise error
                            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Kerberos cookie not present");
                            // Return
                            return;
                        } else {
                            addKrbCookie(response, krbCookie);
                            addKrbSubject(krbAuthCookieValue, krbAuthN.getUserSubject());
                            logger.debug(
                                    "The User Krb identity is already present. Let's authenticate the user thru username/password");
                            //redirect to Login page
                            String redirectUrl = contructKrbLoginURL();
                            response.sendRedirect(response.encodeRedirectURL(redirectUrl));
                            logger.debug("Redirect to.... " + redirectUrl);
                            return;
                        }

                    }

                }

            }
        }

        logger.debug("Krb and/or Forms based AuthN OK. Let's create the session");

        //set username and cookies
        username = creds.getCredential(KRB5_ID).getUsername();

        //creation time var
        long creationTime = System.currentTimeMillis();

        //Setting session values
        sessionID = UserIDEncoder.getID(username, creationTime);
        encodedSessionID = URLEncoder.encode(sessionID, encoder);

        logger.debug("Krb Username is... " + username);

        // setSession                                               
        boolean sessionOk = settingSession(userSession, gsaAuthCookie, creds, username, krbAuthN, creationTime,
                encodedSessionID, krbCookies, nonKrbCookies);

        logger.debug("Session is .... " + sessionOk);

        if (!sessionOk) {
            //SAML
            statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
            response.setStatus(statusCode);

            // Log error
            logger.error("Kerberos Subject has not been created properly");

            // Return
            return;
        } else {
            //Store Session in the Session Map
            sessions.addSession(sessionID, userSession);

            sessions.setMaxSessionAgeMinutes(maxSessionAge);

            if (isSessionEnabled) {
                sessions.setSessionTimeoutMinutes(sessionTimeout);
            } else {
                sessions.setSessionTimeoutMinutes(-1);
            }

            logger.debug("User Session created");

            // Add internal authentication cookie
            response.addCookie(gsaAuthCookie);

            logger.debug("Auth cookie added");

            // Debug
            if (logger.isDebugEnabled())
                logger.debug("Authentication process successful");

            if (!isSAML) {
                // Debug
                if (logger.isDebugEnabled())
                    logger.debug("Redirecting user to: " + gsaRefererCookie.getValue());

                // Redirect
                response.sendRedirect(gsaRefererCookie.getValue());
            } else {
                try {
                    redirectingSAML(response, cookies, sessionID);
                } catch (ValveConfigurationException e) {
                    logger.error("Configuration error: " + e.getMessage(), e);
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }
            }

        }

    } //end of AuthN cases

}

From source file:org.esgf.globusonline.GOauthView3Controller.java

@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView doPost(final HttpServletRequest request) {
    /* get model params here */
    String userCertificate = null;
    String goUserName = null;/*from   ww w .j  a  v a  2s  .com*/
    String target = request.getParameter("path");
    String label = request.getParameter("label");
    String folder = request.getParameter("folder[0]");

    //System.out.println("path from Parameters is: " + target);
    //System.out.println("folder from Parameters is: " + folder);

    String[] endpointInfos = null;
    String endpoint = request.getParameter("endpoint");
    String createdSrcEndpoint = null, createdDestEndpoint = null;

    //if this request comes via go form view 3 we can then obtain the request parameters for myproxy username
    String srcMyproxyUserName = request.getParameter("srcmyproxyuser");
    String srcMyproxyUserPass = request.getParameter("myProxyUserPass");
    String myProxyServerStr = request.getParameter("srcmyproxyserver");

    StringBuffer errorStatus = new StringBuffer("Steps leading up to the error are shown below:<br><br>");

    String auth_code = request.getParameter("code");
    String[] file_urls = null;
    String[] file_names;

    String myproxyServerStr = null;
    String myproxyUserName = null;
    JSONObject goAccessTokenObj = null;
    String goAccessToken = null;
    String userCertificateFile = null;

    Map<String, Object> model = new HashMap<String, Object>();
    //Get the session, so we can retrieve state.
    HttpSession session = request.getSession(false);
    if (session == null) {
    } else {
        if (!(endpoint == null)) {
            session.setAttribute("endpoint", endpoint);
        } else {
            endpoint = (String) session.getAttribute("endpoint");
        }
        if (!(target == null)) {
            session.setAttribute("target", target);
        } else {
            target = (String) session.getAttribute("target");
        }
        if (!(folder == null)) {
            session.setAttribute("folder", folder);
        } else {
            folder = (String) session.getAttribute("folder");
        }
        file_urls = (String[]) session.getAttribute("fileUrls");
        String dataset_id = (String) session.getAttribute("datasetName");
        //System.out.println("Auth3, session id is:" + session.getId());
        //System.out.println("Your dataset name is: " + dataset_id);

        userCertificateFile = (String) session.getAttribute("usercertificatefile");
        if (userCertificateFile.equals("undefined")) {
            userCertificateFile = null;
        }
        goUserName = (String) session.getAttribute("gousername");
        goAccessTokenObj = (JSONObject) session.getAttribute("goaccesstoken");
        try {
            goAccessToken = goAccessTokenObj.getString("access_token");
        } catch (JSONException e) {
            //logger.error("Error getting access_token", e);
            //throw new ValueErrorException();
        }

        myproxyServerStr = (String) session.getAttribute("myproxyServerStr");
        myproxyUserName = (String) session.getAttribute("myproxyUserName");
        //if (!(myproxyUserName == null)){System.out.println("Auth3, myproxyUserName is:" +myproxyUserName);}
        if (srcMyproxyUserPass == null) {
            srcMyproxyUserPass = (String) session.getAttribute("MyproxyUserPass");
        }
    }
    String esg_user = "";
    String esg_password = "";

    try {
        //get the openid here from the cookie
        Cookie[] cookies = request.getCookies();
        String openId = "";
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("esgf.idp.cookie")) {
                openId = cookies[i].getValue();
            }
        }

        LOG.debug("Got User OpenID: " + openId);
        model.put(GOFORMVIEW_OPENID, openId);
        myproxyServerStr = Utils.resolveMyProxyViaOpenID(openId);
        LOG.debug("Using MyProxy Server: " + myproxyServerStr);
        System.out.println("Using MyProxy Server: " + myproxyServerStr);

        ESGFProperties esgfProperties = new ESGFProperties();
        UserInfoDAO uid = new UserInfoDAO(esgfProperties);
        UserInfo userInfo = uid.getUserByOpenid(openId);
        myproxyUserName = userInfo.getUserName();

        LOG.debug("Got MyProxy Username: " + myproxyUserName);
        System.out.println("Got MyProxy Username: " + myproxyUserName);

        if (request.getParameter(GOFORMVIEW_MODEL) != null) {
            //it should never come here...
        } else {
            //do we need this at all?  I don't think so
        }
    } catch (YadisException ye) {
        String eMsg = ye.toString();
        if (eMsg.indexOf("0x702") != -1) {
            model.put(GOFORMVIEW_ERROR, "error");
            model.put(GOFORMVIEW_ERROR_MSG,
                    "Please <a href=\"login\">Login</a>" + " before trying to download data!");
        } else {
            String errorMsg = "Failed to resolve OpenID: " + ye;
            LOG.error("Failed to resolve OpenID: " + ye);
            model.put(GOFORMVIEW_ERROR, "error");
            model.put(GOFORMVIEW_ERROR_MSG, errorMsg + "<br><br>Please make sure that you're"
                    + " logged in as a valid user before trying to download data!<br><br>");
        }
    } catch (Exception e) {
        String errorMsg = "Failed to resolve OpenID: " + e;
        LOG.error("Failed to resolve OpenID: " + e);
        model.put(GOFORMVIEW_ERROR, "error");
        model.put(GOFORMVIEW_ERROR_MSG, errorMsg + "<br><br>Please make sure that you're"
                + " logged in as a valid user before trying to download data!<br><br>");
    }

    if ((userCertificateFile == null || userCertificateFile.isEmpty()) && (srcMyproxyUserPass == null)) {
        //System.out.println("Auth3, srcMyproxyUserPass is null");
        return new ModelAndView("goauthview3", model);
    } else {
        //System.out.println("Auth3, srcMyproxyUserPass is:"); // +srcMyproxyUserPass);
    }
    //LOG.debug("GOFORMView4Controller got Certificate " + userCertificate);
    //LOG.debug("GOFORMView4Controller got Target " + target);
    //LOG.debug("GOFORMView4Controller got selected endpoint " + endpoint);
    //LOG.debug("GOFORMView4Controller got Src Myproxy User " + srcMyproxyUserName);
    //LOG.debug("GOFORMView4Controller got Src Myproxy Pass ******");
    //LOG.debug("GOFORMView4Controller got Src Myproxy Server " + myproxyServerStr);

    //System.out.println("GOFORMView4Controller got Certificate " + userCertificate);
    //System.out.println("GOFORMView4Controller got Target " + target);
    //System.out.println("GOFORMView4Controller got selected endpoint " + endpoint);
    //System.out.println("GOauthView3Controller got Src Myproxy User " + myproxyUserName);
    //System.out.println("GOauthView3Controller got go User " + goUserName);
    //System.out.println("GOFORMView4Controller got Src Myproxy Pass ******");
    // +srcMyproxyUserPass);
    //System.out.println("GOauthView4Controller got Src Myproxy Server " + myproxyServerStr);

    if ((srcMyproxyUserPass != null) || (userCertificateFile == null || userCertificateFile.isEmpty())) {
        try {
            JGOTransfer un = new JGOTransfer(goUserName, myproxyServerStr, myproxyUserName, srcMyproxyUserPass,
                    CA_CERTIFICATE_FILE);
            un.setVerbose(true);
            un.initialize();

            LOG.debug("Globus Online Transfer object Initialize complete");

            //errorStatus.append("Globus Online Transfer object Initialize complete<br>");

            userCertificateFile = un.getUserCertificateFile();
            LOG.debug("Retrieved user credential file: " + userCertificateFile);
            //   System.out.println("Retrieved user credential file: " + userCertificateFile);
            model.put(GOFORMVIEW_USER_CERTIFICATE, userCertificateFile);
        } catch (Exception e) {
            LOG.error("Failed to initialize transfer object to get user cert: " + e);

            //TODO: Iterate back to password page w/ invalid password error
            model.put(GOFORMVIEW_ERROR, "autherror");
            System.out.println("Failed to initialize transfer object to get user cert: " + e);
            return new ModelAndView("goauthview3", model);
        }
    }
    //System.out.println("Retrieved user credential file: " + goUserName + goAccessToken + userCertificateFile + CA_CERTIFICATE_FILE);

    JGOTransfer transfer = new JGOTransfer(goUserName, goAccessToken, CA_CERTIFICATE_FILE);
    transfer.setVerbose(true);
    //If we need to set vs. testing:
    //transfer.setBaseUrl("https://transfer.test.api.globusonline.org/v0.10");

    try {
        String newURL = null, goEP = null;
        String[] pieces = null;

        String[] urlParts = null;
        String urlHost = null;
        int filePathIndex;

        Vector<String> fileList = null;
        HashMap<String, String> sourceEpToGFTPMap = new HashMap<String, String>();
        HashMap<String, Vector<String>> sourceMap = new HashMap<String, Vector<String>>();
        transfer.initialize();

        LOG.debug("About to retrieve available endpoints");
        Vector<EndpointInfo> endpoints = transfer.listEndpoints();
        LOG.debug("We pulled down " + endpoints.size() + " endpoints");
        //System.out.println("We pulled down " + endpoints.size() + " endpoints");
        errorStatus.append("Endpoints retrieved<br>");
        endpointInfos = constructEndpointInfos(endpoints);
        // find the endpointInfo line that matches the endpoint the user selected
        String endpointInfo = Utils.getEndpointInfoFromEndpointStr(endpoint, endpointInfos);
        //System.out.println("User selected endpoint that has the info: " + endpointInfo);
        LOG.debug("User selected endpoint that has the info: " + endpointInfo);

        //boolean isGlobusConnect = endpointInfo.endsWith("true");

        // FIXME: Cache from previous time we called this?
        // or reconstruct from the other format of them that we have?
        Vector<EndpointInfo> goEndpointInfos = transfer.listEndpoints();
        LOG.debug("Got endpointinfo again");

        // first pass, find all sources
        // we create a mapping of GO endpoints to Filelists

        for (String curURL : file_urls) {
            LOG.debug("curURL is:" + curURL);
            //pieces = curURL.split("//");
            pieces = curURL.split("://");
            //splite on :// instead, then the first / will separate host:port from path
            if ((pieces != null) && (pieces.length > 1)) {
                //goEP = Utils.lookupGOEPBasedOnGridFTPURL(pieces[1], goEndpointInfos, true);
                filePathIndex = pieces[1].indexOf("/");
                urlHost = pieces[1].substring(0, filePathIndex);
                LOG.debug("urlHost is " + urlHost + "\n");
                goEP = Utils.lookupGOEPBasedOnGridFTPURL(urlHost, goEndpointInfos, true);

                if (goEP == null) {
                    //goEP = Utils.lookupGOEPBasedOnGridFTPURL(pieces[1], goEndpointInfos, false);
                    goEP = Utils.lookupGOEPBasedOnGridFTPURL(urlHost, goEndpointInfos, true);
                }

                if (!sourceMap.containsKey(goEP)) {
                    //LOG.debug("Mapped GridFTP Server " + pieces[1] + " to GO EP " + goEP);
                    LOG.debug("Mapped GridFTP Server " + pieces[1] + " to GO EP " + goEP);
                    //System.out.println("Mapped GridFTP Server " + pieces[1] + " to GO EP " + goEP);
                    sourceEpToGFTPMap.put(goEP, pieces[1]);
                    sourceMap.put(goEP, new Vector<String>());
                }

                fileList = sourceMap.get(goEP);
                //newURL = "//" + pieces[2];
                //if(pieces.length = 2)
                //newUrl = "//" + pieces[2];
                //shouldn't need to add any leading slashes
                //newURL = "/" + pieces[1].substring(filePathIndex);
                newURL = pieces[1].substring(filePathIndex);

                LOG.debug("Transformed " + curURL + " into " + newURL);
                //System.out.println("Transformed " + curURL + " into " + newURL);
                fileList.add(newURL);
            } else {
                LOG.debug("Failed to split URL on //: " + curURL);
                //System.out.println("Failed to split URL on //: " + curURL);
            }
        }

        // For now we always just grab the first endpoint since we
        // can only handle a single source endpoint (per transfer)
        // ... break up into multiple transfers later when we
        // support transfers of multiple data sets at once
        LOG.debug("Finished Endpoint URL manipulation");
        Map.Entry<String, Vector<String>> entry = sourceMap.entrySet().iterator().next();
        String goSourceEndpoint = entry.getKey();
        Map.Entry<String, String> gftpEntry = sourceEpToGFTPMap.entrySet().iterator().next();
        String gftpServer = gftpEntry.getValue();

        LOG.debug("Got GO Source EP: " + goSourceEndpoint);
        LOG.debug("Got GFTP Server: " + gftpServer);
        if (goSourceEndpoint != null) {
            fileList = entry.getValue();
        } else {
            // create new endpoint using known information
            String srcEndpointInfo = "D^^" + gftpServer + "^^" + myproxyServerStr + "^^false";
            goSourceEndpoint = Utils.createGlobusOnlineEndpointFromEndpointInfo(transfer, goUserName,
                    srcEndpointInfo);
            createdSrcEndpoint = goSourceEndpoint;
        }

        LOG.debug("Using GO Source EP: " + goSourceEndpoint);
        //System.out.println("Using GO Source EP: " + goSourceEndpoint);

        errorStatus.append("Source endpoint resolved as \"");
        errorStatus.append(goSourceEndpoint);
        errorStatus.append("\".<br>");

        // first activate the source endpoint
        LOG.debug("Activating source endpoint " + goSourceEndpoint);
        //System.out.println("Activating source endpoint " + goSourceEndpoint);
        errorStatus.append("Attempting to activate Source Endpoint " + goSourceEndpoint + " ...<br>");
        try {
            // try the activation with the userCertificateFile
            transfer.activateEndpoint(goSourceEndpoint, userCertificateFile);
        } catch (Exception e) {
            //System.out.println("activation w/ userCert failed because:" + e.toString());
            //System.out.println("userCertificateFile:" +userCertificateFile);
            //
            model.put(GOFORMVIEW_ERROR, "crederror");
            //model.put(GOFORMVIEW_ERROR_MSG, error);
            //System.out.println("Failed to initialize transfer object to get user cert: " + e);
            return new ModelAndView("goauthview3", model);
        }
        errorStatus.append("Source Endpoint activated properly!<br>");
        //System.out.println("pSource Endpoint activated properly!<br>");

        String[] endpointPieces = endpointInfo.split("\\^\\^");
        String destEPName = endpointPieces[0];

        // kick off the transfer here!
        errorStatus.append("Attempting to start Globus Online Transfer ...<br>");

        String destpath = target + folder;
        //System.out.println("destpath is" + destpath);
        //System.out.println("goSourceEndpoint is" + goSourceEndpoint);
        //System.out.println("destEPName is" + destEPName);
        //System.out.println("fileList is" + fileList);

        //Need to modify JGOClient to pass label along
        String taskID = transfer.transfer(goSourceEndpoint, destEPName, fileList, destpath);
        if (taskID != null) {
            errorStatus.append("Globus Online Transfer got TaskID " + taskID + ".<br>");
            String transferInfo1 = "The transfer has been accepted and a task has been "
                    + "created and queued for execution.";
            String transferInfo2 = "Globus Online TaskID: " + taskID;
            LOG.debug("Started Globus Online transfer with TaskID: " + taskID);

            if (request.getParameter(GOFORMVIEW_MODEL) != null) {
            } else {
                model.put(GOFORMVIEW_TRANSFER_INFO1, transferInfo1);
                model.put(GOFORMVIEW_TRANSFER_INFO2, transferInfo2);
            }
        } else {
            String error = errorStatus.toString() + "<br><b>Main Error:</b><br><br>Transfer failed";
            model.put(GOFORMVIEW_ERROR, "error");
            model.put(GOFORMVIEW_ERROR_MSG, error);
            LOG.error("Failed to initiate Globus Online transfer.");
        }
    } catch (Exception e) {
        String error = errorStatus.toString() + "<br><b>Main Error:</b><br><br>" + e.toString();
        model.put(GOFORMVIEW_ERROR, "error");
        model.put(GOFORMVIEW_ERROR_MSG, error);
        LOG.error("Failed to initialize Globus Online: " + e);

        System.out.println("Trying to teardown created source endpoints ...");
        if (createdSrcEndpoint != null) {
            try {
                transfer.removeEndpoint(createdSrcEndpoint);
            } catch (Exception e1) {
            }
        }
        if (createdDestEndpoint != null) {
            try {
                transfer.removeEndpoint(createdDestEndpoint);
            } catch (Exception e2) {
            }
        }
        System.out.println("Attempted endpoint removal complete");
    }
    //make sure we put the cert back in the model so we can reuse it
    model.put(GOFORMVIEW_USER_CERTIFICATE, userCertificateFile);
    return new ModelAndView("goauth_transfer", model);
}

From source file:com.joseflavio.uxiamarelo.servlet.UxiAmareloServlet.java

@Override
protected void doPost(HttpServletRequest requisicao, HttpServletResponse resposta)
        throws ServletException, IOException {

    String tipo = requisicao.getContentType();
    if (tipo == null || tipo.isEmpty())
        tipo = "text/plain";

    String codificacao = requisicao.getCharacterEncoding();
    if (codificacao == null || codificacao.isEmpty())
        codificacao = "UTF-8";

    resposta.setCharacterEncoding(codificacao);
    PrintWriter saida = resposta.getWriter();

    try {// w w  w. ja  v  a 2  s .  co m

        JSON json;

        if (tipo.contains("json")) {
            json = new JSON(IOUtils.toString(requisicao.getInputStream(), codificacao));
        } else {
            json = new JSON();
        }

        Enumeration<String> parametros = requisicao.getParameterNames();

        while (parametros.hasMoreElements()) {
            String chave = parametros.nextElement();
            String valor = URLDecoder.decode(requisicao.getParameter(chave), codificacao);
            json.put(chave, valor);
        }

        if (tipo.contains("multipart")) {

            Collection<Part> arquivos = requisicao.getParts();

            if (!arquivos.isEmpty()) {

                File diretorio = new File(uxiAmarelo.getDiretorio());

                if (!diretorio.isAbsolute()) {
                    diretorio = new File(requisicao.getServletContext().getRealPath("") + File.separator
                            + uxiAmarelo.getDiretorio());
                }

                if (!diretorio.exists())
                    diretorio.mkdirs();

                String diretorioStr = diretorio.getAbsolutePath();

                String url = uxiAmarelo.getDiretorioURL();

                if (uxiAmarelo.isDiretorioURLRelativo()) {
                    String url_esquema = requisicao.getScheme();
                    String url_servidor = requisicao.getServerName();
                    int url_porta = requisicao.getServerPort();
                    String url_contexto = requisicao.getContextPath();
                    url = url_esquema + "://" + url_servidor + ":" + url_porta + url_contexto + "/" + url;
                }

                if (url.charAt(url.length() - 1) == '/') {
                    url = url.substring(0, url.length() - 1);
                }

                Map<String, List<JSON>> mapa_arquivos = new HashMap<>();

                for (Part arquivo : arquivos) {

                    String chave = arquivo.getName();
                    String nome_original = getNome(arquivo, codificacao);
                    String nome = nome_original;

                    if (nome == null || nome.isEmpty()) {
                        try (InputStream is = arquivo.getInputStream()) {
                            String valor = IOUtils.toString(is, codificacao);
                            valor = URLDecoder.decode(valor, codificacao);
                            json.put(chave, valor);
                            continue;
                        }
                    }

                    if (uxiAmarelo.getArquivoNome().equals("uuid")) {
                        nome = UUID.randomUUID().toString();
                    }

                    while (new File(diretorioStr + File.separator + nome).exists()) {
                        nome = UUID.randomUUID().toString();
                    }

                    arquivo.write(diretorioStr + File.separator + nome);

                    List<JSON> lista = mapa_arquivos.get(chave);

                    if (lista == null) {
                        lista = new LinkedList<>();
                        mapa_arquivos.put(chave, lista);
                    }

                    lista.add((JSON) new JSON().put("nome", nome_original).put("endereco", url + "/" + nome));

                }

                for (Entry<String, List<JSON>> entrada : mapa_arquivos.entrySet()) {
                    List<JSON> lista = entrada.getValue();
                    if (lista.size() > 1) {
                        json.put(entrada.getKey(), lista);
                    } else {
                        json.put(entrada.getKey(), lista.get(0));
                    }
                }

            }

        }

        String copaiba = (String) json.remove("copaiba");
        if (StringUtil.tamanho(copaiba) == 0) {
            throw new IllegalArgumentException("copaiba = nome@classe@metodo");
        }

        String[] copaibaParam = copaiba.split("@");
        if (copaibaParam.length != 3) {
            throw new IllegalArgumentException("copaiba = nome@classe@metodo");
        }

        String comando = (String) json.remove("uxicmd");
        if (StringUtil.tamanho(comando) == 0)
            comando = null;

        if (uxiAmarelo.isCookieEnviar()) {
            Cookie[] cookies = requisicao.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    String nome = cookie.getName();
                    if (uxiAmarelo.cookieBloqueado(nome))
                        continue;
                    if (!json.has(nome)) {
                        try {
                            json.put(nome, URLDecoder.decode(cookie.getValue(), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            json.put(nome, cookie.getValue());
                        }
                    }
                }
            }
        }

        if (uxiAmarelo.isEncapsulamentoAutomatico()) {
            final String sepstr = uxiAmarelo.getEncapsulamentoSeparador();
            final char sep0 = sepstr.charAt(0);
            for (String chave : new HashSet<>(json.keySet())) {
                if (chave.indexOf(sep0) == -1)
                    continue;
                String[] caminho = chave.split(sepstr);
                if (caminho.length > 1) {
                    Util.encapsular(caminho, json.remove(chave), json);
                }
            }
        }

        String resultado;

        if (comando == null) {
            try (CopaibaConexao cc = uxiAmarelo.conectarCopaiba(copaibaParam[0])) {
                resultado = cc.solicitar(copaibaParam[1], json.toString(), copaibaParam[2]);
                if (resultado == null)
                    resultado = "";
            }
        } else if (comando.equals("voltar")) {
            resultado = json.toString();
            comando = null;
        } else {
            resultado = "";
        }

        if (comando == null) {

            resposta.setStatus(HttpServletResponse.SC_OK);
            resposta.setContentType("application/json");

            saida.write(resultado);

        } else if (comando.startsWith("redirecionar")) {

            resposta.sendRedirect(Util.obterStringDeJSON("redirecionar", comando, resultado));

        } else if (comando.startsWith("base64")) {

            String url = comando.substring("base64.".length());

            resposta.sendRedirect(url + Base64.getUrlEncoder().encodeToString(resultado.getBytes("UTF-8")));

        } else if (comando.startsWith("html_url")) {

            HttpURLConnection con = (HttpURLConnection) new URL(
                    Util.obterStringDeJSON("html_url", comando, resultado)).openConnection();
            con.setRequestProperty("User-Agent", "Uxi-amarelo");

            if (con.getResponseCode() != HttpServletResponse.SC_OK)
                throw new IOException("HTTP = " + con.getResponseCode());

            resposta.setStatus(HttpServletResponse.SC_OK);
            resposta.setContentType("text/html");

            try (InputStream is = con.getInputStream()) {
                saida.write(IOUtils.toString(is));
            }

            con.disconnect();

        } else if (comando.startsWith("html")) {

            resposta.setStatus(HttpServletResponse.SC_OK);
            resposta.setContentType("text/html");

            saida.write(Util.obterStringDeJSON("html", comando, resultado));

        } else {

            throw new IllegalArgumentException(comando);

        }

    } catch (Exception e) {

        resposta.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resposta.setContentType("application/json");

        saida.write(Util.gerarRespostaErro(e).toString());

    }

    saida.flush();

}

From source file:fi.hoski.web.forms.RaceEntryServlet.java

/**
 * Handles the HTTP/*  w w w .  j a  v a2  s . c  om*/
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        String raceFleetKeyStr = request.getParameter("RaceFleetKey");
        if (raceFleetKeyStr == null) {
            throw new ServletException("no RaceFleetKey");
        }
        Key raceFleetKey = KeyFactory.stringToKey(raceFleetKeyStr);
        Entity raceFleetEntity = datastore.get(raceFleetKey);
        Key raceSeriesKey = raceFleetKey.getParent();
        Entity raceseriesEntity = datastore.get(raceSeriesKey);
        RaceSeries raceSeries = (RaceSeries) entities.newInstance(raceseriesEntity);
        RaceFleet raceFleet = (RaceFleet) entities.newInstance(raceFleetEntity);
        RaceEntry raceEntry = new RaceEntry(raceFleet);
        raceEntry.populate(request.getParameterMap());

        String fn = request.getParameter(RaceEntry.FIRSTNAME);
        String ln = request.getParameter(RaceEntry.LASTNAME);
        raceEntry.set(RaceEntry.HELMNAME, fn + " " + ln);

        String sa = request.getParameter(RaceEntry.STREETADDRESS);
        String zc = request.getParameter(RaceEntry.ZIPCODE);
        String ct = request.getParameter(RaceEntry.CITY);
        String cn = request.getParameter(RaceEntry.COUNTRY);
        if (cn == null || cn.isEmpty()) {
            raceEntry.set(RaceEntry.HELMADDRESS, sa + ", " + zc + " " + ct);
        } else {
            raceEntry.set(RaceEntry.HELMADDRESS, sa + ", " + zc + " " + ct + ", " + cn);
        }

        Day closingDay = (Day) raceSeries.get(RaceSeries.ClosingDate);
        Number fee = 0.0;
        if (closingDay != null) {
            Day now = new Day();
            if (closingDay.before(now)) {
                fee = (Number) raceFleet.get(RaceFleet.Fee2);
            } else {
                fee = (Number) raceFleet.get(RaceFleet.Fee);
            }
        }
        Boolean clubDiscount = (Boolean) raceSeries.get(RaceSeries.CLUBDISCOUNT);
        String clubname = repositoryBundle.getString("Clubname");
        if (clubDiscount != null && clubDiscount
                && clubname.equalsIgnoreCase("" + raceEntry.get(RaceEntry.CLUB))) {
            fee = new Double(0);
        }
        raceEntry.set(RaceEntry.FEE, fee);
        raceEntry.set(RaceEntry.TIMESTAMP, new Date());

        entities.put(raceEntry);

        String payingInstructions = "";
        String payingInstructionsHtml = "";
        BankingBarcode bb = races.getBarcode(raceEntry);
        if (bb != null) {
            Day dueDay = new Day(bb.getDueDate());
            String payingFormat = EntityReferences.encode(msg(Messages.RACEENTRYPAYING), "UTF-8");
            String bic = EntityReferences.encode(msg(Messages.RACEBIC), "UTF-8");
            payingInstructions = String.format(payingFormat, bb.toString(), // 1 = barcode
                    bb.getAccount().getIBAN(), // 2 = account
                    bb.getReference().toFormattedRFString(), // 3 = ref
                    dueDay, // 4 = due date
                    String.format("%.2f", bb.getTotal()), // 5 = total
                    bic // 6 = bic
            );
            payingInstructionsHtml = String.format(payingFormat.replace("\n", "<br>"),
                    "<span id='barcode'>" + bb.toString() + "</span>", // 1 = barcode
                    "<span id='iban'>" + bb.getAccount().getIBAN() + "</span>", // 2 = account
                    "<span id='rf'>" + bb.getReference().toFormattedRFString() + "</span>", // 3 = ref
                    "<span id='due'>" + dueDay + "</span>", // 4 = due date
                    "<span id='fee'>" + String.format("%.2f", bb.getTotal()) + "</span>", // 5 = total
                    "<span id='bic'>" + bic + "</span>" // 6 = bic
            );
        }
        URL base = new URL(request.getRequestURL().toString());
        URL barcodeUrl = new URL(base, "/races/code128.html?ancestor=" + raceEntry.createKeyString());
        String name = (String) raceEntry.get(RaceEntry.HELMNAME);
        String email = (String) raceEntry.get(RaceEntry.HELMEMAIL);
        String confirmation = msg(Messages.RACEENTRYCONFIRMATION);
        String plainMessage = "";
        String htmlMessage = "<html><head></head><body>" + EntityReferences.encode(confirmation)
                + payingInstructionsHtml + raceEntry.getFieldsAsHtmlTable() + "<iframe src="
                + barcodeUrl.toString() + "/>" + "</body></html>";
        if (email != null) {
            InternetAddress recipient = new InternetAddress(email, name);
            String senderStr = msg(Messages.RACEENTRYFROMADDRESS);
            InternetAddress sender;
            try {
                sender = new InternetAddress(senderStr);
                plainMessage = confirmation + "\n" + payingInstructions + "\n" + raceEntry.getFields();

                String subject = msg(Messages.RACEENTRYSUBJECT);
                mailService.sendMail(sender, subject, plainMessage, htmlMessage, recipient);
            } catch (Exception ex) {
                log(senderStr, ex);
            }
        }
        Cookie cookie = null;
        Cookie[] cookies = null;
        if (useCookies) {
            cookies = request.getCookies();
        }
        if (cookies != null) {
            for (Cookie ck : cookies) {
                if (COOKIENAME.equals(ck.getName())) {
                    cookie = ck;
                }
            }
        }
        JSONObject json = null;
        if (useCookies && cookie != null) {
            Base64 decoder = new Base64();
            String str = new String(decoder.decode(cookie.getValue()));
            json = new JSONObject(str);
        } else {
            json = new JSONObject();
        }
        for (Map.Entry<String, String[]> entry : ((Map<String, String[]>) request.getParameterMap())
                .entrySet()) {
            String property = entry.getKey();
            String[] values = entry.getValue();
            if (values.length == 1) {
                json.put(property, values[0]);
            }
        }
        Base64 encoder = new Base64();
        String base64 = encoder.encodeAsString(json.toString().getBytes("UTF-8"));
        if (useCookies) {
            if (cookie == null) {
                cookie = new Cookie(COOKIENAME, base64);
                cookie.setPath("/");
                cookie.setMaxAge(400 * 24 * 60 * 60);
            } else {
                cookie.setValue(base64);
            }
            response.addCookie(cookie);
        }
        sendError(response, HttpServletResponse.SC_OK,
                "<div id=\"" + raceEntry.createKeyString() + "\">Ok</div>");
    } catch (JSONException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "<div id=\"eJSON\">Internal error.</div>");
    } catch (EntityNotFoundException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "<div id=\"eEntityNotFound\">Internal error.</div>");
    } catch (NumberFormatException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eNumberFormat\">Number error.</div>");
    }
}

From source file:com.zimbra.cs.service.ExternalUserProvServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String param = req.getParameter("p");
    if (param == null) {
        throw new ServletException("request missing param");
    }//from w  w  w .ja  v a  2s  .co m
    Map<Object, Object> tokenMap = validatePrelimToken(param);
    Map<String, String> reqHeaders = new HashMap<String, String>();
    String ownerId = (String) tokenMap.get("aid");
    String folderId = (String) tokenMap.get("fid");
    String extUserEmail = (String) tokenMap.get("email");

    Provisioning prov = Provisioning.getInstance();
    Account grantee;
    try {
        Account owner = prov.getAccountById(ownerId);
        Domain domain = prov.getDomain(owner);
        grantee = prov.getAccountByName(mapExtEmailToAcctName(extUserEmail, domain));
        if (grantee == null) {
            // external virtual account not created yet
            if (prov.isOctopus() && DebugConfig.skipVirtualAccountRegistrationPage) {
                // provision using 'null' password and display name
                // UI will ask the user to set these post provisioning
                provisionVirtualAccountAndRedirect(req, resp, null, null, ownerId, extUserEmail);
            } else {
                resp.addCookie(new Cookie("ZM_PRELIM_AUTH_TOKEN", param));
                req.setAttribute("extuseremail", extUserEmail);
                if (WebClientServiceUtil.isServerInSplitMode()) {
                    reqHeaders.put("extuseremail", extUserEmail);
                    reqHeaders.put("ZM_PRELIM_AUTH_TOKEN", param);
                    String htmlresp = WebClientServiceUtil
                            .sendServiceRequestToOneRandomUiNode(EXT_USER_PROV_ON_UI_NODE, reqHeaders);
                    resp.getWriter().print(htmlresp);
                } else {
                    ServletContext context = getServletContext().getContext("/zimbra");
                    if (context != null) {
                        RequestDispatcher dispatcher = context.getRequestDispatcher(PUBLIC_EXTUSERPROV_JSP);
                        dispatcher.forward(req, resp);
                    } else {
                        logger.warn("Could not access servlet context url /zimbra");
                        throw ServiceException.TEMPORARILY_UNAVAILABLE();
                    }
                }
            }
        } else {
            // create a new mountpoint in the external user's mailbox if not already created

            String[] sharedItems = owner.getSharedItem();
            int sharedFolderId = Integer.valueOf(folderId);
            String sharedFolderPath = null;
            MailItem.Type sharedFolderView = null;
            for (String sharedItem : sharedItems) {
                ShareInfoData sid = AclPushSerializer.deserialize(sharedItem);
                if (sid.getItemId() == sharedFolderId && extUserEmail.equalsIgnoreCase(sid.getGranteeId())) {
                    sharedFolderPath = sid.getPath();
                    sharedFolderView = sid.getFolderDefaultViewCode();
                    break;
                }
            }
            if (sharedFolderPath == null) {
                throw new ServletException("share not found");
            }
            String mountpointName = getMountpointName(owner, grantee, sharedFolderPath);

            ZMailbox.Options options = new ZMailbox.Options();
            options.setNoSession(true);
            options.setAuthToken(AuthProvider.getAuthToken(grantee).toZAuthToken());
            options.setUri(AccountUtil.getSoapUri(grantee));
            ZMailbox zMailbox = new ZMailbox(options);
            ZMountpoint zMtpt = null;
            try {
                zMtpt = zMailbox.createMountpoint(String.valueOf(getMptParentFolderId(sharedFolderView, prov)),
                        mountpointName, ZFolder.View.fromString(sharedFolderView.toString()),
                        ZFolder.Color.DEFAULTCOLOR, null, ZMailbox.OwnerBy.BY_ID, ownerId,
                        ZMailbox.SharedItemBy.BY_ID, folderId, false);
            } catch (ServiceException e) {
                logger.debug("Error in attempting to create mountpoint. Probably it already exists.", e);
            }
            if (zMtpt != null) {
                if (sharedFolderView == MailItem.Type.APPOINTMENT) {
                    // make sure that the mountpoint is checked in the UI by default
                    FolderActionSelector actionSelector = new FolderActionSelector(zMtpt.getId(), "check");
                    FolderActionRequest actionRequest = new FolderActionRequest(actionSelector);
                    try {
                        zMailbox.invokeJaxb(actionRequest);
                    } catch (ServiceException e) {
                        logger.warn("Error in invoking check action on calendar mountpoint", e);
                    }
                }
                HashSet<MailItem.Type> types = new HashSet<MailItem.Type>();
                types.add(sharedFolderView);
                enableAppFeatures(grantee, types);
            }

            // check if the external user is already logged-in
            String zAuthTokenCookie = null;
            javax.servlet.http.Cookie cookies[] = req.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("ZM_AUTH_TOKEN")) {
                        zAuthTokenCookie = cookie.getValue();
                        break;
                    }
                }
            }
            AuthToken zAuthToken = null;
            if (zAuthTokenCookie != null) {
                try {
                    zAuthToken = AuthProvider.getAuthToken(zAuthTokenCookie);
                } catch (AuthTokenException ignored) {
                    // auth token is not valid
                }
            }
            if (zAuthToken != null && !zAuthToken.isExpired() && zAuthToken.isRegistered()
                    && grantee.getId().equals(zAuthToken.getAccountId())) {
                // external virtual account already logged-in
                resp.sendRedirect("/");
            } else if (prov.isOctopus() && !grantee.isVirtualAccountInitialPasswordSet()
                    && DebugConfig.skipVirtualAccountRegistrationPage) {
                // seems like the virtual user did not set his password during his last visit, after an account was
                // provisioned for him
                setCookieAndRedirect(req, resp, grantee);
            } else {
                req.setAttribute("virtualacctdomain", domain.getName());
                if (WebClientServiceUtil.isServerInSplitMode()) {
                    reqHeaders.put("virtualacctdomain", domain.getName());
                    String htmlresp = WebClientServiceUtil
                            .sendServiceRequestToOneRandomUiNode(PUBLIC_LOGIN_ON_UI_NODE, reqHeaders);
                    resp.getWriter().print(htmlresp);
                } else {
                    RequestDispatcher dispatcher = getServletContext().getContext("/zimbra")
                            .getRequestDispatcher(PUBLIC_LOGIN_JSP);
                    dispatcher.forward(req, resp);
                }
            }
        }
    } catch (ServiceException e) {
        throw new ServletException(e);
    }
}

From source file:com.lp.webapp.zemecs.CommandZE.java

public synchronized String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {

    super.execute(request, response);

    if (request.getCookies() != null) {
        for (int i = 0; i < request.getCookies().length; i++) {
            Cookie cookie = request.getCookies()[i];
            cookie.setMaxAge(10000000);//from  w  w  w . j  a  va  2s  . c o  m
            response.addCookie(cookie);
        }
    }

    String mandant = request.getParameter("mandant");

    Locale localeLogon = getMandantFac().getLocaleDesHauptmandanten();

    String locale = request.getParameter("locale");

    String localeCookie = getCookieValue("locale", request);

    if (localeCookie != null && localeCookie.length() > 3) {
        locale = localeCookie;
    }

    if (locale != null && locale.length() > 3) {
        localeLogon = new Locale(locale.substring(0, 2), locale.substring(2, 4));
    }

    TheClientDto theclientDto = null;
    synchronized (mutex) {
        theclientDto = getLogonFac().logon(Helper.getFullUsername(sUser),
                Helper.getMD5Hash((sUser + new String("lpwebappzemecs")).toCharArray()), localeLogon, null,
                null, new Timestamp(System.currentTimeMillis()));

        if (mandant != null && mandant.length() > 0) {

            theclientDto = getLogonFac().logon(Helper.getFullUsername(sUser),
                    Helper.getMD5Hash((sUser + "lpwebappzemecs").toCharArray()), localeLogon, mandant,
                    theclientDto, new Timestamp(System.currentTimeMillis()));
        } else {
            BenutzerDto benutzerDto = getBenutzerFac().benutzerFindByCBenutzerkennung("lpwebappzemecs",
                    new String(Helper.getMD5Hash("lpwebappzemecs" + "lpwebappzemecs")));
            mandant = benutzerDto.getMandantCNrDefault();
        }
    }

    getTheClient(request, response).setTheClientDto(theclientDto);

    if (command.equals(TheApp.CMD_ZE_BDESTATION)) {
        String ausweis = request.getParameter("ausweis");
        getTheClient(request, response).setSMsg("");

        if (ausweis != null && ausweis.length() > 1) {
            // Personal suchen
            PersonalDto personalDto = getPersonalFac().personalFindByCAusweis(ausweis.substring(2));
            if (personalDto != null) {
                personalDto.setPartnerDto(
                        getPartnerFac().partnerFindByPrimaryKey(personalDto.getPartnerIId(), theclientDto));

                HashMap<String, Serializable> hmParameter = new HashMap<String, Serializable>();
                ZeitdatenDto zeitdatenDto = new ZeitdatenDto();
                zeitdatenDto.setCWowurdegebucht("BDE-Station " + request.getRemoteHost());
                zeitdatenDto.setPersonalIId(personalDto.getIId());
                hmParameter.put("zeitdaten", zeitdatenDto);
                hmParameter.put("person", personalDto.getPartnerDto().formatFixTitelName1Name2());
                getTheClient(request, response).setData(hmParameter);
                setSJSPNext("bdestation2.jsp");
                return getSJSPNext();
            } else {
                getTheClient(request, response)
                        .setSMsg("Ausweis " + ausweis + " bei diesem Mandanten nicht gefunden! ");
            }
        } else {
            getTheClient(request, response).setSMsg("");
        }
    }
    if (command.equals(TheApp.CMD_ZE_BDESTATION2)) {

        HashMap<String, Serializable> hmParameter = (HashMap<String, Serializable>) getTheClient(request,
                response).getData();
        ZeitdatenDto zeitdatenDto = (ZeitdatenDto) hmParameter.get("zeitdaten");
        zeitdatenDto.setTZeit(new Timestamp(System.currentTimeMillis()));

        String option = request.getParameter("option");
        getTheClient(request, response).setSMsg("");

        ParametermandantDto parameterBdeMitTaetigkeitDto = getParameterFac().getMandantparameter(mandant,
                ParameterFac.KATEGORIE_PERSONAL, ParameterFac.PARAMETER_BDE_MIT_TAETIGKEIT);

        Boolean bBdeMitTaetigkeit = (Boolean) parameterBdeMitTaetigkeitDto.getCWertAsObject();
        com.lp.server.artikel.service.ArtikelDto artikelDtoDefaultArbeiztszeit = null;

        if (bBdeMitTaetigkeit == false) {
            ParametermandantDto parameterDtoDefaultarbeitszeit = getParameterFac().getMandantparameter(mandant,
                    ParameterFac.KATEGORIE_ALLGEMEIN, ParameterFac.PARAMETER_DEFAULT_ARBEITSZEITARTIKEL);

            if (parameterDtoDefaultarbeitszeit != null && parameterDtoDefaultarbeitszeit.getCWert() != null
                    && !parameterDtoDefaultarbeitszeit.getCWert().trim().equals("")) {
                try {
                    artikelDtoDefaultArbeiztszeit = getArtikelFac()
                            .artikelFindByCNr(parameterDtoDefaultarbeitszeit.getCWert(), theclientDto);
                    zeitdatenDto.setArtikelIId(artikelDtoDefaultArbeiztszeit.getIId());

                } catch (RemoteException ex2) {
                    myLogger.error("Default-Arbeitszeitartikel " + parameterDtoDefaultarbeitszeit.getCWert()
                            + " nicht vorhanden.", ex2);
                    setSJSPNext("bdestation.jsp");
                    return getSJSPNext();
                }

            } else {
                myLogger.error("Default-Arbeitszeitartikel " + parameterDtoDefaultarbeitszeit.getCWert()
                        + " nicht definiert.");
                setSJSPNext("bdestation.jsp");
                return getSJSPNext();
            }
        }

        if (option != null && option.length() > 2) {

            // Auftrag
            if (option.substring(0, 2).equals("$A") || option.substring(0, 3).equals("$EA")) {
                try {

                    ParametermandantDto parameterDto = getParameterFac().getMandantparameter(mandant,
                            ParameterFac.KATEGORIE_ALLGEMEIN,
                            ParameterFac.PARAMETER_BELEGNUMMERNFORMAT_STELLEN_GESCHAEFTSJAHR);

                    if (parameterDto != null) {
                        if (parameterDto.getCWert() != null && parameterDto.getCWert().equals("4")) {
                            if (option.charAt(4) == 47) {
                                option = "$A"
                                        + Helper.konvertiereDatum2StelligAuf4Stellig(option.substring(2, 4))
                                        + option.substring(4);
                            }
                        }
                    }
                    AuftragDto auftragDto = null;
                    if (option.substring(0, 2).equals("$A")) {

                        auftragDto = getAuftragFac().auftragFindByMandantCNrCNr(mandant, option.substring(2),
                                theclientDto);
                    } else {
                        auftragDto = getAuftragFac().auftragFindByMandantCNrCNr(mandant, option.substring(3),
                                theclientDto);

                    }

                    AuftragpositionDto[] auftragpositionDtos = getAuftragpositionFac()
                            .auftragpositionFindByAuftrag(auftragDto.getIId());

                    if (auftragDto.getAuftragstatusCNr()
                            .equals(com.lp.server.auftrag.service.AuftragServiceFac.AUFTRAGSTATUS_ERLEDIGT)) {
                        setSJSPNext("bdestation.jsp");
                        getTheClient(request, response).setSMsg("Auf Auftrag " + option.substring(2)
                                + " mit Status " + auftragDto.getAuftragstatusCNr().trim()
                                + " darf nicht gebucht werden! ");
                        return getSJSPNext();
                    } else {
                        if (auftragpositionDtos != null && auftragpositionDtos.length > 0) {
                            zeitdatenDto.setIBelegartpositionid(auftragpositionDtos[0].getIId());
                            zeitdatenDto.setIBelegartid(auftragpositionDtos[0].getBelegIId());
                            zeitdatenDto.setCBelegartnr(LocaleFac.BELEGART_AUFTRAG);
                            hmParameter.put("beleg", "A" + option.substring(2));

                            MaschineDto maschineDto = new MaschineDto();
                            maschineDto.setCBez("");
                            hmParameter.put("maschine", maschineDto);

                            if (option.substring(0, 2).equals("$A")) {

                                if (bBdeMitTaetigkeit == false) {
                                    setSJSPNext("bdestation.jsp");
                                    getTheClient(request, response).setSMsg(
                                            getMeldungGebuchtFuerBDE(getTheClient(request, response).getData(),
                                                    artikelDtoDefaultArbeiztszeit.getCNr(), theclientDto));

                                    getZeiterfassungsFac().createZeitdaten(zeitdatenDto, true, true, false,
                                            theclientDto);
                                    return getSJSPNext();

                                } else {
                                    setSJSPNext("bdestation4.jsp");
                                }
                            } else {
                                hmParameter.put("beleg", "A" + option.substring(3));
                                setSJSPNext("bdestation3gutschlecht.jsp");

                            }

                            return getSJSPNext();
                        } else {
                            getTheClient(request, response)
                                    .setSMsg("Auftrag " + option.substring(2) + " hat keine Positionen! ");
                            setSJSPNext("bdestation.jsp");
                            return getSJSPNext();
                        }
                    }

                } catch (EJBExceptionLP ex) {
                    getTheClient(request, response).setSMsg(
                            "Auftrag '" + option.substring(2) + "' bei diesem Mandanten nicht gefunden! ");
                    setSJSPNext("bdestation.jsp");
                    return getSJSPNext();
                }
            } // Los
            else if (option.substring(0, 2).equals("$L") || option.substring(0, 3).equals("$EL")) {
                try {

                    ParametermandantDto parameterDto = getParameterFac().getMandantparameter(mandant,
                            ParameterFac.KATEGORIE_ALLGEMEIN,
                            ParameterFac.PARAMETER_BELEGNUMMERNFORMAT_STELLEN_GESCHAEFTSJAHR);

                    if (parameterDto != null) {
                        if (parameterDto.getCWert() != null && parameterDto.getCWert().equals("4")) {
                            if (option.charAt(4) == 47) {
                                option = "$L"
                                        + Helper.konvertiereDatum2StelligAuf4Stellig(option.substring(2, 4))
                                        + option.substring(4);
                            }
                        }
                    }

                    com.lp.server.fertigung.service.LosDto losDto = null;

                    if (option.substring(0, 2).equals("$L")) {
                        losDto = getFertigungFac().losFindByCNrMandantCNr(option.substring(2), mandant);

                    } else {
                        losDto = getFertigungFac().losFindByCNrMandantCNr(option.substring(3), mandant);

                    }

                    // WH 18-01-2006: Los benoetigt keine Positionen

                    if (losDto.getStatusCNr()
                            .equals(com.lp.server.fertigung.service.FertigungFac.STATUS_ANGELEGT)
                            || losDto.getStatusCNr()
                                    .equals(com.lp.server.fertigung.service.FertigungFac.STATUS_AUSGEGEBEN)
                            || losDto.getStatusCNr()
                                    .equals(com.lp.server.fertigung.service.FertigungFac.STATUS_GESTOPPT)
                            || losDto.getStatusCNr()
                                    .equals(com.lp.server.fertigung.service.FertigungFac.STATUS_ERLEDIGT)
                            || losDto.getStatusCNr()
                                    .equals(com.lp.server.fertigung.service.FertigungFac.STATUS_STORNIERT)) {
                        getTheClient(request, response)
                                .setSMsg("Auf Los " + option.substring(2) + " mit Status "
                                        + losDto.getStatusCNr().trim() + " darf nicht gebucht werden! ");
                        setSJSPNext("bdestation.jsp");
                        return getSJSPNext();
                    } else {
                        zeitdatenDto.setIBelegartid(losDto.getIId());
                        zeitdatenDto.setCBelegartnr(LocaleFac.BELEGART_LOS);

                        if (option.substring(0, 2).equals("$L")) {

                            hmParameter.put("beleg", "L" + option.substring(2));

                            if (bBdeMitTaetigkeit == false) {
                                setSJSPNext("bdestation.jsp");
                                getTheClient(request, response).setSMsg(
                                        getMeldungGebuchtFuerBDE(getTheClient(request, response).getData(),
                                                artikelDtoDefaultArbeiztszeit.getCNr(), theclientDto));

                                getZeiterfassungsFac().createZeitdaten(zeitdatenDto, true, true, true,
                                        theclientDto);
                                return getSJSPNext();
                            } else {
                                setSJSPNext("bdestation3.jsp");
                            }
                        } else {
                            hmParameter.put("beleg", "L" + option.substring(3));
                            setSJSPNext("bdestation3gutschlecht.jsp");
                        }

                        return getSJSPNext();

                    }
                } catch (EJBExceptionLP ex) {
                    getTheClient(request, response)
                            .setSMsg("Los '" + option.substring(2) + "' bei diesem Mandanten nicht gefunden! ");
                    setSJSPNext("bdestation.jsp");
                    return getSJSPNext();
                }

            } // Kombi-Code
            else if (option.length() > 1 && option.substring(0, 2).equals("$V")) {
                setSJSPNext("bdestation.jsp");

                if (option.length() < 12) {

                    getTheClient(request, response).setSMsg("Kombicode muss 10-Stellig sein ");
                    return getSJSPNext();
                }

                try {

                    ParametermandantDto parameter = getParameterFac().getMandantparameter(
                            theclientDto.getMandant(), ParameterFac.KATEGORIE_FERTIGUNG,
                            ParameterFac.PARAMETER_LOSNUMMER_AUFTRAGSBEZOGEN);
                    int iVerlaengerungLosnummer = 0;
                    if ((Integer) parameter.getCWertAsObject() >= 1) {
                        iVerlaengerungLosnummer = 2;
                    }

                    com.lp.server.fertigung.service.LosDto losDto = getFertigungFac()
                            .losFindByCNrMandantCNr(option.substring(2, 12 + iVerlaengerungLosnummer), mandant);

                    // WH 18-01-2006: Los benoetigt keine Positionen

                    if (losDto.getStatusCNr()
                            .equals(com.lp.server.fertigung.service.FertigungFac.STATUS_ANGELEGT)
                            || losDto.getStatusCNr()
                                    .equals(com.lp.server.fertigung.service.FertigungFac.STATUS_AUSGEGEBEN)
                            || losDto.getStatusCNr()
                                    .equals(com.lp.server.fertigung.service.FertigungFac.STATUS_GESTOPPT)
                            || losDto.getStatusCNr()
                                    .equals(com.lp.server.fertigung.service.FertigungFac.STATUS_ERLEDIGT)
                            || losDto.getStatusCNr()
                                    .equals(com.lp.server.fertigung.service.FertigungFac.STATUS_STORNIERT)) {
                        getTheClient(request, response)
                                .setSMsg("Auf Los " + option.substring(2) + " mit Status "
                                        + losDto.getStatusCNr().trim() + " darf nicht gebucht werden! ");
                    } else {
                        zeitdatenDto.setIBelegartid(losDto.getIId());
                        zeitdatenDto.setCBelegartnr(LocaleFac.BELEGART_LOS);

                        String maschine = option.substring(12 + iVerlaengerungLosnummer,
                                14 + iVerlaengerungLosnummer);

                        String taetigkeit = option.substring(14 + iVerlaengerungLosnummer);

                        MaschineDto maschineDto = new MaschineDto();
                        maschineDto.setCBez(maschine);
                        hmParameter.put("maschine", maschineDto);

                        hmParameter.put("beleg", "L" + option.substring(2, 12 + iVerlaengerungLosnummer));

                        com.lp.server.artikel.service.ArtikelDto artikelDto = null;
                        try {
                            artikelDto = getArtikelFac().artikelFindByCNr(taetigkeit, theclientDto);

                            zeitdatenDto.setArtikelIId(
                                    getArtikelFac().artikelFindByCNr(taetigkeit, theclientDto).getIId());

                        } catch (RemoteException ex2) {
                            getTheClient(request, response)
                                    .setSMsg("T\u00E4tigkeit '" + taetigkeit + "' nicht gefunden! ");
                            return getSJSPNext();
                        }

                        com.lp.server.fertigung.service.LossollarbeitsplanDto[] dtos = getFertigungFac()
                                .lossollarbeitsplanFindByLosIIdArtikelIIdTaetigkeit(losDto.getIId(),
                                        artikelDto.getIId());

                        if (dtos != null && dtos.length > 0) {

                            if (!maschine.trim().equals("") && !maschine.equals("--")) {

                                try {
                                    Integer maschineIId = getZeiterfassungsFac()
                                            .maschineFindByCIdentifikationsnr(maschine).getIId();

                                    com.lp.server.fertigung.service.LossollarbeitsplanDto[] sollaDtos = getFertigungFac()
                                            .lossollarbeitsplanFindByLosIIdArtikelIIdTaetigkeit(
                                                    zeitdatenDto.getIBelegartid(),
                                                    zeitdatenDto.getArtikelIId());

                                    if (sollaDtos != null && sollaDtos.length > 0) {
                                        MaschinenzeitdatenDto maschinenzeitdatenDto = new MaschinenzeitdatenDto();
                                        maschinenzeitdatenDto.setLossollarbeitsplanIId(sollaDtos[0].getIId());
                                        maschinenzeitdatenDto.setMaschineIId(maschineIId);
                                        maschinenzeitdatenDto
                                                .setPersonalIIdGestartet(zeitdatenDto.getPersonalIId());
                                        maschinenzeitdatenDto.setTVon(zeitdatenDto.getTZeit());
                                        getZeiterfassungsFac().createMaschinenzeitdaten(maschinenzeitdatenDto,
                                                theclientDto);
                                    }

                                } catch (RemoteException ex2) {
                                    getTheClient(request, response)
                                            .setSMsg("Maschine '" + maschine + "' nicht gefunden! ");
                                    return getSJSPNext();
                                }
                            }

                            // PJ 15388
                            if (maschine.equals("--")) {
                                hmParameter.put("fertig", "");
                                if (dtos != null && dtos.length > 0) {

                                    LossollarbeitsplanDto dto = dtos[0];
                                    dto.setBFertig(Helper.boolean2Short(true));

                                    try {
                                        getFertigungFac().updateLossollarbeitsplan(dto, theclientDto);
                                        getTheClient(request, response).setSMsg(getMeldungGebuchtFuerBDE(
                                                getTheClient(request, response).getData(),
                                                taetigkeit.substring(2), theclientDto));
                                        return getSJSPNext();
                                    } catch (EJBExceptionLP ex2) {
                                        getTheClient(request, response).setSMsg("Fehler beim Buchen!");
                                        return getSJSPNext();
                                    }
                                } else {
                                    getTheClient(request, response).setSMsg("Das Los "
                                            + option.substring(2, 12 + iVerlaengerungLosnummer)
                                            + " hat keinen entsprechen Arbeitsgang mit der Artikelnummer "
                                            + taetigkeit.substring(2));
                                    return getSJSPNext();
                                }
                            }

                            zeitdatenDto.setIBelegartpositionid(dtos[0].getIId());
                        } else {
                            com.lp.server.fertigung.service.LossollarbeitsplanDto[] dtosErstePosition = getFertigungFac()
                                    .lossollarbeitsplanFindByLosIId(losDto.getIId());
                            if (dtosErstePosition != null && dtosErstePosition.length > 0) {
                                zeitdatenDto.setIBelegartpositionid(dtosErstePosition[0].getIId());
                            } else {
                                // Bemerkung
                                getTheClient(request, response)
                                        .setSMsg("Los " + option.substring(2) + " hat keine Positionen");
                                return getSJSPNext();

                            }
                        }

                        try {
                            getZeiterfassungsFac().createZeitdaten(zeitdatenDto, true, true, true,
                                    theclientDto);
                            getTheClient(request, response).setSMsg(getMeldungGebuchtFuerBDE(
                                    getTheClient(request, response).getData(), taetigkeit, theclientDto));

                        } catch (EJBExceptionLP ex2) {
                            getTheClient(request, response).setSMsg("Fehler beim Buchen!");
                            return getSJSPNext();
                        }
                    }
                } catch (EJBExceptionLP ex) {
                    getTheClient(request, response)
                            .setSMsg("Los '" + option.substring(2) + "' bei diesem Mandanten nicht gefunden! ");
                    return getSJSPNext();

                }
                return getSJSPNext();
            } // Sondertaetigkeit
            else {

                if (option.substring(1).equals("SALDO")) {

                    java.sql.Timestamp ts = new java.sql.Timestamp(System.currentTimeMillis() - 3600000 * 24);
                    ts = com.lp.util.Helper.cutTimestamp(ts);

                    Calendar c = Calendar.getInstance();
                    c.setTimeInMillis(ts.getTime());

                    String saldoMitUrlaub = "";
                    try {
                        saldoMitUrlaub = getZeiterfassungsFac().erstelleMonatsAbrechnungFuerBDE(
                                zeitdatenDto.getPersonalIId(), new Integer(c.get(Calendar.YEAR)),
                                new Integer(c.get(Calendar.MONTH)), false, new java.sql.Date(ts.getTime()),
                                theclientDto, true, false);

                    } catch (EJBExceptionLP ex7) {

                        if (ex7.getCause() instanceof EJBExceptionLP) {
                            EJBExceptionLP e = (EJBExceptionLP) ex7.getCause();
                            if (e != null && e
                                    .getCode() == EJBExceptionLP.FEHLER_PERSONAL_FEHLER_BEI_EINTRITTSDATUM) {
                                getTheClient(request, response)
                                        .setSMsg(new String("FEHLER_PERSONAL_FEHLER_BEI_EINTRITTSDATUM"));
                                return getSJSPNext();

                            }
                        }
                        getTheClient(request, response).setSMsg(new String(ex7.getMessage()));
                        setSJSPNext("bdestation.jsp");

                    }

                    getTheClient(request, response).setSMsg(saldoMitUrlaub);

                    setSJSPNext("bdestation.jsp");
                    return getSJSPNext();

                } else if (option.substring(1).equals("TAGESSALDO")) {

                    java.sql.Timestamp ts = new java.sql.Timestamp(System.currentTimeMillis() - 3600000 * 24);

                    Double d = getZeiterfassungsFac().berechneTagesArbeitszeit(zeitdatenDto.getPersonalIId(),
                            new java.sql.Date(System.currentTimeMillis()), theclientDto);

                    StringBuffer sb = new StringBuffer();
                    sb.append("Tagesarbeitszeit bis jetzt: "
                            + Helper.rundeKaufmaennisch(new BigDecimal(d.doubleValue()), 2).doubleValue()
                            + "h");
                    sb.append("\r\n");

                    getTheClient(request, response).setSMsg(new String(sb));
                    setSJSPNext("bdestation.jsp");
                    return getSJSPNext();

                } else {

                    try {
                        TaetigkeitDto taetigkeitDto = getZeiterfassungsFac()
                                .taetigkeitFindByCNr(option.substring(1), theclientDto);

                        zeitdatenDto.setTaetigkeitIId(taetigkeitDto.getIId());
                        getZeiterfassungsFac().createZeitdaten(zeitdatenDto, true, true, true, theclientDto);
                        getTheClient(request, response).setSMsg(
                                getMeldungGebuchtFuerBDE(hmParameter, option.substring(1), theclientDto));
                    } catch (EJBExceptionLP ex1) {
                        getTheClient(request, response)
                                .setSMsg("Sondert\u00E4tigkeit '" + option.substring(1) + "' nicht gefunden! ");
                    }
                    hmParameter.put("zeitdaten", zeitdatenDto);
                    setSJSPNext("bdestation.jsp");

                }
                getTheClient(request, response).setData(hmParameter);
                return getSJSPNext();
            }
        }

    } else if (command.equals(TheApp.CMD_ZE_BDESTATION3)) {

        HashMap<String, Serializable> hmParameter = (HashMap<String, Serializable>) getTheClient(request,
                response).getData();
        ZeitdatenDto zeitdatenDto = (ZeitdatenDto) hmParameter.get("zeitdaten");
        zeitdatenDto.setTZeit(new Timestamp(System.currentTimeMillis()));

        String option = request.getParameter("option");
        getTheClient(request, response).setSMsg("");

        if (option != null && option.length() > 0) {

            if (option.equals("$PLUS")) {
                // CK: PJ5589
                String beleg = (String) hmParameter.get("beleg");

                if (beleg.substring(0, 1).equals("L")) {
                    com.lp.server.fertigung.service.LosDto losDto = getFertigungFac()
                            .losFindByCNrMandantCNr(beleg.substring(1), mandant);

                    ZeitverteilungDto zeitverteilungDto = new ZeitverteilungDto();
                    zeitverteilungDto.setLosIId(losDto.getIId());
                    zeitverteilungDto.setTZeit(new Timestamp(System.currentTimeMillis()));
                    zeitverteilungDto.setPersonalIId(zeitdatenDto.getPersonalIId());
                    try {
                        getZeiterfassungsFac().createZeitverteilung(zeitverteilungDto, theclientDto);
                    } catch (EJBExceptionLP e) {
                        hmParameter.remove("beleg");
                        getTheClient(request, response).setData(hmParameter);
                        getTheClient(request, response)
                                .setSMsg("Los '" + losDto.getCNr() + "' wurde bereits mit $PLUS gebucht");
                        setSJSPNext("bdestation2.jsp");
                        return getSJSPNext();
                    }

                } else {
                    getTheClient(request, response).setSMsg("$PLUS ist nur f\u00FCr Lose m\u00F6glich.");
                    setSJSPNext("bdestation.jsp");
                    return getSJSPNext();
                }

                hmParameter.remove("beleg");
                getTheClient(request, response).setData(hmParameter);
                setSJSPNext("bdestation2.jsp");
                return getSJSPNext();

            } else if (option.equals("$STORNO")) {
                getZeiterfassungsFac().removeZeitverteilungByPersonalIIdUndTag(zeitdatenDto.getPersonalIId(),
                        new Timestamp(System.currentTimeMillis()));
                hmParameter.remove("beleg");
                getTheClient(request, response).setData(hmParameter);
                setSJSPNext("bdestation2.jsp");
            } else if (option.equals("$SPERREN")) {

                String beleg = (String) hmParameter.get("beleg");
                if (beleg.substring(0, 1).equals("L")) {
                    com.lp.server.fertigung.service.LosDto losDto = getFertigungFac()
                            .losFindByCNrMandantCNr(beleg.substring(1), mandant);

                    if (losDto.getStuecklisteIId() != null) {
                        Integer artikelIId = getStuecklisteFac()
                                .stuecklisteFindByPrimaryKey(losDto.getStuecklisteIId(), theclientDto)
                                .getArtikelIId();

                        SperrenDto sDto = getArtikelFac().sperrenFindBDurchfertigung(theclientDto);

                        if (sDto != null) {

                            ArtikelsperrenDto aspDtoVorhanden = getArtikelFac()
                                    .artikelsperrenFindByArtikelIIdSperrenIIdOhneExc(artikelIId, sDto.getIId());
                            if (aspDtoVorhanden == null) {
                                ArtikelsperrenDto spDto = new ArtikelsperrenDto();
                                spDto.setArtikelIId(artikelIId);
                                spDto.setSperrenIId(sDto.getIId());

                                PersonalDto pDto = getPersonalFac()
                                        .personalFindByPrimaryKey(zeitdatenDto.getPersonalIId(), theclientDto);

                                String grund = beleg + " " + pDto.getPartnerDto().getCName1nachnamefirmazeile1()
                                        + " " + pDto.getPartnerDto().getCName2vornamefirmazeile2();

                                if (grund.length() > 80) {
                                    grund = grund.substring(0, 79);
                                }

                                spDto.setCGrund(grund);
                                getArtikelFac().createArtikelsperren(spDto, theclientDto);
                                getTheClient(request, response)
                                        .setSMsg("Los " + losDto.getCNr() + " durch Fertigung gesperrt.");
                                setSJSPNext("bdestation.jsp");
                                return getSJSPNext();
                            } else {
                                getTheClient(request, response)
                                        .setSMsg("St\u00FCckliste bereits durch Fertigung gesperrt.");
                                setSJSPNext("bdestation.jsp");
                                return getSJSPNext();
                            }
                        } else {
                            getTheClient(request, response)
                                    .setSMsg("Fertigungssperre in Grunddaten nicht definiert.");
                            setSJSPNext("bdestation.jsp");
                            return getSJSPNext();
                        }

                    }

                    setSJSPNext("bdestation.jsp");
                    return getSJSPNext();
                }

            } else if (option.equals("$FERTIG")) {
                hmParameter.put("fertig", "");
                MaschineDto maschineDto = new MaschineDto();
                maschineDto.setCBez("Fertig");
                hmParameter.put("maschine", maschineDto);
                getTheClient(request, response).setData(hmParameter);
                setSJSPNext("bdestation4.jsp");
                return getSJSPNext();
            } else {

                setSJSPNext("bdestation.jsp");
                // MASCHINE
                if (option.substring(0, 2).equals("$M")) {

                    String maschine = option.substring(2);

                    try {
                        MaschineDto maschineDto = getZeiterfassungsFac()
                                .maschineFindByCIdentifikationsnr(maschine);
                        hmParameter.put("zeitdaten", zeitdatenDto);
                        hmParameter.put("maschine", maschineDto);
                        setSJSPNext("bdestation4.jsp");
                        return getSJSPNext();

                    } catch (EJBExceptionLP ex2) {
                        getTheClient(request, response).setSMsg("Maschine '" + maschine + "' nicht gefunden! ");
                        return getSJSPNext();
                    }

                } // TAETIGKEIT
                else {

                    String taetigkeit = option.substring(2);

                    com.lp.server.artikel.service.ArtikelDto artikelDto = null;
                    try {
                        artikelDto = getArtikelFac().artikelFindByCNr(taetigkeit, theclientDto);

                        zeitdatenDto.setArtikelIId(
                                getArtikelFac().artikelFindByCNr(taetigkeit, theclientDto).getIId());

                    } catch (EJBExceptionLP ex2) {
                        getTheClient(request, response)
                                .setSMsg("T\u00E4tigkeit '" + taetigkeit + "' nicht gefunden! ");
                        return getSJSPNext();
                    }

                    String beleg = (String) hmParameter.get("beleg");

                    if (beleg.substring(0, 1).equals("L")) {
                        com.lp.server.fertigung.service.LosDto losDto = getFertigungFac()
                                .losFindByCNrMandantCNr(beleg.substring(1), mandant);

                        ZeitverteilungDto[] zvDtos = getZeiterfassungsFac()
                                .zeitverteilungFindByPersonalIIdUndTag(zeitdatenDto.getPersonalIId(),
                                        new Timestamp(System.currentTimeMillis()));
                        if (zvDtos != null & zvDtos.length > 0) {

                            if (zvDtos[0].getArtikelIId() == null) {
                                // Abschlussbuchung eintragen
                                ZeitverteilungDto zv = zvDtos[0];
                                zv.setIId(null);
                                zv.setLosIId(losDto.getIId());
                                zv.setArtikelIId(artikelDto.getIId());
                                try {
                                    getZeiterfassungsFac().createZeitverteilung(zv, theclientDto);
                                } catch (EJBExceptionLP e) {
                                    hmParameter.remove("beleg");
                                    getTheClient(request, response).setData(hmParameter);
                                    getTheClient(request, response).setSMsg(
                                            "Los '" + losDto.getCNr() + "' wurde bereits mit $PLUS gebucht");
                                    setSJSPNext("bdestation2.jsp");
                                    return getSJSPNext();
                                }

                                hmParameter.remove("beleg");
                                getTheClient(request, response).setData(hmParameter);
                                getTheClient(request, response)
                                        .setSMsg("Beginnbuchungen f\u00FCr 'Zeitverteilung' abgeschlossen");
                                setSJSPNext("bdestation.jsp");
                                return getSJSPNext();
                            }
                        }

                        com.lp.server.fertigung.service.LossollarbeitsplanDto[] dtos = getFertigungFac()
                                .lossollarbeitsplanFindByLosIIdArtikelIIdTaetigkeit(losDto.getIId(),
                                        artikelDto.getIId());

                        if (dtos != null && dtos.length > 0) {
                            zeitdatenDto.setIBelegartpositionid(dtos[0].getIId());
                        } else {
                            com.lp.server.fertigung.service.LossollarbeitsplanDto[] dtosErstePosition = getFertigungFac()
                                    .lossollarbeitsplanFindByLosIId(losDto.getIId());
                            if (dtosErstePosition != null && dtosErstePosition.length > 0) {
                                zeitdatenDto.setIBelegartpositionid(dtosErstePosition[0].getIId());
                            } else {
                                // Bemerkung
                                getTheClient(request, response)
                                        .setSMsg("Los " + beleg.substring(1) + " hat keine Positionen");
                                return getSJSPNext();

                            }
                        }
                    }

                    try {
                        getZeiterfassungsFac().createZeitdaten(zeitdatenDto, true, true, true, theclientDto);
                        getTheClient(request, response).setSMsg(getMeldungGebuchtFuerBDE(
                                getTheClient(request, response).getData(), taetigkeit, theclientDto));

                        return getSJSPNext();
                    } catch (EJBExceptionLP ex2) {
                        getTheClient(request, response).setSMsg("Fehler beim Buchen!");
                        return getSJSPNext();
                    }
                }
            }
        }
    } else if (command.equals(TheApp.CMD_ZE_BDESTATION3GUTSCHLECHT)) {
        HashMap<Object, Object> hmParameter = (HashMap<Object, Object>) getTheClient(request, response)
                .getData();
        ZeitdatenDto zeitdatenDto = (ZeitdatenDto) hmParameter.get("zeitdaten");

        String gutstueck = request.getParameter("gutstueck");
        if (gutstueck.equals("")) {
            gutstueck = "0";
        }
        String schlechtstueck = request.getParameter("schlechtstueck");
        if (schlechtstueck.equals("")) {
            schlechtstueck = "0";
        }

        BigDecimal bdGutstueck = null;
        BigDecimal bdSchlechtstueck = null;
        try {
            bdGutstueck = new BigDecimal(gutstueck);
            bdSchlechtstueck = new BigDecimal(schlechtstueck);
        } catch (NumberFormatException ex9) {
            getTheClient(request, response)
                    .setSMsg("Gut/Schlechtst\u00FCck d\u00FCrfen nur aus Zahlen bestehen.");
            setSJSPNext("bdestation.jsp");
            return getSJSPNext();
        }

        if (bdGutstueck.doubleValue() < 0 || bdSchlechtstueck.doubleValue() < 0) {
            getTheClient(request, response).setSMsg("Gut/Schlechtst\u00FCck m\u00FCssen Positiv sein.");
            setSJSPNext("bdestation.jsp");
            return getSJSPNext();
        }
        Integer taetigkeitIId_Ende = getZeiterfassungsFac()
                .taetigkeitFindByCNr(ZeiterfassungFac.TAETIGKEIT_ENDE, theclientDto).getIId();
        ZeitdatenDto zeitdatenDtoEnde = new ZeitdatenDto();
        zeitdatenDtoEnde.setTZeit(new Timestamp(zeitdatenDto.getTZeit().getTime() + 1000));
        zeitdatenDtoEnde.setTaetigkeitIId(taetigkeitIId_Ende);
        zeitdatenDtoEnde.setPersonalIId(zeitdatenDto.getPersonalIId());

        // Hole letzten begonnenen Auftrag und hinterlege gut/schlechtstueck
        Session session = FLRSessionFactory.getFactory().openSession();
        org.hibernate.Criteria liste = session.createCriteria(FLRZeitdaten.class);
        liste.add(Expression.eq(ZeiterfassungFac.FLR_ZEITDATEN_PERSONAL_I_ID, zeitdatenDto.getPersonalIId()));
        liste.add(Expression.gt(ZeiterfassungFac.FLR_ZEITDATEN_T_ZEIT,
                Helper.cutTimestamp(zeitdatenDto.getTZeit())));

        liste.addOrder(Order.desc(ZeiterfassungFac.FLR_ZEITDATEN_T_ZEIT));
        List<?> letzerAuftrag = liste.list();

        Iterator<?> it = letzerAuftrag.iterator();
        ZeitdatenDto letzterAuftrag = null;

        while (it.hasNext()) {
            FLRZeitdaten flrLetzerAuftrag = (FLRZeitdaten) it.next();

            if (flrLetzerAuftrag.getC_belegartnr() != null && flrLetzerAuftrag.getI_belegartid() != null) {
                if (flrLetzerAuftrag.getC_belegartnr().equals(zeitdatenDto.getCBelegartnr())
                        && flrLetzerAuftrag.getI_belegartid().equals(zeitdatenDto.getIBelegartid())) {
                    letzterAuftrag = getZeiterfassungsFac()
                            .zeitdatenFindByPrimaryKey(flrLetzerAuftrag.getI_id(), theclientDto);
                    break;
                }
            } else if (flrLetzerAuftrag.getTaetigkeit_i_id() != null
                    && flrLetzerAuftrag.getTaetigkeit_i_id().equals(taetigkeitIId_Ende)) {
                break;
            }

        }

        if (letzterAuftrag != null) {
            // Hier eintragen
            // letzterAuftrag.setNGut(bdGutstueck);
            // letzterAuftrag.setNSchlecht(bdSchlechtstueck);
            getZeiterfassungsFac().updateZeitdaten(letzterAuftrag, theclientDto);
            // und buche ENDE
            getZeiterfassungsFac().createZeitdaten(zeitdatenDtoEnde, false, false, false, theclientDto);

        } else {
            // was nun?
            // Beginn und ende Buchen
            getZeiterfassungsFac().createZeitdaten(zeitdatenDto, false, false, false, theclientDto);
            getZeiterfassungsFac().createZeitdaten(zeitdatenDtoEnde, false, false, false, theclientDto);

        }

        session.close();
        getTheClient(request, response).setSMsg(
                getMeldungGebuchtFuerBDE(getTheClient(request, response).getData(), null, theclientDto));

        setSJSPNext("bdestation.jsp");
        return getSJSPNext();
    }

    else if (command.equals(TheApp.CMD_ZE_BDESTATION4)) {
        HashMap<?, ?> hmParameter = (HashMap<?, ?>) getTheClient(request, response).getData();
        ZeitdatenDto zeitdatenDto = (ZeitdatenDto) hmParameter.get("zeitdaten");
        zeitdatenDto.setTZeit(new Timestamp(System.currentTimeMillis()));

        String taetigkeit = request.getParameter("taetigkeit");
        getTheClient(request, response).setSMsg("");
        if (taetigkeit != null && taetigkeit.length() > 0) {

            setSJSPNext("bdestation.jsp");
            com.lp.server.artikel.service.ArtikelDto artikelDto = null;
            try {
                artikelDto = getArtikelFac().artikelFindByCNr(taetigkeit.substring(2), theclientDto);

                zeitdatenDto.setArtikelIId(artikelDto.getIId());
            } catch (EJBExceptionLP ex2) {
                getTheClient(request, response)
                        .setSMsg("T\u00E4tigkeit '" + taetigkeit.substring(2) + "' nicht gefunden! ");
                return getSJSPNext();
            }

            String beleg = (String) hmParameter.get("beleg");

            if (beleg.substring(0, 1).equals("L")) {
                com.lp.server.fertigung.service.LosDto losDto = getFertigungFac()
                        .losFindByCNrMandantCNr(beleg.substring(1), mandant);

                com.lp.server.fertigung.service.LossollarbeitsplanDto[] dtos = getFertigungFac()
                        .lossollarbeitsplanFindByLosIIdArtikelIIdTaetigkeit(losDto.getIId(),
                                artikelDto.getIId());

                if (hmParameter.containsKey("fertig")) {

                    if (dtos != null && dtos.length > 0) {

                        LossollarbeitsplanDto dto = dtos[0];
                        dto.setBFertig(Helper.boolean2Short(true));

                        ParametermandantDto parameterDtoTriggerTops = getParameterFac().getMandantparameter(
                                mandant, ParameterFac.KATEGORIE_FERTIGUNG,
                                ParameterFac.PARAMETER_TRIGGERT_TRUMPF_TOPS_ABLIEFERUNG);

                        try {
                            getFertigungFac().updateLossollarbeitsplan(dto, theclientDto);

                            // PJ 17916
                            if (parameterDtoTriggerTops.getCWert() != null
                                    && parameterDtoTriggerTops.getCWert().trim().length() > 0) {
                                ArtikelDto aDto = getArtikelFac().artikelFindByCNrMandantCNrOhneExc(
                                        parameterDtoTriggerTops.getCWert().trim(), theclientDto.getMandant());

                                if (aDto == null) {
                                    getTheClient(request, response).setSMsg(
                                            "Der Artikel, der im Parameter TRIGGERT_TRUMPF_TOPS_ABLIEFERUNG hinterlegt ist, exisitiert nicht! "
                                                    + parameterDtoTriggerTops.getCWert());
                                    return getSJSPNext();
                                }
                                if (aDto != null && aDto.getIId().equals(artikelDto.getIId())) {
                                    getFertigungFac().bucheTOPSArtikelAufHauptLager(losDto.getIId(),
                                            theclientDto, null);
                                }
                            }

                            getTheClient(request, response)
                                    .setSMsg(getMeldungGebuchtFuerBDE(getTheClient(request, response).getData(),
                                            taetigkeit.substring(2), theclientDto));
                            return getSJSPNext();
                        } catch (EJBExceptionLP ex2) {
                            getTheClient(request, response).setSMsg("Fehler beim Buchen!");
                            return getSJSPNext();
                        }
                    } else {
                        getTheClient(request, response).setSMsg("Das Los " + beleg.substring(1)
                                + " hat keinen entsprechen Arbeitsgang mit der Artikelnummer "
                                + taetigkeit.substring(2));
                        return getSJSPNext();
                    }

                }

                if (dtos != null && dtos.length > 0) {
                    zeitdatenDto.setIBelegartpositionid(dtos[0].getIId());
                } else {
                    com.lp.server.fertigung.service.LossollarbeitsplanDto[] dtosErstePosition = getFertigungFac()
                            .lossollarbeitsplanFindByLosIId(losDto.getIId());
                    if (dtosErstePosition != null && dtosErstePosition.length > 0) {
                        zeitdatenDto.setIBelegartpositionid(dtosErstePosition[0].getIId());
                    } else {
                        // Bemerkung
                        getTheClient(request, response)
                                .setSMsg("Los " + beleg.substring(1) + " hat keine Positionen");
                        return getSJSPNext();

                    }
                }
            }

            // Maschinenzeitdaten buchen (geht nur auf Los)

            if (hmParameter.containsKey("maschine") && zeitdatenDto.getCBelegartnr() != null
                    && zeitdatenDto.getCBelegartnr().equals(LocaleFac.BELEGART_LOS)
                    && zeitdatenDto.getIBelegartid() != null) {
                MaschineDto maschineDto = (MaschineDto) hmParameter.get("maschine");

                com.lp.server.fertigung.service.LossollarbeitsplanDto[] dtos = getFertigungFac()
                        .lossollarbeitsplanFindByLosIIdArtikelIIdTaetigkeit(zeitdatenDto.getIBelegartid(),
                                zeitdatenDto.getArtikelIId());

                if (dtos != null && dtos.length > 0) {
                    MaschinenzeitdatenDto maschinenzeitdatenDto = new MaschinenzeitdatenDto();
                    maschinenzeitdatenDto.setPersonalIIdGestartet(zeitdatenDto.getPersonalIId());
                    maschinenzeitdatenDto.setTVon(zeitdatenDto.getTZeit());
                    maschinenzeitdatenDto.setLossollarbeitsplanIId(dtos[0].getIId());
                    maschinenzeitdatenDto.setMaschineIId(maschineDto.getIId());
                    getZeiterfassungsFac().createMaschinenzeitdaten(maschinenzeitdatenDto, theclientDto);

                }
            }

            try {
                getZeiterfassungsFac().createZeitdaten(zeitdatenDto, true, true, false, theclientDto);
                getTheClient(request, response).setSMsg(getMeldungGebuchtFuerBDE(
                        getTheClient(request, response).getData(), taetigkeit.substring(2), theclientDto));
                return getSJSPNext();
            } catch (EJBExceptionLP ex2) {
                getTheClient(request, response).setSMsg("Fehler beim Buchen!");
                return getSJSPNext();
            }

        }
    } else if (command.equals(TheApp.CMD_ZE_MECS_ONLCHECK)) {
        String beleg = request.getParameter("beleg");

        if (beleg == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter 'beleg' muss angegeben werden");
            return null;
        }

        beleg = beleg.trim();

        if (beleg.length() < 2) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Parameter 'beleg' muss mindestens 2 Zeichen lang sein");
            return null;
        }

        String status = null;
        BigDecimal offeneMenge = new BigDecimal(0);

        String ueberliefernErlaubt = "1";
        try {

            if (beleg.substring(0, 2).equals("$A")) {

                AuftragDto auftragDto = getAuftragFac().auftragFindByMandantCNrCNr(mandant, beleg.substring(2),
                        theclientDto);
                status = auftragDto.getAuftragstatusCNr();

            } else if (beleg.substring(0, 2).equals("$L")) {
                LosDto losDto = getFertigungFac().losFindByCNrMandantCNr(beleg.substring(2), mandant);
                status = losDto.getStatusCNr();

                BigDecimal erledigteMenge = getFertigungFac().getErledigteMenge(losDto.getIId(), theclientDto);
                offeneMenge = losDto.getNLosgroesse().subtract(erledigteMenge);

                if (losDto.getStuecklisteIId() != null) {
                    StuecklisteDto stkDto = getStuecklisteFac()
                            .stuecklisteFindByPrimaryKey(losDto.getStuecklisteIId(), theclientDto);

                    if (Helper.short2boolean(stkDto.getBUeberlieferbar()) == false) {
                        ueberliefernErlaubt = "0";
                    }

                }

            }

        } catch (EJBExceptionLP ex8) {
            status = "Beleg existiert nicht";
        }

        StringBuffer sb = new StringBuffer();

        sb.append(Helper.fitString2Length(beleg, 40, ' '));
        sb.append(Helper.fitString2Length(status, 40, ' '));

        // Offene Menge 17 stellig

        DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance();
        dfs.setDecimalSeparator('.');
        DecimalFormat dFormat = new DecimalFormat("0.0000", dfs);
        if (offeneMenge.doubleValue() < 0) {
            sb.append("-");
        } else {
            sb.append(" ");
        }
        sb.append(Helper.fitString2LengthAlignRight(dFormat.format(offeneMenge.abs()), 16, ' '));
        sb.append(ueberliefernErlaubt);
        sb.append("\r\n");

        getTheClient(request, response).setSMsg(new String(sb));

    } else if (command.equals(TheApp.CMD_ZE_MECS_ONLINECHECK_ABL)) {
        String beleg = request.getParameter("beleg");
        String menge = request.getParameter("menge");

        if (beleg == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter 'beleg' muss angegeben werden");
            return null;
        }
        if (menge == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter 'menge' muss angegeben werden");
            return null;
        }

        BigDecimal nMenge = new BigDecimal(menge.trim());

        beleg = beleg.trim();

        if (beleg.length() < 2) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Parameter 'beleg' muss mindestens 2 Zeichen lang sein");
            return null;
        }

        String status = null;
        BigDecimal offeneMenge = new BigDecimal(0);
        boolean ueberliefernErlaubt = true;
        try {

            if (beleg.substring(0, 2).equals("$A")) {

                AuftragDto auftragDto = getAuftragFac().auftragFindByMandantCNrCNr(mandant, beleg.substring(2),
                        theclientDto);
                status = auftragDto.getAuftragstatusCNr();

            } else if (beleg.substring(0, 2).equals("$L")) {
                LosDto losDto = getFertigungFac().losFindByCNrMandantCNr(beleg.substring(2), mandant);
                status = losDto.getStatusCNr();

                BigDecimal erledigteMenge = getFertigungFac().getErledigteMenge(losDto.getIId(), theclientDto);
                offeneMenge = losDto.getNLosgroesse().subtract(erledigteMenge);
                if (losDto.getStuecklisteIId() != null) {
                    StuecklisteDto stkDto = getStuecklisteFac()
                            .stuecklisteFindByPrimaryKey(losDto.getStuecklisteIId(), theclientDto);
                    ueberliefernErlaubt = Helper.short2boolean(stkDto.getBUeberlieferbar());
                }

            }

        } catch (EJBExceptionLP ex8) {
            status = "Beleg existiert nicht";
        }

        StringBuffer sb = new StringBuffer();

        // Zeile1
        sb.append(Helper.fitString2Length(beleg, 40, ' '));
        sb.append(Helper.fitString2Length(status, 40, ' '));
        sb.append("\r\n");
        // Offene Menge 17 stellig

        // Zeile2

        // Zuerst 3 Stellen Fehlernummer: 000= Abliefern moeglich 001=
        // Status erlaubt kein Abliefern - 002=
        // Menge der Ablieferung zu gross

        String fehlercode = "";
        String text1 = "";
        String text2 = "";
        if (status.equals(LocaleFac.STATUS_ERLEDIGT) || status.equals(LocaleFac.STATUS_STORNIERT)
                || status.equals(LocaleFac.STATUS_ANGELEGT) || status.equals(LocaleFac.STATUS_GESTOPPT)) {
            fehlercode = "001";
            text1 = "Nicht erlaubt!";
            text2 = "Status: " + status;
        } else {

            if (nMenge.doubleValue() <= offeneMenge.doubleValue()) {
                // Wenn Abliefermenge kleiner als Offene Menge, dann =OK
                fehlercode = "000";
                text1 = "Ablieferung";
                text2 = "erlaubt";
            } else {
                if (ueberliefernErlaubt == false) {
                    fehlercode = "002";
                    text1 = "Nicht erlaubt!";

                    DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance();
                    dfs.setDecimalSeparator('.');
                    DecimalFormat dFormat = new DecimalFormat("#####0", dfs);
                    text2 = "Nur " + Helper.fitString2LengthAlignRight(dFormat.format(offeneMenge), 6, ' ')
                            + " Stk offen";
                } else {
                    fehlercode = "000";
                    text1 = "Ablieferung";
                    text2 = "erlaubt";
                }
            }
        }
        sb.append(fehlercode);

        // 37 Leerstellen
        sb.append(Helper.fitString2Length("", 37, ' '));

        // Text1
        sb.append(Helper.fitString2Length(text1, 20, ' '));
        // Text2
        sb.append(Helper.fitString2Length(text2, 20, ' '));

        sb.append("\r\n");

        getTheClient(request, response).setSMsg(new String(sb));

    } else if (command.equals(TheApp.CMD_ZE_MECS_AUSWEISE)) {
        String fingerprint = request.getParameter("fingerprint");

        if (fingerprint != null) {
            StringBuffer sb = new StringBuffer();
            PersonalfingerDto[] personalfingerDtos = getZutrittscontrollerFac().personalfingerFindAll();
            for (int i = 0; i < personalfingerDtos.length; i++) {
                PersonalfingerDto personalfingerDto = personalfingerDtos[i];
                String id = personalfingerDto.getIId() + "";
                id = Helper.fitString2LengthAlignRight(id, 8, '0');
                StringBuffer tmp = new StringBuffer();
                // unbedingt nach ausweis sortieren
                tmp.setLength(0);
                tmp.append(Helper.fitString2Length(id, 20, ' '));

                PersonalDto personalDto = getPersonalFac()
                        .personalFindByPrimaryKey(personalfingerDto.getPersonalIId(), theclientDto);

                tmp.append(Helper.fitString2LengthAlignRight(personalDto.getCPersonalnr() + "", 5, '0')); // persnr
                tmp.append(Helper.fitString2Length("", 3, ' ')); // zutrkl

                String sVorname = personalDto.getPartnerDto().getCName2vornamefirmazeile2();
                String sNachname = personalDto.getPartnerDto().getCName1nachnamefirmazeile1();

                if (sVorname == null) {
                    sVorname = "";
                }
                tmp.append(Helper.fitString2Length(sVorname + " " + sNachname, 25, ' ')); // name
                sb.append(tmp).append("\r\n");

            }
            getTheClient(request, response).setSMsg(new String(sb));
        } else {

            // Ausweisnummern holen
            StringBuffer sb = new StringBuffer();
            PersonalDto[] personalDtos = getPersonalFac().personalFindByCAusweisSortiertNachCAusweis();

            ParametermandantDto parameterDto = getParameterFac().getMandantparameter(mandant,
                    ParameterFac.KATEGORIE_PERSONAL, ParameterFac.PARAMETER_LEAD_IN_AUSWEISNUMMER_MECS);

            String leadIn = "";
            if (parameterDto.getCWert() != null) {
                leadIn = parameterDto.getCWert().trim();
            }

            for (int i = 0; i < personalDtos.length; i++) {
                PersonalDto personalDto = personalDtos[i];
                personalDto.setPartnerDto(
                        getPartnerFac().partnerFindByPrimaryKey(personalDto.getPartnerIId(), theclientDto));
                StringBuffer tmp = new StringBuffer();
                // unbedingt nach ausweis sortieren
                tmp.setLength(0);
                tmp.append(Helper.fitString2Length(leadIn + personalDto.getCAusweis(), 20, ' ')); // ausweis
                tmp.append(Helper.fitString2LengthAlignRight(personalDto.getCPersonalnr() + "", 5, '0')); // persnr
                tmp.append(Helper.fitString2Length("", 3, ' ')); // zutrkl

                String sVorname = personalDto.getPartnerDto().getCName2vornamefirmazeile2();
                String sNachname = personalDto.getPartnerDto().getCName1nachnamefirmazeile1();

                if (sVorname == null) {
                    sVorname = "";
                }

                tmp.append(Helper.fitString2Length(sVorname + " " + sNachname, 25, ' ')); // name
                sb.append(tmp).append("\r\n");

            }

            getTheClient(request, response).setSMsg(new String(sb));
        }
    } else if (command.equals(TheApp.CMD_ZE_MECS_ERLAUBTETAETIGKEITEN)) {

        Session session = FLRSessionFactory.getFactory().openSession();
        org.hibernate.Criteria liste = session.createCriteria(FLRTaetigkeit.class);
        liste.add(Expression.eq(ZeiterfassungFac.FLR_TAETIGKEIT_B_BDEBUCHBAR, Helper.boolean2Short(true)));
        liste.addOrder(Order.asc("c_nr"));
        List<?> lReisezeiten = liste.list();
        Iterator<?> it = lReisezeiten.iterator();

        StringBuffer sb = new StringBuffer();

        while (it.hasNext()) {
            FLRTaetigkeit flrTaetigkeit = (FLRTaetigkeit) it.next();
            StringBuffer tmp = new StringBuffer();

            tmp.setLength(0);
            tmp.append('$');
            tmp.append(Helper.fitString2LengthAlignRight(flrTaetigkeit.getC_nr(), 14, ' ')); // persnr
            sb.append(tmp).append("\r\n");

        }
        session.close();

        getTheClient(request, response).setSMsg(new String(sb));

    } else if (command.equals(TheApp.CMD_ZE_MECS_PERSSTAMM)) {
        // Personalstamm holen

        StringBuffer sb = new StringBuffer();

        // unbedingt nach personalnummer sortieren
        PersonalDto[] personalDtos = getPersonalFac().personalFindByCAusweisSortiertNachPersonalnr();
        for (int i = 0; i < personalDtos.length; i++) {
            PersonalDto personalDto = personalDtos[i];
            personalDto.setPartnerDto(
                    getPartnerFac().partnerFindByPrimaryKey(personalDto.getPartnerIId(), theclientDto));
            StringBuffer tmp = new StringBuffer();

            tmp.setLength(0);
            tmp.append(Helper.fitString2LengthAlignRight(personalDto.getCPersonalnr() + "", 5, '0')); // persnr
            tmp.append(Helper.fitString2Length("", 3, ' ')); // zutrkl

            String sVorname = personalDto.getPartnerDto().getCName2vornamefirmazeile2();
            String sNachname = personalDto.getPartnerDto().getCName1nachnamefirmazeile1();

            if (sVorname == null) {
                sVorname = "";
            }

            tmp.append(Helper.fitString2Length(sVorname + " " + sNachname, 25, ' ')); // name
            sb.append(tmp).append("\r\n");

        }
        getTheClient(request, response).setSMsg(new String(sb));
    } else if (command.equals(TheApp.CMD_ZE_MECS_SALDO)) {
        String ausweis = "";
        try {
            ausweis = request.getParameter("ausweis");
        } catch (Exception e) {
            getTheClient(request, response).setBResponseIsReady(true);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter 'ausweis' nicht angegeben");
            myLogger.error("doPost; Exception aufgetreten", e);
            return null;
        }
        if (ausweis.startsWith("$P")) {
            ausweis = ausweis.substring(2);
        }

        ausweis = ausweis.trim();

        ParametermandantDto parameterDto = getParameterFac().getMandantparameter(mandant,
                ParameterFac.KATEGORIE_PERSONAL, ParameterFac.PARAMETER_LEAD_IN_AUSWEISNUMMER_MECS);

        String leadIn = "";
        if (parameterDto.getCWert() != null) {
            leadIn = parameterDto.getCWert().trim();
            int iLaenge = leadIn.length();
            if (ausweis.length() > iLaenge) {
                ausweis = ausweis.substring(iLaenge);
            }
        }

        PersonalDto personalDto = getPersonalFac().personalFindByCAusweis(ausweis);

        personalDto.setPartnerDto(
                getPartnerFac().partnerFindByPrimaryKey(personalDto.getPartnerIId(), theclientDto));

        java.sql.Timestamp ts = new java.sql.Timestamp(System.currentTimeMillis() - 3600000 * 24);
        ts = com.lp.util.Helper.cutTimestamp(ts);

        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(ts.getTime());

        String urlaub = null;
        try {
            urlaub = getZeiterfassungsFac().erstelleMonatsAbrechnungFuerBDE(personalDto.getIId(),
                    new Integer(c.get(Calendar.YEAR)), new Integer(c.get(Calendar.MONTH)), false,
                    new java.sql.Date(ts.getTime()), theclientDto, true, false);

        } catch (EJBExceptionLP ex7) {

            if (ex7.getCause() instanceof EJBExceptionLP) {
                EJBExceptionLP e = (EJBExceptionLP) ex7.getCause();
                if (e != null && e.getCode() == EJBExceptionLP.FEHLER_PERSONAL_FEHLER_BEI_EINTRITTSDATUM) {
                    getTheClient(request, response)
                            .setSMsg(new String("FEHLER_PERSONAL_FEHLER_BEI_EINTRITTSDATUM"));
                    return getSJSPNext();

                }
            }
            getTheClient(request, response).setSMsg(new String(ex7.getMessage()));
            setSJSPNext("bdestation.jsp");

        }

        getTheClient(request, response).setSMsg(urlaub);

    } else if (command.equals(TheApp.CMD_ZE_MECS_ZEITBUCHEN)
            || command.equals(TheApp.CMD_ZE_MECS_ZEITBUCHENFINGERPRINT)) {
        String record = null;

        if (command.equals(TheApp.CMD_ZE_MECS_ZEITBUCHEN)) {
            record = request.getParameter("record");
        } else {
            record = request.getParameter("recordfingerprint");

        }

        record = Helper.fitString2Length(record, 200, ' ');

        String schluesselNr = record.substring(19, 39).trim();
        String zeit = record.substring(5, 19);
        String taetigkeit = record.substring(3, 5);
        // SP753
        String terminal = record.substring(64, 86);
        // Damit die Sollzeitenueberschreitungspruefeung nicht durchgefuehrt
        // wird:
        terminal = "ZT:" + terminal;
        terminal = terminal.trim();

        boolean bAbliefern = false;

        ArtikelDto artikelDtoTaetigkeit = null;

        if (record.substring(130, 155).trim().equals("$ABLIEFERN")) {
            bAbliefern = true;
        } else {

            artikelDtoTaetigkeit = getArtikelFac().artikelFindByCNrOhneExc(record.substring(132, 155).trim(),
                    theclientDto);
        }

        ZeitdatenDto zeitdatenDto = new ZeitdatenDto();
        ZeitdatenDto zeitdatenDtoEnde = new ZeitdatenDto();
        zeitdatenDto.setCWowurdegebucht(terminal);
        zeitdatenDtoEnde.setCWowurdegebucht(terminal);

        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, new Integer(zeit.substring(0, 4)).intValue());
        c.set(Calendar.MONTH, new Integer(zeit.substring(4, 6)).intValue() - 1);
        c.set(Calendar.DAY_OF_MONTH, new Integer(zeit.substring(6, 8)).intValue());
        c.set(Calendar.HOUR_OF_DAY, new Integer(zeit.substring(8, 10)).intValue());
        c.set(Calendar.MINUTE, new Integer(zeit.substring(10, 12)).intValue());
        c.set(Calendar.SECOND, new Integer(zeit.substring(12, 14)).intValue());

        zeitdatenDto.setTZeit(new java.sql.Timestamp(c.getTime().getTime()));
        zeitdatenDtoEnde.setTZeit(new java.sql.Timestamp(c.getTime().getTime() + 1000));
        zeitdatenDto.setTAendern(zeitdatenDto.getTZeit());
        zeitdatenDtoEnde.setTAendern(zeitdatenDtoEnde.getTZeit());

        // Wenn hier NullPointerException, dann kann kein Personal mit
        // Ausweisnummer gefunden werden
        Integer personalIId = null;

        if (schluesselNr.startsWith("$P")) {
            try {
                personalIId = getPersonalFac().personalFindByCAusweis(schluesselNr.substring(2)).getIId();
            } catch (NullPointerException ex11) {
                String msg = "Person mit Ausweis " + schluesselNr + " nicht vorhanden. ORIGINAL-Request:"
                        + record;
                myLogger.error(msg, ex11);
                response.setStatus(HttpServletResponse.SC_OK);
                return getSJSPNext();

            }

        } else {
            if (command.equals(TheApp.CMD_ZE_MECS_ZEITBUCHEN)) {
                try {
                    personalIId = getPersonalFac().personalFindByCAusweis(schluesselNr).getIId();
                } catch (NullPointerException ex11) {
                    String msg = "Person mit Ausweis " + schluesselNr + " nicht vorhanden. ORIGINAL-Request:"
                            + record;
                    myLogger.error(msg, ex11);

                    response.setStatus(HttpServletResponse.SC_OK);
                    return getSJSPNext();

                }

            } else if (command.equals(TheApp.CMD_ZE_MECS_ZEITBUCHENFINGERPRINT)) {
                Integer i = new Integer(schluesselNr);
                getZutrittscontrollerFac().personalfingerFindByPrimaryKey(i).getPersonalIId();
                personalIId = getZutrittscontrollerFac().personalfingerFindByPrimaryKey(i).getPersonalIId();
            }
        }

        zeitdatenDto.setPersonalIId(personalIId);
        zeitdatenDtoEnde.setPersonalIId(personalIId);
        zeitdatenDtoEnde.setTaetigkeitIId(getZeiterfassungsFac()
                .taetigkeitFindByCNr(ZeiterfassungFac.TAETIGKEIT_ENDE, theclientDto).getIId());

        // Taetigkeiten, die MECS liefert muessen in der Tabelle LP_KEYVALUE
        // uebersetzt werden (als String)
        // Bsp: MECSTERMINAL|B1|KOMMT|java.lang.String
        try {
            String sTaetigkeit = null;

            if (schluesselNr.startsWith("$P")) {
                sTaetigkeit = record.substring(110, 126);
                Integer taetigkeitIId_Ende = getZeiterfassungsFac()
                        .taetigkeitFindByCNr(ZeiterfassungFac.TAETIGKEIT_ENDE, theclientDto).getIId();
                String gutStueck = record.substring(160, 172);
                String schlechtStueck = record.substring(173, 189);

                BigDecimal nGutStueck = new BigDecimal(gutStueck.trim());
                BigDecimal nSchlechtStueck = new BigDecimal(schlechtStueck.trim());
                Integer artikelIId = null;

                if (artikelDtoTaetigkeit == null) {
                    ParametermandantDto parameterDto = getParameterFac().getMandantparameter(mandant,
                            ParameterFac.KATEGORIE_ALLGEMEIN,
                            ParameterFac.PARAMETER_DEFAULT_ARBEITSZEITARTIKEL);

                    if (parameterDto != null && parameterDto.getCWert() != null
                            && !parameterDto.getCWert().trim().equals("")) {
                        try {
                            artikelIId = getArtikelFac().artikelFindByCNr(parameterDto.getCWert(), theclientDto)
                                    .getIId();

                        } catch (RemoteException ex2) {
                            myLogger.error("Default-Arbeitszeitartikel " + parameterDto.getCWert()
                                    + " nicht vorhanden.", ex2);
                            return getSJSPNext();
                        }

                    } else {
                        myLogger.error(
                                "Default-Arbeitszeitartikel " + parameterDto.getCWert() + " nicht definiert.");
                        return getSJSPNext();
                    }
                } else {
                    artikelIId = artikelDtoTaetigkeit.getIId();
                }

                if (sTaetigkeit.startsWith("$A")) {

                    AuftragDto auftragDto = null;
                    try {
                        if (sTaetigkeit.startsWith("$A")) {
                            auftragDto = getAuftragFac().auftragFindByMandantCNrCNr(mandant,
                                    sTaetigkeit.substring(2).trim(), theclientDto);
                        } else {
                            auftragDto = getAuftragFac().auftragFindByMandantCNrCNr(mandant,
                                    sTaetigkeit.substring(3).trim(), theclientDto);

                        }
                    } catch (RemoteException ex8) {
                        zeitdatenDto.setCBemerkungZuBelegart(
                                "Auftrag " + sTaetigkeit.substring(2).trim() + " konnte nicht gefunden werden");
                        zeitdatenDto.setTaetigkeitIId(taetigkeitIId_Ende);
                        getZeiterfassungsFac().createZeitdaten(zeitdatenDto, true, true, false, theclientDto);

                        return getSJSPNext();
                    }
                    // Wenn Auftragsbeginn ->
                    if (sTaetigkeit.startsWith("$A")) {
                        AuftragpositionDto[] auftragpositionDtos = getAuftragpositionFac()
                                .auftragpositionFindByAuftrag(auftragDto.getIId());

                        if (auftragpositionDtos.length > 0) {
                            zeitdatenDto.setCBelegartnr(LocaleFac.BELEGART_AUFTRAG);
                            zeitdatenDto.setArtikelIId(artikelIId);
                            zeitdatenDto.setIBelegartid(auftragDto.getIId());
                            zeitdatenDto.setIBelegartpositionid(auftragpositionDtos[0].getIId());
                        } else {
                            myLogger.error("Buchung von MECS-TERMINAL, Ausweis: " + schluesselNr + ", Auftrag"
                                    + sTaetigkeit + " hat keine Positionen.");
                            return getSJSPNext();
                        }
                    }
                } else if (sTaetigkeit.startsWith("$EL") || sTaetigkeit.startsWith("$L")) {

                    com.lp.server.fertigung.service.LosDto losDto = null;
                    try {
                        if (sTaetigkeit.startsWith("$L")) {

                            losDto = getFertigungFac().losFindByCNrMandantCNr(

                                    sTaetigkeit.substring(2).trim(), mandant);

                        } else {
                            losDto = getFertigungFac().losFindByCNrMandantCNr(

                                    sTaetigkeit.substring(3).trim(), mandant);

                        }

                    } catch (EJBExceptionLP ex10) {
                        zeitdatenDto.setCBemerkungZuBelegart(
                                "Los " + sTaetigkeit.substring(2).trim() + " konnte nicht gefunden werden");
                        zeitdatenDto.setTaetigkeitIId(taetigkeitIId_Ende);
                        getZeiterfassungsFac().createZeitdaten(zeitdatenDto, true, true, false, theclientDto);
                        return getSJSPNext();
                    }

                    if (bAbliefern == true) {
                        LosablieferungDto losablieferungDto = new LosablieferungDto();
                        losablieferungDto.setLosIId(losDto.getIId());
                        String menge = record.substring(155, 170);
                        BigDecimal nMenge = new BigDecimal(menge.trim());
                        losablieferungDto.setNMenge(nMenge);
                        losablieferungDto.setTAendern(zeitdatenDto.getTZeit());

                        if (nMenge.doubleValue() > 0) {
                            // lt. FM
                            BigDecimal bdBisherErledigt = getFertigungFac().getErledigteMenge(losDto.getIId(),
                                    theclientDto);

                            if (bdBisherErledigt.add(nMenge).doubleValue() > losDto.getNLosgroesse()
                                    .doubleValue()) {
                                getFertigungFac().aendereLosgroesse(losDto.getIId(),
                                        bdBisherErledigt.add(nMenge).intValue(), false, theclientDto);

                                // SP933
                                losDto.setNLosgroesse(bdBisherErledigt.add(nMenge));

                            }

                            try {
                                getFertigungFac().bucheMaterialAufLos(losDto, nMenge, false, false, true,
                                        theclientDto, null, false);
                            } catch (Exception e1) {
                                // Terminal darf keinen Fehler bekommen
                            }

                            getFertigungFac().createLosablieferungFuerTerminalOhnePreisberechnung(
                                    losablieferungDto, theclientDto, false);

                            try {
                                getFertigungFac().aktualisiereNachtraeglichPreiseAllerLosablieferungen(
                                        losDto.getIId(), theclientDto, true);
                            } catch (Exception e) {
                                // PREISBERECHNUNG FEHLGESCHLAGEN
                                myLogger.error("Preisberechnung der Ablieferungen f\u00FCr Los "
                                        + losDto.getCNr() + " fehlgeschlagen. Bitte manuell ausfuehren", e);
                            }
                        }

                        // PJ17748

                        ParametermandantDto parameterAblieferungBuchtEndeDto = getParameterFac()
                                .getMandantparameter(mandant, ParameterFac.KATEGORIE_FERTIGUNG,
                                        ParameterFac.PARAMETER_ABLIEFERUNG_BUCHT_ENDE);

                        Boolean bAblieferungBuchtEndeDto = (Boolean) parameterAblieferungBuchtEndeDto
                                .getCWertAsObject();

                        if (bAblieferungBuchtEndeDto == true) {
                            zeitdatenDto.setTaetigkeitIId(taetigkeitIId_Ende);
                            zeitdatenDto.setCBelegartnr(null);
                            zeitdatenDto.setArtikelIId(null);
                            zeitdatenDto.setIBelegartid(null);
                            zeitdatenDto.setIBelegartpositionid(null);
                            Integer zeitdatenIId = getZeiterfassungsFac().createZeitdaten(zeitdatenDto, false,
                                    false, false, theclientDto);

                            // PJ17797
                            if (nMenge.doubleValue() > 0) {
                                if (getMandantFac().darfAnwenderAufZusatzfunktionZugreifen(
                                        MandantFac.ZUSATZFUNKTION_STUECKRUECKMELDUNG, theclientDto)) {

                                    Integer lossollarbeitsplanIId = null;
                                    LossollarbeitsplanDto[] sollDtos = getFertigungFac()
                                            .lossollarbeitsplanFindByLosIId(losDto.getIId());
                                    if (sollDtos.length > 0) {
                                        lossollarbeitsplanIId = sollDtos[sollDtos.length - 1].getIId();
                                    } else {
                                        lossollarbeitsplanIId = getFertigungFac()
                                                .defaultArbeitszeitartikelErstellen(losDto, theclientDto);
                                    }

                                    LosgutschlechtDto losgutschlechtDto = new LosgutschlechtDto();
                                    losgutschlechtDto.setZeitdatenIId(zeitdatenIId);
                                    losgutschlechtDto.setLossollarbeitsplanIId(lossollarbeitsplanIId);
                                    losgutschlechtDto.setNGut(nMenge);
                                    losgutschlechtDto.setNSchlecht(new BigDecimal(0));
                                    losgutschlechtDto.setNInarbeit(new BigDecimal(0));

                                    getFertigungFac().createLosgutschlecht(losgutschlechtDto, theclientDto);
                                }
                            }

                        }

                        return getSJSPNext();
                    }

                    // Wenn Auftragsbeginn ->
                    if (sTaetigkeit.startsWith("$L")) {
                        zeitdatenDto.setCBelegartnr(LocaleFac.BELEGART_LOS);
                        zeitdatenDto.setArtikelIId(artikelIId);
                        zeitdatenDto.setIBelegartid(losDto.getIId());

                        LossollarbeitsplanDto[] sollDtos = getFertigungFac()
                                .lossollarbeitsplanFindByLosIIdArtikelIIdTaetigkeit(losDto.getIId(),
                                        artikelIId);
                        if (sollDtos.length > 0) {
                            zeitdatenDto.setIBelegartpositionid(sollDtos[0].getIId());
                        }
                    } else {
                        // Hole letzten begonnenen Auftrag und hinterlege
                        // gut/schlechtstueck
                        Session session = FLRSessionFactory.getFactory().openSession();
                        org.hibernate.Criteria liste = session.createCriteria(FLRZeitdaten.class);
                        liste.add(Expression.eq(ZeiterfassungFac.FLR_ZEITDATEN_PERSONAL_I_ID, personalIId));
                        /*
                         * liste.add(Expression.eq(ZeiterfassungFac.
                         * FLR_ZEITDATEN_C_BELEGARTNR ,
                         * LocaleFac.BELEGART_LOS)); liste.add(Expression.eq
                         * (ZeiterfassungFac.FLR_ZEITDATEN_I_BELEGARTID,
                         * losDto.getIId()));
                         */
                        liste.add(Expression.gt(ZeiterfassungFac.FLR_ZEITDATEN_T_ZEIT,
                                Helper.cutTimestamp(zeitdatenDto.getTZeit())));

                        liste.addOrder(Order.desc(ZeiterfassungFac.FLR_ZEITDATEN_T_ZEIT));
                        // liste.setMaxResults(1);
                        List<?> lReisezeiten = liste.list();

                        Iterator<?> it = lReisezeiten.iterator();
                        zeitdatenDto.setCBelegartnr(LocaleFac.BELEGART_LOS);
                        zeitdatenDto.setArtikelIId(artikelIId);
                        zeitdatenDto.setIBelegartid(losDto.getIId());

                        ZeitdatenDto letzterAuftrag = null;
                        while (it.hasNext()) {
                            FLRZeitdaten flrLetzerAuftrag = (FLRZeitdaten) it.next();

                            if (flrLetzerAuftrag.getC_belegartnr() != null
                                    && flrLetzerAuftrag.getI_belegartid() != null) {
                                if (flrLetzerAuftrag.getC_belegartnr().equals(zeitdatenDto.getCBelegartnr())
                                        && flrLetzerAuftrag.getI_belegartid()
                                                .equals(zeitdatenDto.getIBelegartid())) {
                                    letzterAuftrag = getZeiterfassungsFac().zeitdatenFindByPrimaryKey(
                                            flrLetzerAuftrag.getI_id(), theclientDto);
                                    break;
                                }
                            } else if (flrLetzerAuftrag.getTaetigkeit_i_id() != null
                                    && flrLetzerAuftrag.getTaetigkeit_i_id().equals(taetigkeitIId_Ende)) {
                                break;
                            }

                        }

                        if (letzterAuftrag != null) {
                            // Hier eintragen
                            ZeitdatenDto auftragsbeginn = getZeiterfassungsFac()
                                    .zeitdatenFindByPrimaryKey(letzterAuftrag.getIId(), theclientDto);

                            // auftragsbeginn.setNGut(nGutStueck);
                            // auftragsbeginn.setNSchlecht(nSchlechtStueck);
                            getZeiterfassungsFac().updateZeitdaten(auftragsbeginn, theclientDto);
                            // und buche ENDE
                            zeitdatenDto = zeitdatenDtoEnde;

                        } else {
                            zeitdatenDto.setCBelegartnr(LocaleFac.BELEGART_LOS);
                            zeitdatenDto.setArtikelIId(artikelIId);
                            zeitdatenDto.setIBelegartid(losDto.getIId());
                            // zeitdatenDto.setNGut(nGutStueck);
                            // zeitdatenDto.setNSchlecht(nSchlechtStueck);

                            getZeiterfassungsFac().createZeitdaten(zeitdatenDto, true, true, false,
                                    theclientDto);
                            zeitdatenDto = zeitdatenDtoEnde;
                        }
                        session.close();

                        /*
                         * if (lReisezeiten.size() > 0) { FLRZeitdaten
                         * flrZeitdaten = (FLRZeitdaten)
                         * lReisezeiten.iterator().next();
                         * 
                         * ZeitdatenDto losbeginn = getZeiterfassungsFac().
                         * zeitdatenFindByPrimaryKey(flrZeitdaten.getI_id(),
                         * cNrUser);
                         * 
                         * losbeginn.setNGut(nGutStueck);
                         * losbeginn.setNSchlecht(nSchlechtStueck);
                         * getZeiterfassungsFac().updateZeitdaten(losbeginn,
                         * cNrUser); //und buche ENDE zeitdatenDto =
                         * zeitdatenDtoEnde; } else {
                         * zeitdatenDto.setCBelegartnr
                         * (LocaleFac.BELEGART_LOS);
                         * zeitdatenDto.setArtikelIId(artikelIId);
                         * zeitdatenDto.setIBelegartid(losDto.getIId());
                         * zeitdatenDto.setNGut(nGutStueck);
                         * zeitdatenDto.setNSchlecht(nSchlechtStueck);
                         * getZeiterfassungsFac
                         * ().createZeitdaten(zeitdatenDto, true, true,
                         * cNrUser); zeitdatenDto = zeitdatenDtoEnde; }
                         * 
                         * session.close();
                         */

                    }

                } else {
                    zeitdatenDto.setTaetigkeitIId(getZeiterfassungsFac().taetigkeitFindByCNr(
                            Helper.fitString2Length(sTaetigkeit.substring(1), 15, ' '), theclientDto).getIId());
                }

            }

            else {
                sTaetigkeit = getSystemServicesFac()
                        .keyvalueFindByPrimaryKey(SystemServicesFac.KEYVALUE_MECSTERMINAL, taetigkeit)
                        .getCValue();
                if (sTaetigkeit != null && !sTaetigkeit.equals(ZeiterfassungFac.TAETIGKEIT_REISE.trim())) {
                    zeitdatenDto.setTaetigkeitIId(getZeiterfassungsFac()
                            .taetigkeitFindByCNr(Helper.fitString2Length(sTaetigkeit, 15, ' '), theclientDto)
                            .getIId());
                }
            }

            // Resezeiten wenn Taetigkeit REISE
            if (sTaetigkeit != null && sTaetigkeit.equals(ZeiterfassungFac.TAETIGKEIT_REISE.trim())) {
                ReiseDto reiseDto = new ReiseDto();
                reiseDto.setPersonalIId(personalIId);

                // Letzte Reise von HEUTE holen
                // Heute 00:00 Uhr
                Calendar cTemp = Calendar.getInstance();
                cTemp.setTimeInMillis(zeitdatenDto.getTZeit().getTime());
                cTemp.set(Calendar.HOUR_OF_DAY, 0);
                cTemp.set(Calendar.MINUTE, 0);
                cTemp.set(Calendar.SECOND, 0);
                cTemp.set(Calendar.MILLISECOND, 0);

                Session sessReise = FLRSessionFactory.getFactory().openSession();
                org.hibernate.Criteria reisezeiten = sessReise.createCriteria(FLRReise.class);
                reisezeiten.add(Expression.eq(ZeiterfassungFac.FLR_REISE_PERSONAL_I_ID, personalIId));
                reisezeiten.add(Expression.ge(ZeiterfassungFac.FLR_REISE_T_ZEIT,
                        new Timestamp(cTemp.getTimeInMillis())));
                reisezeiten.add(Expression.lt(ZeiterfassungFac.FLR_REISE_T_ZEIT, zeitdatenDto.getTZeit()));
                reisezeiten.addOrder(Order.desc(ZeiterfassungFac.FLR_REISE_T_ZEIT));
                reisezeiten.setMaxResults(1);
                List<?> lReisezeiten = reisezeiten.list();

                if (lReisezeiten.size() == 0) {
                    reiseDto.setBBeginn(Helper.boolean2Short(true));
                } else {
                    FLRReise flrReise = (FLRReise) lReisezeiten.get(0);
                    if (Helper.short2boolean(flrReise.getB_beginn()) == true) {
                        reiseDto.setBBeginn(Helper.boolean2Short(false));
                    } else {
                        reiseDto.setBBeginn(Helper.boolean2Short(true));

                    }
                }

                reiseDto.setTZeit(zeitdatenDto.getTZeit());

                Integer partnerMandant = getMandantFac().mandantFindByPrimaryKey(mandant, theclientDto)
                        .getPartnerIId();
                PartnerDto partnerDto = getPartnerFac().partnerFindByPrimaryKey(partnerMandant, theclientDto);

                if (partnerDto.getLandplzortIId() == null) {
                    throw new Exception("Mandant hat kein Land hinterlegt");
                }

                DiaetenDto[] dtos = getZeiterfassungsFac()
                        .diaetenFindByLandIId(partnerDto.getLandplzortDto().getIlandID());

                if (dtos.length == 0) {
                    // Einen anlegen
                    DiaetenDto dto = new DiaetenDto();
                    dto.setCBez(partnerDto.getLandplzortDto().getLandDto().getCName());
                    dto.setLandIId(partnerDto.getLandplzortDto().getIlandID());
                    reiseDto.setDiaetenIId(getZeiterfassungsFac().createDiaeten(dto));
                } else {
                    reiseDto.setDiaetenIId(dtos[0].getIId());
                }

                getZeiterfassungsFac().createReise(reiseDto, theclientDto);
                response.setStatus(HttpServletResponse.SC_OK);
                response.flushBuffer();
                getTheClient(request, response).setBResponseIsReady(true);

                return getSJSPNext();
            }
        } catch (Exception ex3) {
            ex3.printStackTrace();
            // lt. FM darf an das MECS-Terminal nur Status=200
            // zurueckgegeben werden
            response.setStatus(HttpServletResponse.SC_OK);
            return getSJSPNext();
        }

        getZeiterfassungsFac().createZeitdaten(zeitdatenDto, true, true, false, theclientDto);

        response.setStatus(HttpServletResponse.SC_OK);
        response.flushBuffer();
        getTheClient(request, response).setBResponseIsReady(true);
    } else if (command.equals(TheApp.CMD_ZE_QUICKZE)) {

    } else if (command.equals(TheApp.CMD_ZE_RECHNERSTART1)) {
        int i = 0;
    } else if (command.equals(TheApp.CMD_ZE_QUICKZEITERFASSUNG)) {
        if (getTheClient(request, response).getSMsg() == null) {
            getTheClient(request, response).setSMsg("");
        }

        String username = getCookieValue("anmeldename", request);
        String password = getCookieValue("pass", request);

        if (localeCookie != null && localeCookie.length() > 3) {
            localeLogon = new Locale(localeCookie.substring(0, 2), localeCookie.substring(2, 4));
        }

        if (username == null || password == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Es wurde kein Benutzername oder Kennwort angegeben. Bitte verwenden Sie http://?????cmd=quickze");

        }
        try {
            theclientDto = getLogonFac().logon(Helper.getFullUsername(username),
                    Helper.getMD5Hash((username + password).toCharArray()), localeLogon, null, null,
                    new Timestamp(System.currentTimeMillis()));
        } catch (EJBExceptionLP ex12) {

            int code = ex12.getCode();
            if (code == EJBExceptionLP.FEHLER_BEI_FINDBYPRIMARYKEY) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Benutzername '" + username + "' konnte im System nicht gefunden werden");
            } else if (code == EJBExceptionLP.FEHLER_FALSCHES_KENNWORT) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Kennwort f\u00FCr Benutzername '" + username + "' ist falsch.");
            } else if (code == EJBExceptionLP.FEHLER_BENUTZER_IST_GESPERRT) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Benutzername '" + username + "' ist gesperrt.");
            } else if (code == EJBExceptionLP.FEHLER_BENUTZER_IST_NICHT_MEHR_GUELTIG) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Benutzername '" + username + "' ist nicht mehr g\u00FCltig.");
            } else if (code == EJBExceptionLP.FEHLER_BENUTZER_DARF_SICH_BEI_DIESEM_MANDANTEN_NICHT_ANMELDEN) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Benutzername '" + username + "' darf sich bei dem Mandanten nicht anmelden.");
            } else if (code == EJBExceptionLP.FEHLER_BENUTZER_KEIN_EINTRAG_IN_BENUTZERMANDANT) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Kein Eintrag in Benutzermandant f\u00FCr Benutzername '" + username + "'.");
            } else if (ex12.getCode() == EJBExceptionLP.FEHLER_MAXIMALE_BENUTZERANZAHL_UEBERSCHRITTEN) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Maximale Benutzeranzahl \u00FCberschritten '" + username + "'.");
                return null;
            } else if (code == EJBExceptionLP.FEHLER_BENUTZER_DARF_SICH_IN_DIESER_SPRACHE_NICHT_ANMELDEN) {
                ArrayList<?> al = ((EJBExceptionLP) ex12.getCause()).getAlInfoForTheClient();
                String zusatz = "";
                if (al.size() > 0 && al.get(0) instanceof Locale) {
                    Locale loc = (Locale) al.get(0);
                    zusatz = "(" + loc.getDisplayLanguage() + "|" + loc.getDisplayCountry() + ")";
                }
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Benutzer '" + username + "' darf sich in '" + zusatz + "' nicht anmelden.");
            }

            return null;
        }

        PersonalDto personalDto = getPersonalFac().personalFindByPrimaryKey(theclientDto.getIDPersonal(),
                theclientDto);

        personalDto.setPartnerDto(
                getPartnerFac().partnerFindByPrimaryKey(personalDto.getPartnerIId(), theclientDto));

        HashMap<String, Object> hmData = new HashMap<String, Object>();

        TextDto textDto = getSystemMultilanguageFac().textFindByPrimaryKeyOhneExc("quickze.sondertaetigkeit",
                theclientDto.getMandant(), theclientDto.getLocUiAsString());
        if (textDto != null) {
            hmData.put("bezeichnung_sondertaetigkeit", textDto.getCText());
        } else {
            hmData.put("bezeichnung_sondertaetigkeit", "Sondert\u00E4tigkeit");
        }

        // Belegarten holen

        Map<String, String> b = getZeiterfassungsFac().getBebuchbareBelegarten(theclientDto);

        hmData.put("belegarten", b);

        String firstBelegart = (String) b.keySet().iterator().next();
        String belegart = null;
        if (request.getParameter("belegart") == null) {
            belegart = firstBelegart;
        } else {
            belegart = request.getParameter("belegart");
        }

        if (belegart.equals(LocaleFac.BELEGART_AUFTRAG)) {
            textDto = getSystemMultilanguageFac().textFindByPrimaryKeyOhneExc("quickze.offenerauftrag",
                    theclientDto.getMandant(), theclientDto.getLocUiAsString());
        } else if (belegart.equals(LocaleFac.BELEGART_LOS)) {
            textDto = getSystemMultilanguageFac().textFindByPrimaryKeyOhneExc("quickze.offeneslos",
                    theclientDto.getMandant(), theclientDto.getLocUiAsString());
        } else if (belegart.equals(LocaleFac.BELEGART_ANGEBOT)) {
            textDto = getSystemMultilanguageFac().textFindByPrimaryKeyOhneExc("quickze.offenesangebot",
                    theclientDto.getMandant(), theclientDto.getLocUiAsString());
        } else if (belegart.equals(LocaleFac.BELEGART_PROJEKT)) {
            textDto = getSystemMultilanguageFac().textFindByPrimaryKeyOhneExc("quickze.offenesprojekt",
                    theclientDto.getMandant(), theclientDto.getLocUiAsString());
        }
        if (textDto != null) {
            hmData.put("bezeichnung_offenerauftrag", textDto.getCText());
        } else {
            hmData.put("bezeichnung_offenerauftrag", "Offener Beleg");
        }

        textDto = getSystemMultilanguageFac().textFindByPrimaryKeyOhneExc("quickze.taetigkeit",
                theclientDto.getMandant(), theclientDto.getLocUiAsString());
        if (textDto != null) {
            hmData.put("bezeichnung_taetigkeit", textDto.getCText());
        } else {
            hmData.put("bezeichnung_taetigkeit", "T\u00E4tigkeit");
        }

        textDto = getSystemMultilanguageFac().textFindByPrimaryKeyOhneExc("quickze.kunde",
                theclientDto.getMandant(), theclientDto.getLocUiAsString());
        if (textDto != null) {
            hmData.put("bezeichnung_kunde", textDto.getCText());
        } else {
            hmData.put("bezeichnung_kunde", "Kunde");
        }

        textDto = getSystemMultilanguageFac().textFindByPrimaryKeyOhneExc("quickze.belegart",
                theclientDto.getMandant(), theclientDto.getLocUiAsString());
        if (textDto != null) {
            hmData.put("bezeichnung_belegart", textDto.getCText());
        } else {
            hmData.put("bezeichnung_belegart", "Belegart");
        }

        textDto = getSystemMultilanguageFac().textFindByPrimaryKeyOhneExc("quickze.bemerkung",
                theclientDto.getMandant(), theclientDto.getLocUiAsString());
        if (textDto != null) {
            hmData.put("bezeichnung_bemerkung", textDto.getCText());
        } else {
            hmData.put("bezeichnung_bemerkung", "Bemerkung");
        }

        hmData.put("locale", Helper.locale2String(localeLogon).trim());
        hmData.put("mandant", mandant);
        hmData.put("person", personalDto.getPartnerDto().formatAnrede());

        // Kunden mit offenen Auftraegen holen
        Session session = FLRSessionFactory.getFactory().openSession();
        String sQuery = "";
        if (belegart.equals(LocaleFac.BELEGART_AUFTRAG)) {
            sQuery = "SELECT flrkunde.flrpartner.c_name1nachnamefirmazeile1, flrkunde.flrpartner.c_name2vornamefirmazeile2, flrkunde.flrpartner.i_id "
                    + " FROM FLRAuftrag AS auftrag WHERE (auftrag.auftragstatus_c_nr='" + LocaleFac.STATUS_OFFEN
                    + "' OR auftrag.auftragstatus_c_nr='" + LocaleFac.STATUS_TEILERLEDIGT
                    + "') AND auftrag.mandant_c_nr='" + theclientDto.getMandant() + "'"
                    + "  GROUP BY flrkunde.flrpartner.c_name1nachnamefirmazeile1, flrkunde.flrpartner.c_name2vornamefirmazeile2, flrkunde.flrpartner.i_id  ORDER BY flrkunde.flrpartner.c_name1nachnamefirmazeile1 ASC";
        } else if (belegart.equals(LocaleFac.BELEGART_ANGEBOT)) {
            sQuery = "SELECT flrkunde.flrpartner.c_name1nachnamefirmazeile1, flrkunde.flrpartner.c_name2vornamefirmazeile2, flrkunde.flrpartner.i_id "
                    + " FROM FLRAngebot AS angebot WHERE (angebot.angebotstatus_c_nr='" + LocaleFac.STATUS_OFFEN
                    + "') AND angebot.mandant_c_nr='" + theclientDto.getMandant() + "'"
                    + "  GROUP BY flrkunde.flrpartner.c_name1nachnamefirmazeile1, flrkunde.flrpartner.c_name2vornamefirmazeile2, flrkunde.flrpartner.i_id  ORDER BY flrkunde.flrpartner.c_name1nachnamefirmazeile1 ASC";
        } else if (belegart.equals(LocaleFac.BELEGART_PROJEKT)) {
            sQuery = "SELECT flrpartner.c_name1nachnamefirmazeile1, flrpartner.c_name2vornamefirmazeile2, flrpartner.i_id "
                    + " FROM FLRProjekt AS projekt WHERE projekt.status_c_nr<>'"
                    + ProjektServiceFac.PROJEKT_STATUS_STORNIERT
                    + "' AND projekt.t_erledigungsdatum IS NULL AND projekt.mandant_c_nr='"
                    + theclientDto.getMandant() + "'"
                    + "  GROUP BY flrpartner.c_name1nachnamefirmazeile1, flrpartner.c_name2vornamefirmazeile2, flrpartner.i_id  ORDER BY flrpartner.c_name1nachnamefirmazeile1 ASC";

        }
        LinkedHashMap<Object, Object> tmKunden = new LinkedHashMap<Object, Object>();
        Integer firstKunde = null;
        if (!belegart.equals(LocaleFac.BELEGART_LOS)) {
            Query kunden = session.createQuery(sQuery);

            List<?> resultList = kunden.list();

            Iterator<?> resultListIterator = resultList.iterator();

            int row = 0;

            while (resultListIterator.hasNext()) {
                Object o[] = (Object[]) resultListIterator.next();
                if (row == 0) {
                    firstKunde = (Integer) o[2];
                }
                if (o[1] == null) {
                    tmKunden.put(o[2], o[0]);

                } else {
                    tmKunden.put(o[2], o[0] + " " + o[1]);

                }
                row++;
            }
            session.close();
        } else {

            sQuery = "SELECT los " + " FROM FLRLosReport AS los WHERE (los.status_c_nr='"
                    + LocaleFac.STATUS_AUSGEGEBEN + "' OR los.status_c_nr='" + LocaleFac.STATUS_IN_PRODUKTION
                    + "' OR los.status_c_nr='" + LocaleFac.STATUS_TEILERLEDIGT + "')  AND los.mandant_c_nr='"
                    + theclientDto.getMandant()
                    + "' AND ( los.flrauftrag IS NOT NULL OR los.flrkunde IS NOT NULL) ";

            Query kunden = session.createQuery(sQuery);

            List<?> resultList = kunden.list();

            Iterator<?> resultListIterator = resultList.iterator();

            int row = 0;

            while (resultListIterator.hasNext()) {
                FLRLosReport los = (FLRLosReport) resultListIterator.next();

                Integer partnerIId = null;
                String kundenname = "";
                if (los.getFlrauftrag() != null) {
                    partnerIId = los.getFlrauftrag().getFlrkunde().getFlrpartner().getI_id();

                    kundenname += los.getFlrauftrag().getFlrkunde().getFlrpartner()
                            .getC_name1nachnamefirmazeile1();

                    if (los.getFlrauftrag().getFlrkunde().getFlrpartner()
                            .getC_name2vornamefirmazeile2() != null) {
                        kundenname += " " + los.getFlrauftrag().getFlrkunde().getFlrpartner()
                                .getC_name2vornamefirmazeile2();
                    }

                } else {
                    partnerIId = los.getFlrkunde().getFlrpartner().getI_id();
                    kundenname += los.getFlrkunde().getFlrpartner().getC_name1nachnamefirmazeile1();

                    if (los.getFlrkunde().getFlrpartner().getC_name2vornamefirmazeile2() != null) {
                        kundenname += " " + los.getFlrkunde().getFlrpartner().getC_name2vornamefirmazeile2();
                    }
                }

                if (row == 0) {
                    firstKunde = partnerIId;
                }
                if (!tmKunden.containsKey(partnerIId)) {

                    tmKunden.put(partnerIId, kundenname);
                }

                row++;
            }

            tmKunden = (LinkedHashMap) Helper.sortByValue(tmKunden);

            // leeren Kunden einfuegen
            tmKunden.put("", "--KEIN--");

            session.close();
        }
        hmData.put("kunden", tmKunden);

        // Sondertaetigkeiten holen

        Map<Integer, String> m = getZeiterfassungsFac()
                .getAllSprSondertaetigkeitenNurBDEBuchbar(theclientDto.getLocUiAsString());

        hmData.put("taetigkeiten", m);

        // Kunden holen

        Integer kunde = null;
        if (request.getParameter("kunde") == null) {
            kunde = firstKunde;
        } else {
            if (!request.getParameter("kunde").equals("")) {
                if (!request.getParameter("kunde").equals(" ")) {
                    if (!request.getParameter("kunde").trim().equals("null")) {
                        kunde = new Integer(request.getParameter("kunde").trim());
                    }
                }

            }
        }

        hmData.put("selectedbelegart", belegart);

        session = FLRSessionFactory.getFactory().openSession();

        if (belegart.equals(LocaleFac.BELEGART_AUFTRAG)) {

            sQuery = "SELECT auftrag.i_id, auftrag.c_nr, auftrag.c_bez, auftrag.t_liefertermin, auftrag.flrkunde.flrpartner.i_id "
                    + " FROM FLRAuftrag AS auftrag WHERE (auftrag.auftragstatus_c_nr='" + LocaleFac.STATUS_OFFEN
                    + "' OR auftrag.auftragstatus_c_nr='" + LocaleFac.STATUS_TEILERLEDIGT
                    + "') AND auftrag.flrkunde.flrpartner.i_id=" + kunde
                    + " AND auftrag.b_versteckt=0 ORDER BY auftrag.c_nr ASC";
        } else if (belegart.equals(LocaleFac.BELEGART_LOS)) {
            sQuery = "SELECT los.i_id, los.c_nr, los.c_projekt, los.t_produktionsende, coalesce(auftragpartner.i_id,kundepartner.i_id) "
                    + " FROM FLRLosReport AS los LEFT OUTER JOIN los.flrauftrag.flrkunde.flrpartner as auftragpartner LEFT OUTER JOIN los.flrkunde.flrpartner as kundepartner  WHERE (los.status_c_nr='"
                    + LocaleFac.STATUS_AUSGEGEBEN + "' OR los.status_c_nr='" + LocaleFac.STATUS_IN_PRODUKTION
                    + "' OR los.status_c_nr='" + LocaleFac.STATUS_TEILERLEDIGT + "') ";
            if (kunde != null) {
                sQuery += " AND ( auftragpartner.i_id=" + kunde + " OR kundepartner.i_id=" + kunde + ")";

            } else {
                sQuery += " AND ( auftragpartner.i_id IS NULL AND kundepartner.i_id IS NULL)";
            }
            sQuery += " ORDER BY los.c_nr ASC";
        } else if (belegart.equals(LocaleFac.BELEGART_ANGEBOT)) {
            sQuery = "SELECT angebot.i_id, angebot.c_nr, angebot.c_bez, angebot.t_realisierungstermin, angebot.flrkunde.flrpartner.i_id "
                    + " FROM FLRAngebot AS angebot WHERE angebot.angebotstatus_c_nr='" + LocaleFac.STATUS_OFFEN
                    + "' AND angebot.flrkunde.flrpartner.i_id=" + kunde + "  ORDER BY angebot.c_nr ASC";
        } else if (belegart.equals(LocaleFac.BELEGART_PROJEKT)) {
            sQuery = "SELECT projekt.i_id, projekt.c_nr, projekt.c_titel, projekt.t_zielwunschdatum, projekt.partner_i_id "
                    + " FROM FLRProjekt AS projekt WHERE projekt.status_c_nr<>'"
                    + ProjektServiceFac.PROJEKT_STATUS_STORNIERT
                    + "' AND projekt.t_erledigungsdatum IS NULL AND projekt.partner_i_id=" + kunde
                    + " ORDER BY projekt.c_nr ASC";
        }
        Query auftraege = session.createQuery(sQuery);

        List<?> resultList = auftraege.list();

        Iterator resultListIterator = resultList.iterator();
        LinkedHashMap<Object, Object> tmAuftraege = new LinkedHashMap<Object, Object>();
        Object partnerIId = null;
        String selectedAuftragId = null;
        while (resultListIterator.hasNext()) {
            Object o[] = (Object[]) resultListIterator.next();
            partnerIId = (Integer) o[4];

            if (o[2] == null) {
                tmAuftraege.put(o[0], o[1]);

            } else {
                tmAuftraege.put(o[0], o[1] + " " + o[2]);

            }
            if (selectedAuftragId == null) {
                selectedAuftragId = o[0].toString();
            }
        }

        session.close();
        hmData.put("auftraege", tmAuftraege);

        hmData.put("selectedkunde", partnerIId);

        if (request.getParameter("auftrag") != null && request.getParameter("auftrag").length() > 0) {
            selectedAuftragId = request.getParameter("auftrag");

        }

        // Artikel zu Auftrag holen
        session = FLRSessionFactory.getFactory().openSession();

        if (belegart.equals(LocaleFac.BELEGART_AUFTRAG)) {

            sQuery = "SELECT a.i_id, a.flrartikel.i_id FROM FLRAuftragposition AS a WHERE a.flrauftrag.i_id="
                    + selectedAuftragId + " AND a.flrartikel.artikelart_c_nr='"
                    + ArtikelFac.ARTIKELART_ARBEITSZEIT + "'";
        } else if (belegart.equals(LocaleFac.BELEGART_LOS)) {

            sQuery = "SELECT a.i_id, a.flrartikel.i_id FROM FLRLossollarbeitsplan AS a WHERE a.los_i_id="
                    + selectedAuftragId + " AND a.flrartikel.artikelart_c_nr='"
                    + ArtikelFac.ARTIKELART_ARBEITSZEIT + "'";
        } else if (belegart.equals(LocaleFac.BELEGART_ANGEBOT)) {

            sQuery = "SELECT a.i_id, a.flrartikel.i_id FROM FLRAngebotposition AS a WHERE a.flrangebot.i_id="
                    + selectedAuftragId + " AND a.flrartikel.artikelart_c_nr='"
                    + ArtikelFac.ARTIKELART_ARBEITSZEIT + "'";
        }
        LinkedHashMap<Object, Object> tmArtikel = new LinkedHashMap<Object, Object>();
        if (!belegart.equals(LocaleFac.BELEGART_PROJEKT)) {
            Query artikelListe = session.createQuery(sQuery);

            resultList = artikelListe.list();

            resultListIterator = resultList.iterator();

            if (resultList.size() > 0) {
                tmArtikel.put(-1, " - - - - - - Beleg - - - - - -");
            }

            while (resultListIterator.hasNext()) {
                Object[] zeile = (Object[]) resultListIterator.next();

                Integer artikelIId = (Integer) zeile[1];

                String sollIst = "";

                if (belegart.equals(LocaleFac.BELEGART_AUFTRAG)) {

                    BigDecimal bdSoll = getAuftragpositionFac()
                            .auftragpositionFindByPrimaryKey((Integer) zeile[0]).getNMenge();
                    sollIst = "; Soll: " + Helper.formatZahl(bdSoll, 2, theclientDto.getLocUi());

                    Double dIst;
                    try {

                        boolean bZuvieleZeitbuchungen = getZeiterfassungsFac()
                                .sindZuvieleZeitdatenEinesBelegesVorhanden(belegart,
                                        new Integer(selectedAuftragId), theclientDto);
                        if (bZuvieleZeitbuchungen == false) {

                            dIst = getZeiterfassungsFac().getSummeZeitenEinesBeleges(belegart,
                                    new Integer(selectedAuftragId), (Integer) zeile[0], null, null, null,
                                    theclientDto);
                            sollIst += " Ist: " + Helper.formatZahl(dIst, 2, theclientDto.getLocUi());
                        }
                    } catch (Exception e) {
                        sollIst += " Ist: ERR";
                    }

                }

                String artikel = getArtikelFac().artikelFindByPrimaryKey(artikelIId, theclientDto)
                        .formatArtikelbezeichnung() + sollIst;
                if (!tmArtikel.containsKey(artikelIId)) {
                    tmArtikel.put(artikelIId, artikel);

                }
            }
            session.close();
        }
        // Artikel des Auftrags + Artikel aus Personalverfuegbarkeit holen

        if (selectedAuftragId != null) {

            PersonalverfuegbarkeitDto[] personalverfuegbarkeitDtos = getPersonalFac()
                    .personalverfuegbarkeitFindByPersonalIId(personalDto.getIId());
            if (personalverfuegbarkeitDtos.length > 0) {
                tmArtikel.put(-2, " - - - Verf\u00FCgbarkeit - - - ");
            }
            for (int i = 0; i < personalverfuegbarkeitDtos.length; i++) {
                PersonalverfuegbarkeitDto v = personalverfuegbarkeitDtos[i];
                String artikel = getArtikelFac().artikelFindByPrimaryKey(v.getArtikelIId(), theclientDto)
                        .formatArtikelbezeichnung();
                tmArtikel.put(v.getArtikelIId(), artikel);
            }

            hmData.put("selectedauftrag", selectedAuftragId);

        }

        ParametermandantDto parameterDtoDefaultarbeitszeit = getParameterFac().getMandantparameter(mandant,
                ParameterFac.KATEGORIE_ALLGEMEIN, ParameterFac.PARAMETER_DEFAULT_ARBEITSZEITARTIKEL);

        if (parameterDtoDefaultarbeitszeit != null && parameterDtoDefaultarbeitszeit.getCWert() != null
                && !parameterDtoDefaultarbeitszeit.getCWert().trim().equals("")) {

            ArtikelDto artikelDtoDefaultArbeiztszeit = getArtikelFac()
                    .artikelFindByCNr(parameterDtoDefaultarbeitszeit.getCWert(), theclientDto);
            tmArtikel.put(-3, " - - - Default-Arbeitszeitartikel - - -");
            tmArtikel.put(artikelDtoDefaultArbeiztszeit.getIId(),
                    artikelDtoDefaultArbeiztszeit.formatArtikelbezeichnung());
        }

        hmData.put("artikel", tmArtikel);

        // Zeitbuchen
        String bucheauftrag = request.getParameter("bucheauftrag");
        String buchesondertaetigkeit = request.getParameter("buchesondertaetigkeit");

        // Zeit buchen
        ZeitdatenDto zeitdatenDto = new ZeitdatenDto();
        zeitdatenDto.setPersonalIId(personalDto.getIId());
        Timestamp tZeit = new Timestamp(System.currentTimeMillis());
        zeitdatenDto.setCWowurdegebucht("Quick-ZE " + request.getRemoteHost());
        String meldung = "";

        zeitdatenDto.setTZeit(tZeit);
        String bemerkung = request.getParameter("bemerkung");
        zeitdatenDto.setCBemerkungZuBelegart(bemerkung);

        if (bucheauftrag != null && bucheauftrag.length() > 0) {

            if (request.getParameter("artikel") != null) {

                Integer artikelId = new Integer(request.getParameter("artikel"));
                if (artikelId > 0) {

                    Integer auftragIId = new Integer(selectedAuftragId.trim());

                    String s = "Auf ";

                    if (kunde != null) {
                        PartnerDto partnerDto = getPartnerFac().partnerFindByPrimaryKey(kunde, theclientDto);
                        s += partnerDto.formatFixName1Name2() + ", ";
                    }

                    if (belegart.equals(LocaleFac.BELEGART_AUFTRAG)) {
                        textDto = getSystemMultilanguageFac().textFindByPrimaryKeyOhneExc("quickze.auftrag",
                                theclientDto.getMandant(), theclientDto.getLocUiAsString());

                        if (textDto != null) {
                            s += textDto.getCText() + " ";
                        } else {
                            s += "Auftrag ";
                        }

                        com.lp.server.auftrag.service.AuftragDto auftragDto = getAuftragFac()
                                .auftragFindByPrimaryKey(auftragIId);
                        s += auftragDto.getCNr();
                        if (auftragDto.getCBezProjektbezeichnung() != null) {
                            s += " " + auftragDto.getCBezProjektbezeichnung();
                        }

                        com.lp.server.auftrag.service.AuftragpositionDto[] auftragpositionDtos = getAuftragpositionFac()
                                .auftragpositionFindByAuftrag(auftragIId);
                        if (auftragpositionDtos.length > 0) {
                            zeitdatenDto.setIBelegartpositionid(auftragpositionDtos[0].getIId());
                        }
                    } else if (belegart.equals(LocaleFac.BELEGART_ANGEBOT)) {
                        textDto = getSystemMultilanguageFac().textFindByPrimaryKeyOhneExc("angb.angebot",
                                theclientDto.getMandant(), theclientDto.getLocUiAsString());

                        if (textDto != null) {
                            s += textDto.getCText() + " ";
                        } else {
                            s += "Angebot ";
                        }

                        com.lp.server.angebot.service.AngebotDto auftragDto = getAngebotFac()
                                .angebotFindByPrimaryKey(auftragIId, theclientDto);
                        s += auftragDto.getCNr();
                        if (auftragDto.getCBez() != null) {
                            s += " " + auftragDto.getCBez();
                        }

                    } else if (belegart.equals(LocaleFac.BELEGART_PROJEKT)) {
                        textDto = getSystemMultilanguageFac().textFindByPrimaryKeyOhneExc(
                                "lp.projekt.modulname", theclientDto.getMandant(),
                                theclientDto.getLocUiAsString());

                        if (textDto != null) {
                            s += textDto.getCText() + " ";
                        } else {
                            s += "Projekt ";
                        }

                        com.lp.server.projekt.service.ProjektDto auftragDto = getProjektFac()
                                .projektFindByPrimaryKey(auftragIId);
                        s += auftragDto.getCNr();
                        if (auftragDto.getCTitel() != null) {
                            s += " " + auftragDto.getCTitel();
                        }

                    } else if (belegart.equals(LocaleFac.BELEGART_LOS)) {
                        textDto = getSystemMultilanguageFac().textFindByPrimaryKeyOhneExc(
                                "fert.tab.unten.los.title", theclientDto.getMandant(),
                                theclientDto.getLocUiAsString());

                        if (textDto != null) {
                            s += textDto.getCText() + " ";
                        } else {
                            s += "Los ";
                        }

                        LosDto auftragDto = getFertigungFac().losFindByPrimaryKey(auftragIId);
                        s += auftragDto.getCNr();
                        if (auftragDto.getCProjekt() != null) {
                            s += " " + auftragDto.getCProjekt();
                        }

                        LossollarbeitsplanDto[] dtos = getFertigungFac()
                                .lossollarbeitsplanFindByLosIIdArtikelIIdTaetigkeit(auftragIId, artikelId);
                        if (dtos.length > 0) {
                            zeitdatenDto.setIBelegartpositionid(dtos[0].getIId());
                        }

                    }
                    zeitdatenDto.setPersonalIId(personalDto.getIId());
                    zeitdatenDto.setCBelegartnr(belegart);
                    zeitdatenDto.setIBelegartid(auftragIId);
                    zeitdatenDto.setArtikelIId(artikelId);

                    ArtikelDto artikelDto = getArtikelFac().artikelFindByPrimaryKey(artikelId, theclientDto);

                    meldung += s + ", " + artikelDto.formatArtikelbezeichnung();

                    getZeiterfassungsFac().createZeitdaten(zeitdatenDto, true, true, false, theclientDto);
                    meldung += " um " + Helper.formatTime(tZeit, localeLogon) + " gebucht.";
                    getTheClient(request, response).setSMsg(meldung);
                }
            } else {

                getTheClient(request, response).setSMsg("Keine Auftragsposition ausgew\u00E4hlt");
            }
        } else if (buchesondertaetigkeit != null && buchesondertaetigkeit.length() > 0) {
            String zusatz = request.getParameter("zusatz");

            if (zusatz != null && zusatz.length() > 0) {
                // Zeit ist immer jetzt
                Calendar c = Calendar.getInstance();
                c.setTimeInMillis(zeitdatenDto.getTZeit().getTime());
                ZeitdatenDto[] letzeBuchungen = getZeiterfassungsFac()
                        .zeitdatenFindZeitdatenEinesTagesUndEinerPersonOnheBelegzeiten(
                                zeitdatenDto.getPersonalIId(), Helper.cutTimestamp(zeitdatenDto.getTZeit()),
                                zeitdatenDto.getTZeit());
                Integer taetigkeitIId_Kommt = getZeiterfassungsFac()
                        .taetigkeitFindByCNr(ZeiterfassungFac.TAETIGKEIT_KOMMT, theclientDto).getIId();
                Integer taetigkeitIId_Unter = getZeiterfassungsFac()
                        .taetigkeitFindByCNr(ZeiterfassungFac.TAETIGKEIT_UNTER, theclientDto).getIId();
                Integer taetigkeitIId_Geht = getZeiterfassungsFac()
                        .taetigkeitFindByCNr(ZeiterfassungFac.TAETIGKEIT_GEHT, theclientDto).getIId();
                if (zusatz.equals("spezialkommt")) {

                    if (letzeBuchungen.length == 0) {
                        // Zuerst Kommt und dann UNTER
                        ZeitdatenDto dtoKommt = new ZeitdatenDto();
                        dtoKommt.setTaetigkeitIId(taetigkeitIId_Kommt);
                        dtoKommt.setPersonalIId(zeitdatenDto.getPersonalIId());
                        dtoKommt.setCWowurdegebucht("Spezial-Kommt");
                        // Zeit 100 MS vorher
                        dtoKommt.setTZeit(new Timestamp(zeitdatenDto.getTZeit().getTime()));
                        getZeiterfassungsFac().createZeitdaten(dtoKommt, false, false, false, theclientDto);
                        // Taetigkeit GEHT Buchen
                        ZeitdatenDto dtoUnter = new ZeitdatenDto();
                        dtoUnter.setTaetigkeitIId(taetigkeitIId_Unter);
                        dtoUnter.setPersonalIId(zeitdatenDto.getPersonalIId());
                        dtoUnter.setCWowurdegebucht("Spezial-Kommt");
                        // Zeit 100 MS nachher
                        dtoUnter.setTZeit(new Timestamp(zeitdatenDto.getTZeit().getTime() + 96));
                        getZeiterfassungsFac().createZeitdaten(dtoUnter, false, false, false, theclientDto);
                    } else if (letzeBuchungen.length == 1) {
                        Integer letztetaetigkeit = letzeBuchungen[0].getTaetigkeitIId();
                        // Wenn nur Kommt, dann Unter buchen
                        if (taetigkeitIId_Kommt.equals(letztetaetigkeit)) {
                            // Taetigkeit UNTER Buchen
                            ZeitdatenDto dtoUnter = new ZeitdatenDto();
                            dtoUnter.setTaetigkeitIId(taetigkeitIId_Unter);
                            dtoUnter.setPersonalIId(zeitdatenDto.getPersonalIId());
                            dtoUnter.setCWowurdegebucht("Spezial-Kommt");
                            dtoUnter.setTZeit(new Timestamp(zeitdatenDto.getTZeit().getTime()));
                            getZeiterfassungsFac().createZeitdaten(dtoUnter, false, false, false, theclientDto);

                        }
                    } else if (letzeBuchungen.length > 1) {
                        Integer letztetaetigkeit = letzeBuchungen[letzeBuchungen.length - 1].getTaetigkeitIId();
                        if (taetigkeitIId_Kommt.equals(letztetaetigkeit)) {
                            // Taetigkeit UNTER Buchen
                            ZeitdatenDto dtoUnter = new ZeitdatenDto();
                            dtoUnter.setTaetigkeitIId(taetigkeitIId_Unter);
                            dtoUnter.setPersonalIId(zeitdatenDto.getPersonalIId());
                            dtoUnter.setCWowurdegebucht("Spezial-Kommt");
                            dtoUnter.setTZeit(new Timestamp(zeitdatenDto.getTZeit().getTime()));
                            getZeiterfassungsFac().createZeitdaten(dtoUnter, false, false, false, theclientDto);

                        } else {

                            // Wenn letzte Taetigkeit ein Geht ist wird
                            // Kommt
                            // und Unter gebucht
                            if (!taetigkeitIId_Geht.equals(letztetaetigkeit)) {

                                int iSondertaetigkeitenHintereinander = 1;
                                for (int i = letzeBuchungen.length - 2; i >= 0; i--) {
                                    ZeitdatenDto dto = letzeBuchungen[i];
                                    if (letztetaetigkeit.equals(dto.getTaetigkeitIId())) {
                                        iSondertaetigkeitenHintereinander++;
                                    } else {
                                        break;
                                    }
                                    letztetaetigkeit = dto.getTaetigkeitIId();
                                }

                                if (iSondertaetigkeitenHintereinander % 2 == 0) {
                                    // Taetigkeit UNTER Buchen
                                    ZeitdatenDto dtoUnter = new ZeitdatenDto();
                                    dtoUnter.setTaetigkeitIId(taetigkeitIId_Unter);
                                    dtoUnter.setPersonalIId(zeitdatenDto.getPersonalIId());
                                    dtoUnter.setCWowurdegebucht("Spezial-Geht");
                                    dtoUnter.setTZeit(new Timestamp(zeitdatenDto.getTZeit().getTime()));
                                    getZeiterfassungsFac().createZeitdaten(dtoUnter, false, false, false,
                                            theclientDto);

                                    /**
                                     * @todo 100ms vorher Projekt-ENDE
                                     *       buchen
                                     */
                                }
                            } else {
                                // Taetigkeit KOMMT Buchen
                                ZeitdatenDto dtoKommt = new ZeitdatenDto();
                                dtoKommt.setTaetigkeitIId(taetigkeitIId_Kommt);
                                dtoKommt.setPersonalIId(zeitdatenDto.getPersonalIId());
                                dtoKommt.setCWowurdegebucht("Spezial-Kommt");
                                dtoKommt.setTZeit(new Timestamp(zeitdatenDto.getTZeit().getTime()));
                                getZeiterfassungsFac().createZeitdaten(dtoKommt, false, false, false,
                                        theclientDto);
                                // Taetigkeit UNTER Buchen
                                ZeitdatenDto dtoUnter = new ZeitdatenDto();
                                dtoUnter.setTaetigkeitIId(taetigkeitIId_Unter);
                                dtoUnter.setPersonalIId(zeitdatenDto.getPersonalIId());
                                dtoUnter.setCWowurdegebucht("Spezial-Kommt");
                                // Zeit 100 MS nachher
                                dtoUnter.setTZeit(new Timestamp(zeitdatenDto.getTZeit().getTime() + 96));
                                getZeiterfassungsFac().createZeitdaten(dtoUnter, false, false, false,
                                        theclientDto);

                            }
                        }
                    }

                } else if (zusatz.equals("spezialgeht")) {
                    if (letzeBuchungen.length > 1) {

                        Integer letztetaetigkeit = letzeBuchungen[letzeBuchungen.length - 1].getTaetigkeitIId();
                        // Wenn letzte Taetigkeit kein geht ist, sonst wird
                        // geht verschmissen
                        if (!taetigkeitIId_Geht.equals(letztetaetigkeit)) {

                            int iSondertaetigkeitenHintereinander = 1;
                            for (int i = letzeBuchungen.length - 2; i >= 0; i--) {
                                ZeitdatenDto dto = letzeBuchungen[i];
                                if (letztetaetigkeit.equals(dto.getTaetigkeitIId())) {
                                    iSondertaetigkeitenHintereinander++;
                                } else {
                                    break;
                                }
                                letztetaetigkeit = dto.getTaetigkeitIId();
                            }

                            if (iSondertaetigkeitenHintereinander % 2 == 1) {
                                // Sondertaetigkeit Ende Buchen
                                ZeitdatenDto dtoSonderEnde = new ZeitdatenDto();
                                dtoSonderEnde.setTaetigkeitIId(letztetaetigkeit);
                                dtoSonderEnde.setPersonalIId(zeitdatenDto.getPersonalIId());
                                dtoSonderEnde.setCWowurdegebucht("Spezial-Geht");
                                // Zeit 100 MS vorher
                                dtoSonderEnde.setTZeit(new Timestamp(zeitdatenDto.getTZeit().getTime() - 96));
                                getZeiterfassungsFac().createZeitdaten(dtoSonderEnde, false, false, false,
                                        theclientDto);
                                // Taetigkeit GEHT Buchen
                                ZeitdatenDto dtoUnter = new ZeitdatenDto();
                                dtoUnter.setTaetigkeitIId(taetigkeitIId_Geht);
                                dtoUnter.setPersonalIId(zeitdatenDto.getPersonalIId());
                                dtoUnter.setCWowurdegebucht("Spezial-Geht");
                                // Zeit 100 MS vorher
                                dtoUnter.setTZeit(new Timestamp(zeitdatenDto.getTZeit().getTime()));
                                getZeiterfassungsFac().createZeitdaten(dtoUnter, false, false, false,
                                        theclientDto);

                            } else {
                                // Taetigkeit GEHT Buchen
                                ZeitdatenDto dtoUnter = new ZeitdatenDto();
                                dtoUnter.setTaetigkeitIId(taetigkeitIId_Geht);
                                dtoUnter.setPersonalIId(zeitdatenDto.getPersonalIId());
                                dtoUnter.setCWowurdegebucht("Spezial-Geht");
                                // Zeit 100 MS vorher
                                dtoUnter.setTZeit(new Timestamp(zeitdatenDto.getTZeit().getTime()));
                                getZeiterfassungsFac().createZeitdaten(dtoUnter, false, false, false,
                                        theclientDto);

                            }
                        }

                    }

                } else {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "zusatz '" + zusatz + "' unbekannt");
                }
                setSJSPNext("mecs.jsp");
                return getSJSPNext();
            } else {

                if (request.getParameter("taetigkeit") != null) {

                    Integer taetigkeitId = new Integer(request.getParameter("taetigkeit"));
                    zeitdatenDto.setTaetigkeitIId(taetigkeitId);

                    TaetigkeitDto dto = getZeiterfassungsFac().taetigkeitFindByPrimaryKey(taetigkeitId,
                            theclientDto);
                    meldung += dto.getBezeichnung();

                    getZeiterfassungsFac().createZeitdaten(zeitdatenDto, true, true, false, theclientDto);
                    meldung += " um " + Helper.formatTime(tZeit, localeLogon) + " gebucht.";
                    getTheClient(request, response).setSMsg(meldung);
                } else {
                    getTheClient(request, response).setSMsg("Keine T\u00E4tigkeit ausgew\u00E4hlt");
                }
            }
        }
        getTheClient(request, response).setData(hmData);
        // AD+CK logout wegen usercount
        synchronized (mutex) { // PJ 15986
            getLogonFac().logout(theclientDto);
        }
    } else if (command.equals(TheApp.CMD_ZU_MECS_TERMINAL)) {
        // Personalstamm holen

        String master = request.getParameter("master");

        try {
            ZutrittscontrollerDto zutrittscontrollerDto = getZutrittscontrollerFac()
                    .zutrittscontrollerFindByCNr(master);
            ZutrittsobjektDto[] zutrittsobjektDtos = getZutrittscontrollerFac()
                    .zutrittsobjektFindByZutrittscontrollerIId(zutrittscontrollerDto.getIId());

            StringBuffer objekte = new StringBuffer();

            for (int i = 0; i < zutrittsobjektDtos.length; i++) {
                objekte.append(Helper.fitString2Length(zutrittsobjektDtos[i].getCNr(), 6, ' ')); // terminal-
                // id
                objekte.append(Helper.fitString2Length(zutrittsobjektDtos[i].getCAdresse(), 100, ' ')); // adresse
                objekte.append("\r\n");
            }
            myLogger.info(command + ":" + new String(objekte));

            getTheClient(request, response).setSMsg(new String(objekte));
        }

        catch (RemoteException ex5) {
            if (ex5.getCause() instanceof EJBExceptionLP) {
                EJBExceptionLP lpex = (EJBExceptionLP) ex5.getCause();
                if (lpex.getCode() == EJBExceptionLP.FEHLER_BEI_FIND) {
                    myLogger.error("Zutrittscontroller '" + master + "' nicht angelegt", ex5);
                } else {
                    myLogger.error(ex5.getMessage(), ex5);
                }
            }

        }
    } else if (command.equals(TheApp.CMD_ZU_MECS_RELAIS)) {
        // Personalstamm holen

        String termid = request.getParameter("termid");
        if (termid == null || termid.length() == 0) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Es ist der Parameter termid='LanPortName' erforderlich");
            return null;
        }
        try {
            ZutrittsobjektDto zutrittsobjektDto = getZutrittscontrollerFac().zutrittsobjektFindByCNr(termid);

            StringBuffer objekte = new StringBuffer();

            objekte.append("10"); // readerid
            objekte.append("0"); // port
            objekte.append(zutrittsobjektDto.getCRelais()); // relais
            String oeffnungszeit = zutrittsobjektDto.getFOeffnungszeit().toString();
            oeffnungszeit = oeffnungszeit.replaceAll(",", ".");
            objekte.append(Helper.fitString2LengthAlignRight(oeffnungszeit, 4, ' ')); // oeffnungszeit
            objekte.append(zutrittsobjektDto.getZutrittsleserCNr().trim()); // readerid
            objekte.append("\r\n");
            myLogger.info(command + ":" + new String(objekte));

            getTheClient(request, response).setSMsg(new String(objekte));
        } catch (EJBExceptionLP ex4) {

            if (ex4.getCode() == EJBExceptionLP.FEHLER_BEI_FIND) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND,
                        "Zutrittsobjekt '" + termid + "' nicht angelegt");
                return null;
            } else {
                ex4.printStackTrace();
                myLogger.error(ex4.getMessage(), ex4);
            }

        }
    } else if (command.equals(TheApp.CMD_ZU_MECS_ZUTRITT)) {
        String termid = request.getParameter("termid");
        try {
            ZutrittsobjektDto dto = getZutrittscontrollerFac().zutrittsobjektFindByCNr(termid);

            String s = getZutrittscontrollerFac().getZutrittsdatenFuerEinObjektFuerMecs(dto.getIId(),
                    theclientDto);
            myLogger.info(command + ":" + new String(s));

            getTheClient(request, response).setSMsg(new String(s));
        } catch (EJBExceptionLP ex4) {
            if (ex4.getCode() == EJBExceptionLP.FEHLER_BEI_FIND) {
                myLogger.error("Zutrittsobjekt '" + termid + "' nicht angelegt", ex4);
                response.sendError(HttpServletResponse.SC_NOT_FOUND,
                        "Zutrittsobjekt '" + termid + "' nicht angelegt");

            } else {
                myLogger.error(ex4.getMessage(), ex4);
                response.sendError(HttpServletResponse.SC_NOT_FOUND, ex4.getMessage());
            }

        }

    } else if (command.equals(TheApp.CMD_ZU_MECS_AUSWEISE_ZUTRITT)) {
        PersonalzutrittsklasseDto[] dtos = getZutrittscontrollerFac().personalzutrittsklassenFindByTGueltigab(
                new Timestamp(System.currentTimeMillis()), theclientDto);

        ArrayList<StringBuffer> alDaten = new ArrayList<StringBuffer>();

        for (int i = 0; i < dtos.length; i++) {
            StringBuffer sb = new StringBuffer();
            sb.append("10");

            // Hole personalDto
            PersonalDto personalDto = getPersonalFac().personalFindByPrimaryKeySmall(dtos[i].getPersonalIId());

            sb.append(Helper.fitString2Length(personalDto.getCAusweis(), 20, ' '));
            sb.append(Helper.fitString2Length(personalDto.getCPersonalnr().toString(), 10, ' '));
            sb.append(Helper.fitString2Length("", 24, ' '));

            // Hole Zutrittsklasse
            ZutrittsklasseDto zutrittsklasseDto = getZutrittscontrollerFac()
                    .zutrittsklasseFindByPrimaryKey(dtos[i].getZutrittsklasseIId());
            sb.append(Helper.fitString2Length(zutrittsklasseDto.getCNr(), 3, ' '));
            alDaten.add(sb);
        }

        // Besucherausweise
        String[] ausweise = getZutrittscontrollerFac()
                .zutrittonlinecheckAusweiseFindByTGueltigab(new Timestamp(System.currentTimeMillis()));

        for (int i = 0; i < ausweise.length; i++) {
            StringBuffer sb = new StringBuffer();
            sb.append("10");
            sb.append(Helper.fitString2Length(ausweise[i], 20, ' '));
            sb.append(Helper.fitString2Length("", 10, ' '));
            sb.append(Helper.fitString2Length("", 24, ' '));
            sb.append(Helper.fitString2Length(ZutrittscontrollerFac.ZUTRITTSKLASSE_ONLINECHECK, 3, ' '));
            alDaten.add(sb);
        }

        // sortieren
        String datenGesamt = "";
        for (int i = alDaten.size() - 1; i > 0; --i) {
            for (int j = 0; j < i; ++j) {
                if ((new String(alDaten.get(j))).compareTo(new String(alDaten.get(j + 1))) > 0) {
                    StringBuffer lagerbewegungDtoTemp = alDaten.get(j);
                    alDaten.set(j, alDaten.get(j + 1));
                    alDaten.set(j + 1, lagerbewegungDtoTemp);
                }
            }
        }

        for (int i = 0; i < alDaten.size(); i++) {

            StringBuffer sbTemp = alDaten.get(i);
            sbTemp.append("\r\n");
            datenGesamt += new String(sbTemp);
        }

        myLogger.info(command + ":" + datenGesamt);
        getTheClient(request, response).setSMsg(datenGesamt);
    } else if (command.startsWith(TheApp.CMD_ZU_MECS_ZUTRITT_ONLINE_CHECK)) {
        String termid = request.getParameter("termid");

        String card = request.getParameter("card");
        String pin = request.getParameter("pin");

        try {
            ZutrittsobjektDto dto = getZutrittscontrollerFac().zutrittsobjektFindByCNr(termid);
            boolean b = getZutrittscontrollerFac().onlineCheck(card, pin,
                    new Timestamp(System.currentTimeMillis()), dto.getIId());
            if (b == true) {
                myLogger.info(command + ": ZUTRITT ERLAUBT");
                getTheClient(request, response).setSMsg("A");

            } else {
                myLogger.info(command + ": ZUTRITT VERWEIGERT");
                getTheClient(request, response).setSMsg("Z");
            }
        } catch (EJBExceptionLP ex4) {
            if (ex4.getCause() instanceof EJBExceptionLP) {
                EJBExceptionLP lpex = (EJBExceptionLP) ex4.getCause();
                if (lpex.getCode() == EJBExceptionLP.FEHLER_BEI_FIND) {

                    response.sendError(HttpServletResponse.SC_NOT_FOUND,
                            "Zutrittsobjekt '" + termid + "' nicht angelegt");
                    myLogger.error("Zutrittsobjekt '" + termid + "' nicht angelegt", ex4);
                } else {
                    myLogger.error(ex4.getMessage(), ex4);
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, ex4.getMessage());
                }
            }
        }

    } else if (command.startsWith(TheApp.CMD_ZU_MECS_ZUTRITT_EVENTS)) {
        String termid = request.getParameter("termid");

        if (termid == null || termid.length() == 0) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Es ist der Parameter termid='LanPortName' erforderlich");
            return null;
        }

        ZutrittsobjektDto dto = null;
        try {
            dto = getZutrittscontrollerFac().zutrittsobjektFindByCNr(termid);
        } catch (EJBExceptionLP e) {
            if (e.getCode() == EJBExceptionLP.FEHLER_BEI_FIND) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND,
                        "Zutrittsobjekt '" + termid + "' nicht angelegt");
                return null;
            } else {
                e.printStackTrace();
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Unerwarteter Fehler aufgetreten.");
                return null;
            }
        }

        String s = getZutrittscontrollerFac().getZutrittsEventsFuerMecs(dto.getIId(), theclientDto);
        myLogger.info(command + ":" + s);
        getTheClient(request, response).setSMsg(s);

    } else if (command.startsWith(TheApp.CMD_ZU_MECS_MAXTRANSNR)) {
        getTheClient(request, response).setSMsg("999");
    } else if (command.startsWith(TheApp.CMD_ZU_MECS_LOG)) {

        String record = command.substring(17);
        ZutrittslogDto dto = new ZutrittslogDto();

        Calendar c = Calendar.getInstance();
        String zeitpunkt = record.substring(5, 19);
        int iJahr = new Integer(zeitpunkt.substring(0, 4));
        int iMonat = new Integer(zeitpunkt.substring(4, 6)) - 1;
        int iTag = new Integer(zeitpunkt.substring(6, 8));
        int iStunden = new Integer(zeitpunkt.substring(8, 10));
        int iMinuten = new Integer(zeitpunkt.substring(10, 12));
        int iSekunden = new Integer(zeitpunkt.substring(12, 14));

        c.set(iJahr, iMonat, iTag, iStunden, iMinuten, iSekunden);
        dto.setTZeitpunkt(new Timestamp(c.getTimeInMillis()));
        String personalnr = record.substring(19, 24);
        String erlaubt = record.substring(24, 27);
        String objekt = record.substring(46, 67).trim();
        String ausweis = record.substring(106, 135).trim();
        String event = record.substring(126, 137).trim();

        PersonalDto personalDto = getPersonalFac().personalFindByCAusweis(ausweis);

        if (personalDto != null || event.equals("PINONLINE") || personalnr.equals("?????")
                || personalnr.equals("     ")) {
            if (personalDto != null) {
                dto.setCPerson(
                        getPartnerFac().partnerFindByPrimaryKey(personalDto.getPartnerIId(), theclientDto)
                                .formatFixAnredeTitelName2Name1());
                dto.setMandantCNr(personalDto.getMandantCNr());
            } else if (personalnr.equals("     ")) {
                dto.setCPerson("Besucher");
                dto.setMandantCNr(mandant);
            } else if (event != null && event.equals("PINONLINE")) {
                dto.setCPerson("Tempor\u00E4rer Pin-Code");
                dto.setMandantCNr(mandant);
            } else {
                dto.setCPerson("Unbekannt");
                dto.setMandantCNr(mandant);
            }

            if (erlaubt.equals("ZZ1")) {
                dto.setBErlaubt(Helper.boolean2Short(true));
            } else {
                dto.setBErlaubt(Helper.boolean2Short(false));
            }

            dto.setCAusweis(ausweis);
            dto.setCZutrittscontroller(null);

            try {
                ZutrittsobjektDto zutrittsobjektDto = getZutrittscontrollerFac()
                        .zutrittsobjektFindByCNr(objekt);

                dto.setCZutrittsobjekt(
                        zutrittsobjektDto.getBezeichnung() + "-" + zutrittsobjektDto.getCAdresse());
                dto.setCZutrittscontroller(getZutrittscontrollerFac()
                        .zutrittscontrollerFindByPrimaryKey(zutrittsobjektDto.getZutrittscontrollerIId())
                        .getCNr());
                dto.setMandantCNrObjekt(zutrittsobjektDto.getMandantCNr());
            } catch (RemoteException ex6) {
                dto.setCZutrittsobjekt("Zutrittsobjekt unbekannt");
            }

            getZutrittscontrollerFac().createZutrittslog(dto);
        }

        myLogger.info(command);

    } else if (command.startsWith(TheApp.CMD_ZU_MECS_TEMPLATES)) {

        String sAendern = request.getParameter("changedsince");

        PersonalfingerDto[] personalfingerDtos = null;
        if (sAendern == null) {
            personalfingerDtos = getZutrittscontrollerFac().personalfingerFindAll();

        } else {

            Calendar c = Calendar.getInstance();
            int iJahr = new Integer(sAendern.substring(0, 4));
            int iMonat = new Integer(sAendern.substring(4, 6)) - 1;
            int iTag = new Integer(sAendern.substring(6, 8));
            int iStunden = new Integer(sAendern.substring(8, 10));
            int iMinuten = new Integer(sAendern.substring(10, 12));

            c.set(iJahr, iMonat, iTag, iStunden, iMinuten, 0);
            c.set(Calendar.MILLISECOND, 0);

            personalfingerDtos = getZutrittscontrollerFac()
                    .personalfingerFindByTAendern(new java.sql.Timestamp(c.getTimeInMillis()), theclientDto);
        }
        StringBuffer sb = new StringBuffer();
        // Zuerts alle loeschen
        sb.append(Helper.fitString2LengthAlignRight("0", 5, ' '));
        sb.append(Helper.fitString2LengthAlignRight("0", 2, ' '));
        sb.append(Helper.fitString2Length("X", 512, 'X'));
        StringBuffer zeit = new StringBuffer();
        Calendar cAendern = Calendar.getInstance();
        zeit.append(Helper.fitString2Length(cAendern.get(Calendar.YEAR) + "", 4, '0'));
        zeit.append(Helper.fitString2Length((cAendern.get(Calendar.MONTH) + 1) + "", 2, '0'));
        zeit.append(Helper.fitString2Length(cAendern.get(Calendar.DAY_OF_MONTH) + "", 2, '0'));
        zeit.append(Helper.fitString2Length(cAendern.get(Calendar.HOUR_OF_DAY) + "", 2, '0'));
        zeit.append(Helper.fitString2Length(cAendern.get(Calendar.MINUTE) + "", 2, '0'));

        sb.append(zeit);
        sb.append("\r\n");

        for (int i = 0; i < personalfingerDtos.length; i++) {
            PersonalfingerDto personalfingerDto = personalfingerDtos[i];
            sb.append(Helper.fitString2LengthAlignRight(personalfingerDto.getIId() + "", 5, ' '));
            sb.append(Helper.fitString2LengthAlignRight("1", 2, ' '));
            String templateBase64 = new String(
                    org.apache.commons.codec.binary.Base64.encodeBase64(personalfingerDto.getOTemplate1()));
            sb.append(Helper.fitString2Length(templateBase64, 512, ' '));

            cAendern = Calendar.getInstance();
            cAendern.setTimeInMillis(personalfingerDto.getTAendern().getTime());
            zeit = new StringBuffer();
            zeit.append(Helper.fitString2Length(cAendern.get(Calendar.YEAR) + "", 4, '0'));
            zeit.append(Helper.fitString2Length((cAendern.get(Calendar.MONTH) + 1) + "", 2, '0'));
            zeit.append(Helper.fitString2Length(cAendern.get(Calendar.DAY_OF_MONTH) + "", 2, '0'));
            zeit.append(Helper.fitString2Length(cAendern.get(Calendar.HOUR_OF_DAY) + "", 2, '0'));
            zeit.append(Helper.fitString2Length(cAendern.get(Calendar.MINUTE) + "", 2, '0'));

            sb.append(zeit);
            sb.append("\r\n");

            if (personalfingerDto.getOTemplate2() != null) {
                sb.append(Helper.fitString2LengthAlignRight(personalfingerDto.getIId() + "", 5, ' '));
                sb.append(Helper.fitString2LengthAlignRight("2", 2, ' '));
                templateBase64 = new String(
                        org.apache.commons.codec.binary.Base64.encodeBase64(personalfingerDto.getOTemplate2()));
                sb.append(Helper.fitString2Length(templateBase64, 512, ' '));
                sb.append(zeit);
                if (i == personalfingerDtos.length - 1) {
                    // sb.append("\r");
                } else {
                    sb.append("\r\n");
                }
            }

        }
        getTheClient(request, response).setSMsg(new String(sb));

    }

    return getSJSPNext();
}

From source file:edu.harvard.iq.dvn.core.web.servlet.FileDownloadServlet.java

public void service(HttpServletRequest req, HttpServletResponse res) {

    // Parameters:

    // 1. Extracted from the session:

    VDCUser user = null;/*from w  ww. j  a v  a  2  s.  c  om*/
    if (vdcSession.getLoginBean() != null) {
        user = vdcSession.getLoginBean().getUser();
    }

    VDC vdc = vdcService.getVDCFromRequest(req);

    UserGroup ipUserGroup = null;
    if (req.getSession(true).getAttribute("ipUserGroup") != null) {
        ipUserGroup = (UserGroup) req.getSession().getAttribute("ipUserGroup");
    }

    // 2. HTTP parameters:

    String fileId = req.getParameter("fileId");
    String formatRequested = req.getParameter("format");
    String downloadOriginalFormat = req.getParameter("downloadOriginalFormat");
    String imageThumb = req.getParameter("imageThumb");
    String noVarHeader = req.getParameter("noVarHeader");
    String versionNumber = req.getParameter("versionNumber");

    // Single file download request:

    if (fileId != null && (!fileId.contains(","))) {

        // This is done in a few easy steps:

        // step 1. look up the studyfile by id:

        StudyFile file = lookupStudyFile(fileId);

        if (file == null) {
            createErrorResponse404(res);
            return;
        }

        // step 2. perform access authorization check:

        if (!isAccessAuthorized(file, req, user, vdc, ipUserGroup)) {
            // generate a response with a correct 403/FORBIDDEN code
            createErrorResponse403(res);
            return;
        }

        // step 3. initiate download object/subsystem:

        FileDownloadObject fileDownloadObject = initiateDownloadObject(file, req);

        if (fileDownloadObject == null || (fileDownloadObject.getStatus() != 200)) {

            if (fileDownloadObject != null) {
                if (fileDownloadObject.getStatus() == 403) {
                    createErrorResponse403Remote(res);
                } else {
                    // generic "not found" message:
                    createErrorResponse404(res);
                }
                fileDownloadObject.releaseConnection();
            } else {
                createErrorResponse404(res);
            }
            return;

        }

        // step 4a. perform format conversion, if requested:

        if (formatRequested != null) {
            fileDownloadObject = performFormatConversion(file, fileDownloadObject, formatRequested);

        }

        // step 4b. see if this is a "download as original" request:

        else if (downloadOriginalFormat != null) {
            fileDownloadObject = lookupOriginalFormat(file, fileDownloadObject);
        }

        // step 4c. or if it's a request for a thumbnail of an image:

        else if (imageThumb != null) {
            fileDownloadObject = getImageThumb(file, fileDownloadObject);
        }

        // step 5. create error response if any of the above has failed:

        if (fileDownloadObject == null) {
            // generate error response:
            createErrorResponse404(res);

            //fileDownloadObject.releaseConnection();
            return;
        }

        // step 6. set the headers in the HTTP response and stream the
        // data:

        deliverContent(file, fileDownloadObject, res);

        // step 7. increment the appropriate download counters:
        // (but only if it's not a LOCKSS crawl OR a thumbnail!)

        if (!isLockssCrawlRequest(req) && imageThumb == null) {
            String jsessionId = null;
            javax.servlet.http.Cookie cookies[] = req.getCookies();

            for (int i = 0; i < cookies.length; i++) {
                if ("JSESSIONID".equals(cookies[i].getName())) {
                    jsessionId = cookies[i].getValue();
                }
            }
            incrementDownloadCounts(file, vdc, fileDownloadObject.getMimeType(), jsessionId, versionNumber);
        }

        // done!
        // End of single file download.

    } else { // a request for a zip-packaged multiple file archive.
        zipMultipleFiles(req, res, user, vdc, ipUserGroup);
    }

    return;
}

From source file:de.tu_dortmund.ub.api.paia.auth.PaiaAuthEndpoint.java

protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    ObjectMapper mapper = new ObjectMapper();

    String format;/*from  w ww  . jav a  2  s . com*/
    String language;
    String redirect_url;

    this.logger.debug("PathInfo = " + httpServletRequest.getPathInfo());
    this.logger.debug("QueryString = " + httpServletRequest.getQueryString());

    String service = "";
    String authorization = "";

    String path = httpServletRequest.getPathInfo();
    String[] params = path.substring(1, path.length()).split("/");

    if (params.length == 1) {
        service = params[0];
    }

    format = "html";
    language = "";

    // Hole 'Accept' und 'Authorization' aus dem Header;
    Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {

        String headerNameKey = (String) headerNames.nextElement();
        this.logger.debug("headerNameKey = " + headerNameKey + " / headerNameValue = "
                + httpServletRequest.getHeader(headerNameKey));

        if (headerNameKey.equals("Accept")) {

            this.logger.debug("headerNameKey = " + httpServletRequest.getHeader(headerNameKey));

            if (httpServletRequest.getHeader(headerNameKey).contains("text/html")) {
                format = "html";
            } else if (httpServletRequest.getHeader(headerNameKey).contains("application/xml")) {
                format = "xml";
            } else if (httpServletRequest.getHeader(headerNameKey).contains("application/json")) {
                format = "json";
            }
        }
        if (headerNameKey.equals("Accept-Language")) {
            language = httpServletRequest.getHeader(headerNameKey);
            this.logger.debug("Accept-Language: " + language);
        }
        if (headerNameKey.equals("Authorization")) {
            authorization = httpServletRequest.getHeader(headerNameKey);
        }
    }

    this.logger.debug("Service: " + service);

    if (httpServletRequest.getParameter("format") != null
            && !httpServletRequest.getParameter("format").equals("")) {

        format = httpServletRequest.getParameter("format");
    }

    this.logger.info("format = " + format);

    if (format.equals("html") && Lookup.lookupAll(ObjectToHtmlTransformation.class).size() == 0) {

        this.logger.error(HttpServletResponse.SC_BAD_REQUEST + ": " + "html not implemented!");

        // Error handling mit suppress_response_codes=true
        if (httpServletRequest.getParameter("suppress_response_codes") != null) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        }
        // Error handling mit suppress_response_codes=false (=default)
        else {
            httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

        // Json fr Response body
        RequestError requestError = new RequestError();
        requestError.setError(
                this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST)));
        requestError.setCode(HttpServletResponse.SC_BAD_REQUEST);
        requestError.setDescription(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description"));
        requestError.setErrorUri(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri"));

        this.sendRequestError(httpServletResponse, requestError, format, language, "");
    } else {

        // redirect_url
        redirect_url = "";

        if (httpServletRequest.getParameter("redirect_url") != null
                && !httpServletRequest.getParameter("redirect_url").equals("")) {

            if (httpServletRequest.getParameter("redirect_url").contains("redirect_url=")) {
                String tmp[] = httpServletRequest.getParameter("redirect_url").split("redirect_url=");

                redirect_url = tmp[0] + "redirect_url=" + URLEncoder.encode(tmp[1], "UTF-8");
            } else {
                redirect_url = httpServletRequest.getParameter("redirect_url");
            }
        }

        this.logger.info("redirect_url = " + redirect_url);

        // language
        if (language.startsWith("de")) {
            language = "de";
        } else if (language.startsWith("en")) {
            language = "en";
        } else if (httpServletRequest.getParameter("l") != null) {
            language = httpServletRequest.getParameter("l");
        } else {
            language = "de";
        }

        this.logger.info("language = " + language);

        if (authorization.equals("") && httpServletRequest.getParameter("access_token") != null) {

            authorization = httpServletRequest.getParameter("access_token");
        }

        if (authorization.equals("")) {

            // if exists PaiaService-Cookie: read content
            Cookie[] cookies = httpServletRequest.getCookies();

            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("PaiaService")) {

                        String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
                        this.logger.info(value);
                        LoginResponse loginResponse = mapper.readValue(value, LoginResponse.class);

                        authorization = loginResponse.getAccess_token();

                        break;
                    }
                }
            }
        }

        this.logger.debug("Access_token: " + authorization);

        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = httpServletRequest.getReader();
            while ((line = reader.readLine()) != null)
                jb.append(line);
        } catch (Exception e) {
            /*report an error*/ }

        String requestBody = jb.toString();

        this.logger.info(requestBody);

        httpServletResponse.setHeader("Access-Control-Allow-Origin",
                this.config.getProperty("Access-Control-Allow-Origin"));
        httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control"));

        // 2. Schritt: Service
        if (service.equals("login") || service.equals("logout") || service.equals("change")
                || service.equals("renew")) {

            this.provideService(httpServletRequest, httpServletResponse, service, authorization, requestBody,
                    format, language, redirect_url);
        } else {

            this.logger.error(HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + "POST for '" + service
                    + "' not allowed!");

            // Error handling mit suppress_response_codes=true
            if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            }
            // Error handling mit suppress_response_codes=false (=default)
            else {
                httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }

            // Json fr Response body
            RequestError requestError = new RequestError();
            requestError.setError(this.config
                    .getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED)));
            requestError.setCode(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            requestError.setDescription(this.config.getProperty(
                    "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".description"));
            requestError.setErrorUri(this.config.getProperty(
                    "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".uri"));

            this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
        }
    }
}