Example usage for javax.servlet.http HttpServletResponse flushBuffer

List of usage examples for javax.servlet.http HttpServletResponse flushBuffer

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse flushBuffer.

Prototype

public void flushBuffer() throws IOException;

Source Link

Document

Forces any content in the buffer to be written to the client.

Usage

From source file:org.exist.http.urlrewrite.XQueryURLRewrite.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws IOException, ServletException {
    if (rewriteConfig == null) {
        configure();/*  ww  w .  ja  va 2s.c o m*/
        rewriteConfig = new RewriteConfig(this);
    }

    final long start = System.currentTimeMillis();
    final HttpServletRequest request = servletRequest;
    final HttpServletResponse response = servletResponse;

    if (LOG.isTraceEnabled()) {
        LOG.trace(request.getRequestURI());
    }
    final Descriptor descriptor = Descriptor.getDescriptorSingleton();
    if (descriptor != null && descriptor.requestsFiltered()) {
        final String attr = (String) request.getAttribute("XQueryURLRewrite.forwarded");
        if (attr == null) {
            //                request = new HttpServletRequestWrapper(request, /*formEncoding*/ "utf-8" );
            //logs the request if specified in the descriptor
            descriptor.doLogRequestInReplayLog(request);

            request.setAttribute("XQueryURLRewrite.forwarded", "true");
        }
    }

    Subject user = defaultUser;

    Subject requestUser = HttpAccount.getUserFromServletRequest(request);
    if (requestUser != null) {
        user = requestUser;
    } else {
        // Secondly try basic authentication
        final String auth = request.getHeader("Authorization");
        if (auth != null) {
            requestUser = authenticator.authenticate(request, response);
            if (requestUser != null) {
                user = requestUser;
            }
        }
    }

    try {
        configure();
        //checkCache(user);

        final RequestWrapper modifiedRequest = new RequestWrapper(request);
        final URLRewrite staticRewrite = rewriteConfig.lookup(modifiedRequest);
        if (staticRewrite != null && !staticRewrite.isControllerForward()) {
            modifiedRequest.setPaths(staticRewrite.resolve(modifiedRequest), staticRewrite.getPrefix());

            if (LOG.isTraceEnabled()) {
                LOG.trace("Forwarding to target: " + staticRewrite.getTarget());
            }
            staticRewrite.doRewrite(modifiedRequest, response);
        } else {

            if (LOG.isTraceEnabled()) {
                LOG.trace("Processing request URI: " + request.getRequestURI());
            }
            if (staticRewrite != null) {
                // fix the request URI
                staticRewrite.updateRequest(modifiedRequest);
            }

            // check if the request URI is already in the url cache
            ModelAndView modelView = getFromCache(request.getHeader("Host") + request.getRequestURI(), user);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Checked cache for URI: " + modifiedRequest.getRequestURI() + " original: "
                        + request.getRequestURI());
            }
            // no: create a new model and view configuration
            if (modelView == null) {
                modelView = new ModelAndView();
                // Execute the query
                Sequence result = Sequence.EMPTY_SEQUENCE;
                DBBroker broker = null;
                try {
                    broker = pool.get(user);
                    modifiedRequest.setAttribute(RQ_ATTR_REQUEST_URI, request.getRequestURI());

                    final Properties outputProperties = new Properties();

                    outputProperties.setProperty(OutputKeys.INDENT, "yes");
                    outputProperties.setProperty(OutputKeys.ENCODING, "UTF-8");
                    outputProperties.setProperty(OutputKeys.MEDIA_TYPE, MimeType.XML_TYPE.getName());

                    result = runQuery(broker, modifiedRequest, response, modelView, staticRewrite,
                            outputProperties);

                    logResult(broker, result);

                    if (response.isCommitted()) {
                        return;
                    }

                    // process the query result
                    if (result.getItemCount() == 1) {
                        final Item resource = result.itemAt(0);
                        if (!Type.subTypeOf(resource.getType(), Type.NODE)) {
                            throw new ServletException(
                                    "XQueryURLRewrite: urlrewrite query should return an element!");
                        }
                        Node node = ((NodeValue) resource).getNode();
                        if (node.getNodeType() == Node.DOCUMENT_NODE) {
                            node = ((Document) node).getDocumentElement();
                        }
                        if (node.getNodeType() != Node.ELEMENT_NODE) {
                            //throw new ServletException("Redirect XQuery should return an XML element!");
                            response(broker, response, outputProperties, result);
                            return;
                        }
                        Element elem = (Element) node;
                        if (!(Namespaces.EXIST_NS.equals(elem.getNamespaceURI()))) {
                            response(broker, response, outputProperties, result);
                            return;
                            //                            throw new ServletException("Redirect XQuery should return an element in namespace " + Namespaces.EXIST_NS);
                        }

                        if (Namespaces.EXIST_NS.equals(elem.getNamespaceURI())
                                && "dispatch".equals(elem.getLocalName())) {
                            node = elem.getFirstChild();
                            while (node != null) {
                                if (node.getNodeType() == Node.ELEMENT_NODE
                                        && Namespaces.EXIST_NS.equals(node.getNamespaceURI())) {
                                    final Element action = (Element) node;
                                    if ("view".equals(action.getLocalName())) {
                                        parseViews(modifiedRequest, action, modelView);
                                    } else if ("error-handler".equals(action.getLocalName())) {
                                        parseErrorHandlers(modifiedRequest, action, modelView);
                                    } else if ("cache-control".equals(action.getLocalName())) {
                                        final String option = action.getAttribute("cache");
                                        modelView.setUseCache("yes".equals(option));
                                    } else {
                                        final URLRewrite urw = parseAction(modifiedRequest, action);
                                        if (urw != null) {
                                            modelView.setModel(urw);
                                        }
                                    }
                                }
                                node = node.getNextSibling();
                            }
                            if (modelView.getModel() == null) {
                                modelView.setModel(new PassThrough(config, elem, modifiedRequest));
                            }
                        } else if (Namespaces.EXIST_NS.equals(elem.getNamespaceURI())
                                && "ignore".equals(elem.getLocalName())) {
                            modelView.setModel(new PassThrough(config, elem, modifiedRequest));
                            final NodeList nl = elem.getElementsByTagNameNS(Namespaces.EXIST_NS,
                                    "cache-control");
                            if (nl.getLength() > 0) {
                                elem = (Element) nl.item(0);
                                final String option = elem.getAttribute("cache");
                                modelView.setUseCache("yes".equals(option));
                            }
                        } else {
                            response(broker, response, outputProperties, result);
                            return;
                        }
                    } else if (result.getItemCount() > 1) {
                        response(broker, response, outputProperties, result);
                        return;
                    }

                    if (modelView.useCache()) {
                        LOG.debug("Caching request to " + request.getRequestURI());
                        urlCache.put(modifiedRequest.getHeader("Host") + request.getRequestURI(), modelView);
                    }

                } finally {
                    pool.release(broker);
                }

                // store the original request URI to org.exist.forward.request-uri
                modifiedRequest.setAttribute(RQ_ATTR_REQUEST_URI, request.getRequestURI());
                modifiedRequest.setAttribute(RQ_ATTR_SERVLET_PATH, request.getServletPath());

            }
            if (LOG.isTraceEnabled()) {
                LOG.trace("URLRewrite took " + (System.currentTimeMillis() - start) + "ms.");
            }
            final HttpServletResponse wrappedResponse = new CachingResponseWrapper(response,
                    modelView.hasViews() || modelView.hasErrorHandlers());
            if (modelView.getModel() == null) {
                modelView.setModel(new PassThrough(config, modifiedRequest));
            }

            if (staticRewrite != null) {
                if (modelView.getModel().doResolve()) {
                    staticRewrite.rewriteRequest(modifiedRequest);
                } else {
                    modelView.getModel().setAbsolutePath(modifiedRequest);
                }
            }
            modifiedRequest.allowCaching(!modelView.hasViews());
            doRewrite(modelView.getModel(), modifiedRequest, wrappedResponse);

            int status = ((CachingResponseWrapper) wrappedResponse).getStatus();
            if (status == HttpServletResponse.SC_NOT_MODIFIED) {
                response.flushBuffer();
            } else if (status < 400) {
                if (modelView.hasViews()) {
                    applyViews(modelView, modelView.views, response, modifiedRequest, wrappedResponse);
                } else {
                    ((CachingResponseWrapper) wrappedResponse).flush();
                }
            } else {
                // HTTP response code indicates an error
                if (modelView.hasErrorHandlers()) {
                    final byte[] data = ((CachingResponseWrapper) wrappedResponse).getData();
                    if (data != null) {
                        modifiedRequest.setAttribute(RQ_ATTR_ERROR, new String(data, UTF_8));
                    }
                    applyViews(modelView, modelView.errorHandlers, response, modifiedRequest, wrappedResponse);
                } else {
                    flushError(response, wrappedResponse);
                }
            }
        }
        //            Sequence result;
        //            if ((result = (Sequence) request.getAttribute(RQ_ATTR_RESULT)) != null) {
        //                writeResults(response, broker, result);
        //            }
    } catch (final Throwable e) {
        LOG.error("Error while processing " + servletRequest.getRequestURI() + ": " + e.getMessage(), e);
        throw new ServletException("An error occurred while processing request to "
                + servletRequest.getRequestURI() + ": " + e.getMessage(), e);

    }
}

From source file:com.ibm.ioes.dao.ReportsDao.java

private void columnHeadeForParallelUpgrade(HttpServletResponse response, StringBuffer row) throws Exception {
    PrintWriter pw = response.getWriter();
    try {/*from   w w  w .j  a  v a 2s  . com*/
        startRow(row);
        addCell(row, "Customer Segment");
        addCell(row, "Order Type");
        addCell(row, "Change Type");
        addCell(row, "Customer Name");
        addCell(row, "CRM_Order_ID");
        addCell(row, "Order Date");
        addCell(row, "COPC Approval Date");
        addCell(row, "Logical Circuit Id");
        addCell(row, "Service No");
        addCell(row, "Change Reason");
        addCell(row, "LSI_Disconnection_SR_No");
        addCell(row, "Service_Stage");
        addCell(row, "Service BT Action Date");
        addCell(row, "Attribute Remarks");
        addCell(row, "Bin");
        addCell(row, "OLD LSI");
        addCell(row, "OLD LSI _Latest stage");
        addCell(row, "Old_Lsi_BT_Action_Date");
        addCell(row, "OLD_LSI_Disconnetion_SRNO");
        endRow(row);

        pw.write(row.toString());
        response.flushBuffer();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.ibm.ioes.dao.ReportsDao.java

private void savedatainexcel(ParallelUpgradeReportDto objReportsDto, HttpServletResponse response)
        throws Exception {

    PrintWriter pw = response.getWriter();

    StringBuffer row = new StringBuffer();
    try {/*from   w w  w  . ja va 2  s.  c o  m*/

        startRow(row);
        addCell(row, objReportsDto.getCustomerSegment());
        addCell(row, objReportsDto.getOrderType());
        addCell(row, objReportsDto.getChangeType());
        addCell(row, objReportsDto.getCustomername());
        addCellint(row, objReportsDto.getCrm_order_id());
        addCell(row, objReportsDto.getOrderDate());
        addCell(row, objReportsDto.getCopcApprovalDate());
        addCellint(row, objReportsDto.getLogical_si_no());
        addCellint(row, objReportsDto.getServiceNo());
        addCell(row, objReportsDto.getChangeReason());
        addCell(row, objReportsDto.getLsi_disconnection_SRNO());
        addCell(row, objReportsDto.getService_stage());
        addCell(row, objReportsDto.getServiceBTActionDate());
        addCell(row, objReportsDto.getAttribute_remarks());
        addCell(row, objReportsDto.getBin());
        addCellint(row, objReportsDto.getOld_lsi());
        addCell(row, objReportsDto.getOld_lsi_lateststage());
        addCell(row, objReportsDto.getOld_lsi_BT_ActionDate());
        addCell(row, objReportsDto.getOld_lsi_disconnection_SRno());
        endRow(row);

        pw.write(row.toString());
        response.flushBuffer();
    } catch (Exception e) {
        e.printStackTrace();
    }
    /*finally{
    if(null != pw)
       pw.close();
    }*/
}

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

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

    /**//from  w  ww .  j  av a  2  s .  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:org.epics.archiverappliance.retrieval.DataRetrievalServlet.java

private void doGetSinglePV(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    PoorMansProfiler pmansProfiler = new PoorMansProfiler();
    String pvName = req.getParameter("pv");

    if (configService.getStartupState() != STARTUP_SEQUENCE.STARTUP_COMPLETE) {
        String msg = "Cannot process data retrieval requests for PV " + pvName
                + " until the appliance has completely started up.";
        logger.error(msg);//from w  ww .  j a v a2  s. co m
        resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, msg);
        return;
    }

    String startTimeStr = req.getParameter("from");
    String endTimeStr = req.getParameter("to");
    boolean useReduced = false;
    String useReducedStr = req.getParameter("usereduced");
    if (useReducedStr != null && !useReducedStr.equals("")) {
        try {
            useReduced = Boolean.parseBoolean(useReducedStr);
        } catch (Exception ex) {
            logger.error("Exception parsing usereduced", ex);
            useReduced = false;
        }
    }
    String extension = req.getPathInfo().split("\\.")[1];
    logger.info("Mime is " + extension);

    boolean useChunkedEncoding = true;
    String doNotChunkStr = req.getParameter("donotchunk");
    if (doNotChunkStr != null && !doNotChunkStr.equals("false")) {
        logger.info("Turning off HTTP chunked encoding");
        useChunkedEncoding = false;
    }

    boolean fetchLatestMetadata = false;
    String fetchLatestMetadataStr = req.getParameter("fetchLatestMetadata");
    if (fetchLatestMetadataStr != null && fetchLatestMetadataStr.equals("true")) {
        logger.info("Adding a call to the engine to fetch the latest metadata");
        fetchLatestMetadata = true;
    }

    // For data retrieval we need a PV info. However, in case of PV's that have long since retired, we may not want to have PVTypeInfo's in the system.
    // So, we support a template PV that lays out the data sources.
    // During retrieval, you can pass in the PV as a template and we'll clone this and make a temporary copy.
    String retiredPVTemplate = req.getParameter("retiredPVTemplate");

    if (pvName == null) {
        String msg = "PV name is null.";
        resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }

    if (pvName.equals(ARCH_APPL_PING_PV)) {
        logger.debug("Processing ping PV - this is used to validate the connection with the client.");
        processPingPV(req, resp);
        return;
    }

    if (pvName.endsWith(".VAL")) {
        int len = pvName.length();
        pvName = pvName.substring(0, len - 4);
        logger.info("Removing .VAL from pvName for request giving " + pvName);
    }

    // ISO datetimes are of the form "2011-02-02T08:00:00.000Z"
    Timestamp end = TimeUtils.plusHours(TimeUtils.now(), 1);
    if (endTimeStr != null) {
        try {
            end = TimeUtils.convertFromISO8601String(endTimeStr);
        } catch (IllegalArgumentException ex) {
            try {
                end = TimeUtils.convertFromDateTimeStringWithOffset(endTimeStr);
            } catch (IllegalArgumentException ex2) {
                String msg = "Cannot parse time" + endTimeStr;
                logger.warn(msg, ex2);
                resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
                return;
            }
        }
    }

    // We get one day by default
    Timestamp start = TimeUtils.minusDays(end, 1);
    if (startTimeStr != null) {
        try {
            start = TimeUtils.convertFromISO8601String(startTimeStr);
        } catch (IllegalArgumentException ex) {
            try {
                start = TimeUtils.convertFromDateTimeStringWithOffset(startTimeStr);
            } catch (IllegalArgumentException ex2) {
                String msg = "Cannot parse time " + startTimeStr;
                logger.warn(msg, ex2);
                resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
                return;
            }
        }
    }

    if (end.before(start)) {
        String msg = "For request, end " + end.toString() + " is before start " + start.toString() + " for pv "
                + pvName;
        logger.error(msg);
        resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    LinkedList<TimeSpan> requestTimes = new LinkedList<TimeSpan>();

    // We can specify a list of time stamp pairs using the optional timeranges parameter
    String timeRangesStr = req.getParameter("timeranges");
    if (timeRangesStr != null) {
        boolean continueWithRequest = parseTimeRanges(resp, pvName, requestTimes, timeRangesStr);
        if (!continueWithRequest) {
            // Cannot parse the time ranges properly; we so abort the request.
            return;
        }

        // Override the start and the end so that the mergededup consumer works correctly.
        start = requestTimes.getFirst().getStartTime();
        end = requestTimes.getLast().getEndTime();

    } else {
        requestTimes.add(new TimeSpan(start, end));
    }

    assert (requestTimes.size() > 0);

    String postProcessorUserArg = req.getParameter("pp");
    if (pvName.contains("(")) {
        if (!pvName.contains(")")) {
            logger.error("Unbalanced paran " + pvName);
            resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        String[] components = pvName.split("[(,)]");
        postProcessorUserArg = components[0];
        pvName = components[1];
        if (components.length > 2) {
            for (int i = 2; i < components.length; i++) {
                postProcessorUserArg = postProcessorUserArg + "_" + components[i];
            }
        }
        logger.info("After parsing the function call syntax pvName is " + pvName
                + " and postProcessorUserArg is " + postProcessorUserArg);
    }

    PostProcessor postProcessor = PostProcessors.findPostProcessor(postProcessorUserArg);

    PVTypeInfo typeInfo = PVNames.determineAppropriatePVTypeInfo(pvName, configService);
    pmansProfiler.mark("After PVTypeInfo");

    if (typeInfo == null && RetrievalState.includeExternalServers(req)) {
        logger.debug("Checking to see if pv " + pvName + " is served by a external Archiver Server");
        typeInfo = checkIfPVisServedByExternalServer(pvName, start, req, resp, useChunkedEncoding);
    }

    if (typeInfo == null) {
        if (resp.isCommitted()) {
            logger.debug("Proxied the data thru an external server for PV " + pvName);
            return;
        }
    }

    if (typeInfo == null) {
        if (retiredPVTemplate != null) {
            PVTypeInfo templateTypeInfo = PVNames.determineAppropriatePVTypeInfo(retiredPVTemplate,
                    configService);
            if (templateTypeInfo != null) {
                typeInfo = new PVTypeInfo(pvName, templateTypeInfo);
                typeInfo.setPaused(true);
                typeInfo.setApplianceIdentity(configService.getMyApplianceInfo().getIdentity());
                // Somehow tell the code downstream that this is a fake typeInfo.
                typeInfo.setSamplingMethod(SamplingMethod.DONT_ARCHIVE);
                logger.debug("Using a template PV for " + pvName + " Need to determine the actual DBR type.");
                setActualDBRTypeFromData(pvName, typeInfo, configService);
            }
        }
    }

    if (typeInfo == null) {
        logger.error("Unable to find typeinfo for pv " + pvName);
        resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (postProcessor == null) {
        if (useReduced) {
            String defaultPPClassName = configService.getInstallationProperties().getProperty(
                    "org.epics.archiverappliance.retrieval.DefaultUseReducedPostProcessor",
                    FirstSamplePP.class.getName());
            logger.debug("Using the default usereduced preprocessor " + defaultPPClassName);
            try {
                postProcessor = (PostProcessor) Class.forName(defaultPPClassName).newInstance();
            } catch (Exception ex) {
                logger.error("Exception constructing new instance of post processor " + defaultPPClassName, ex);
                postProcessor = null;
            }
        }
    }

    if (postProcessor == null) {
        logger.debug("Using the default raw preprocessor");
        postProcessor = new DefaultRawPostProcessor();
    }

    ApplianceInfo applianceForPV = configService.getApplianceForPV(pvName);
    if (applianceForPV == null) {
        // TypeInfo cannot be null here...
        assert (typeInfo != null);
        applianceForPV = configService.getAppliance(typeInfo.getApplianceIdentity());
    }

    if (!applianceForPV.equals(configService.getMyApplianceInfo())) {
        // Data for pv is elsewhere. Proxy/redirect and return.
        proxyRetrievalRequest(req, resp, pvName, useChunkedEncoding,
                applianceForPV.getRetrievalURL() + "/../data");
        return;
    }

    pmansProfiler.mark("After Appliance Info");

    String pvNameFromRequest = pvName;

    String fieldName = PVNames.getFieldName(pvName);
    if (fieldName != null && !fieldName.equals("") && !pvName.equals(typeInfo.getPvName())) {
        logger.debug("We reset the pvName " + pvName + " to one from the typeinfo " + typeInfo.getPvName()
                + " as that determines the name of the stream. Also using ExtraFieldsPostProcessor");
        pvName = typeInfo.getPvName();
        postProcessor = new ExtraFieldsPostProcessor(fieldName);
    }

    try {
        // Postprocessors get their mandatory arguments from the request.
        // If user does not pass in the expected request, throw an exception.
        postProcessor.initialize(postProcessorUserArg, pvName);
    } catch (Exception ex) {
        logger.error("Postprocessor threw an exception during initialization for " + pvName, ex);
        resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    try (BasicContext retrievalContext = new BasicContext(typeInfo.getDBRType(), pvNameFromRequest);
            MergeDedupConsumer mergeDedupCountingConsumer = createMergeDedupConsumer(resp, extension,
                    useChunkedEncoding);
            RetrievalExecutorResult executorResult = determineExecutorForPostProcessing(pvName, typeInfo,
                    requestTimes, req, postProcessor)) {
        HashMap<String, String> engineMetadata = null;
        if (fetchLatestMetadata) {
            // Make a call to the engine to fetch the latest metadata.
            engineMetadata = fetchLatestMedataFromEngine(pvName, applianceForPV);
        }

        LinkedList<Future<RetrievalResult>> retrievalResultFutures = resolveAllDataSources(pvName, typeInfo,
                postProcessor, applianceForPV, retrievalContext, executorResult, req, resp);
        pmansProfiler.mark("After data source resolution");

        long s1 = System.currentTimeMillis();
        String currentlyProcessingPV = null;

        List<Future<EventStream>> eventStreamFutures = getEventStreamFuturesFromRetrievalResults(executorResult,
                retrievalResultFutures);

        logger.debug(
                "Done with the RetrievalResult's; moving onto the individual event stream from each source for "
                        + pvName);
        pmansProfiler.mark("After retrieval results");

        for (Future<EventStream> future : eventStreamFutures) {
            EventStreamDesc sourceDesc = null;
            try (EventStream eventStream = future.get()) {
                sourceDesc = null; // Reset it for each loop iteration.
                sourceDesc = eventStream.getDescription();
                if (sourceDesc == null) {
                    logger.warn("Skipping event stream without a desc for pv " + pvName);
                    continue;
                }

                logger.debug("Processing event stream for pv " + pvName + " from source "
                        + ((eventStream.getDescription() != null) ? eventStream.getDescription().getSource()
                                : " unknown"));

                try {
                    mergeTypeInfo(typeInfo, sourceDesc, engineMetadata);
                } catch (MismatchedDBRTypeException mex) {
                    logger.error(mex.getMessage(), mex);
                    continue;
                }

                if (currentlyProcessingPV == null || !currentlyProcessingPV.equals(pvName)) {
                    logger.debug("Switching to new PV " + pvName
                            + " In some mime responses we insert special headers at the beginning of the response. Calling the hook for that");
                    currentlyProcessingPV = pvName;
                    mergeDedupCountingConsumer.processingPV(currentlyProcessingPV, start, end,
                            (eventStream != null) ? sourceDesc : null);
                }

                try {
                    // If the postProcessor does not have a consolidated event stream, we send each eventstream across as we encounter it.
                    // Else we send the consolidatedEventStream down below.
                    if (!(postProcessor instanceof PostProcessorWithConsolidatedEventStream)) {
                        mergeDedupCountingConsumer.consumeEventStream(eventStream);
                        resp.flushBuffer();
                    }
                } catch (Exception ex) {
                    if (ex != null && ex.toString() != null && ex.toString().contains("ClientAbortException")) {
                        // We check for ClientAbortException etc this way to avoid including tomcat jars in the build path.
                        logger.debug(
                                "Exception when consuming and flushing data from " + sourceDesc.getSource(),
                                ex);
                    } else {
                        logger.error("Exception when consuming and flushing data from " + sourceDesc.getSource()
                                + "-->" + ex.toString(), ex);
                    }
                }
                pmansProfiler.mark("After event stream " + eventStream.getDescription().getSource());
            } catch (Exception ex) {
                if (ex != null && ex.toString() != null && ex.toString().contains("ClientAbortException")) {
                    // We check for ClientAbortException etc this way to avoid including tomcat jars in the build path.
                    logger.debug("Exception when consuming and flushing data from "
                            + (sourceDesc != null ? sourceDesc.getSource() : "N/A"), ex);
                } else {
                    logger.error("Exception when consuming and flushing data from "
                            + (sourceDesc != null ? sourceDesc.getSource() : "N/A") + "-->" + ex.toString(),
                            ex);
                }
            }
        }

        if (postProcessor instanceof PostProcessorWithConsolidatedEventStream) {
            try (EventStream eventStream = ((PostProcessorWithConsolidatedEventStream) postProcessor)
                    .getConsolidatedEventStream()) {
                EventStreamDesc sourceDesc = eventStream.getDescription();
                if (sourceDesc == null) {
                    logger.error("Skipping event stream without a desc for pv " + pvName
                            + " and post processor " + postProcessor.getExtension());
                } else {
                    mergeDedupCountingConsumer.consumeEventStream(eventStream);
                    resp.flushBuffer();
                }
            }
        }

        // If the postProcessor needs to send final data across, give it a chance now...
        if (postProcessor instanceof AfterAllStreams) {
            EventStream finalEventStream = ((AfterAllStreams) postProcessor).anyFinalData();
            if (finalEventStream != null) {
                mergeDedupCountingConsumer.consumeEventStream(finalEventStream);
                resp.flushBuffer();
            }
        }

        pmansProfiler.mark("After writing all eventstreams to response");

        long s2 = System.currentTimeMillis();
        logger.info("For the complete request, found a total of "
                + mergeDedupCountingConsumer.totalEventsForAllPVs + " in " + (s2 - s1) + "(ms)" + " skipping "
                + mergeDedupCountingConsumer.skippedEventsForAllPVs + " events" + " deduping involved "
                + mergeDedupCountingConsumer.comparedEventsForAllPVs + " compares.");
    } catch (Exception ex) {
        if (ex != null && ex.toString() != null && ex.toString().contains("ClientAbortException")) {
            // We check for ClientAbortException etc this way to avoid including tomcat jars in the build path.
            logger.debug("Exception when retrieving data ", ex);
        } else {
            logger.error("Exception when retrieving data " + "-->" + ex.toString(), ex);
        }
    }
    pmansProfiler.mark("After all closes and flushing all buffers");

    // Till we determine all the if conditions where we log this, we log sparingly..
    if (pmansProfiler.totalTimeMS() > 5000) {
        logger.error("Retrieval time for " + pvName + " from " + startTimeStr + " to " + endTimeStr
                + pmansProfiler.toString());
    }
}

From source file:org.epics.archiverappliance.retrieval.DataRetrievalServlet.java

private void doGetMultiPV(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    PoorMansProfiler pmansProfiler = new PoorMansProfiler();

    // Gets the list of PVs specified by the `pv` parameter
    // String arrays might be inefficient for retrieval. In any case, they are sorted, which is essential later on.
    List<String> pvNames = Arrays.asList(req.getParameterValues("pv"));

    // Ensuring that the AA has finished starting up before requests are accepted.
    if (configService.getStartupState() != STARTUP_SEQUENCE.STARTUP_COMPLETE) {
        String msg = "Cannot process data retrieval requests for specified PVs ("
                + StringUtils.join(pvNames, ", ") + ") until the appliance has completely started up.";
        logger.error(msg);/*from ww w. j  a v  a2  s  .  co m*/
        resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, msg);
        return;
    }

    // Getting various fields from arguments
    String startTimeStr = req.getParameter("from");
    String endTimeStr = req.getParameter("to");
    boolean useReduced = false;
    String useReducedStr = req.getParameter("usereduced");
    if (useReducedStr != null && !useReducedStr.equals("")) {
        try {
            useReduced = Boolean.parseBoolean(useReducedStr);
        } catch (Exception ex) {
            logger.error("Exception parsing usereduced", ex);
            useReduced = false;
        }
    }

    // Getting MIME type
    String extension = req.getPathInfo().split("\\.")[1];
    logger.info("Mime is " + extension);

    if (!extension.equals("json") && !extension.equals("raw") && !extension.equals("jplot")
            && !extension.equals("qw")) {
        String msg = "Mime type " + extension + " is not supported. Please use \"json\", \"jplot\" or \"raw\".";
        resp.setHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }

    boolean useChunkedEncoding = true;
    String doNotChunkStr = req.getParameter("donotchunk");
    if (doNotChunkStr != null && !doNotChunkStr.equals("false")) {
        logger.info("Turning off HTTP chunked encoding");
        useChunkedEncoding = false;
    }

    boolean fetchLatestMetadata = false;
    String fetchLatestMetadataStr = req.getParameter("fetchLatestMetadata");
    if (fetchLatestMetadataStr != null && fetchLatestMetadataStr.equals("true")) {
        logger.info("Adding a call to the engine to fetch the latest metadata");
        fetchLatestMetadata = true;
    }

    // For data retrieval we need a PV info. However, in case of PV's that have long since retired, we may not want to have PVTypeInfo's in the system.
    // So, we support a template PV that lays out the data sources.
    // During retrieval, you can pass in the PV as a template and we'll clone this and make a temporary copy.
    String retiredPVTemplate = req.getParameter("retiredPVTemplate");

    // Goes through given PVs and returns bad request error.
    int nullPVs = 0;
    for (String pvName : pvNames) {
        if (pvName == null) {
            nullPVs++;
        }
        if (nullPVs > 0) {
            logger.warn("Some PVs are null in the request.");
            resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
    }

    if (pvNames.toString().matches("^.*" + ARCH_APPL_PING_PV + ".*$")) {
        logger.debug("Processing ping PV - this is used to validate the connection with the client.");
        processPingPV(req, resp);
        return;
    }

    for (String pvName : pvNames)
        if (pvName.endsWith(".VAL")) {
            int len = pvName.length();
            pvName = pvName.substring(0, len - 4);
            logger.info("Removing .VAL from pvName for request giving " + pvName);
        }

    // ISO datetimes are of the form "2011-02-02T08:00:00.000Z"
    Timestamp end = TimeUtils.plusHours(TimeUtils.now(), 1);
    if (endTimeStr != null) {
        try {
            end = TimeUtils.convertFromISO8601String(endTimeStr);
        } catch (IllegalArgumentException ex) {
            try {
                end = TimeUtils.convertFromDateTimeStringWithOffset(endTimeStr);
            } catch (IllegalArgumentException ex2) {
                String msg = "Cannot parse time " + endTimeStr;
                logger.warn(msg, ex2);
                resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
                return;
            }
        }
    }

    // We get one day by default
    Timestamp start = TimeUtils.minusDays(end, 1);
    if (startTimeStr != null) {
        try {
            start = TimeUtils.convertFromISO8601String(startTimeStr);
        } catch (IllegalArgumentException ex) {
            try {
                start = TimeUtils.convertFromDateTimeStringWithOffset(startTimeStr);
            } catch (IllegalArgumentException ex2) {
                String msg = "Cannot parse time " + startTimeStr;
                logger.warn(msg, ex2);
                resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
                return;
            }
        }
    }

    if (end.before(start)) {
        String msg = "For request, end " + end.toString() + " is before start " + start.toString() + " for pvs "
                + StringUtils.join(pvNames, ", ");
        logger.error(msg);
        resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }

    LinkedList<TimeSpan> requestTimes = new LinkedList<TimeSpan>();

    // We can specify a list of time stamp pairs using the optional timeranges parameter
    String timeRangesStr = req.getParameter("timeranges");
    if (timeRangesStr != null) {
        boolean continueWithRequest = parseTimeRanges(resp, "[" + StringUtils.join(pvNames, ", ") + "]",
                requestTimes, timeRangesStr);
        if (!continueWithRequest) {
            // Cannot parse the time ranges properly; we so abort the request.
            String msg = "The specified time ranges could not be processed appropriately. Aborting.";
            logger.info(msg);
            resp.setHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
            return;
        }

        // Override the start and the end so that the mergededup consumer works correctly.
        start = requestTimes.getFirst().getStartTime();
        end = requestTimes.getLast().getEndTime();

    } else {
        requestTimes.add(new TimeSpan(start, end));
    }

    assert (requestTimes.size() > 0);

    // Get a post processor for each PV specified in pvNames
    // If PV in the form <pp>(<pv>), process it
    String postProcessorUserArg = req.getParameter("pp");
    List<String> postProcessorUserArgs = new ArrayList<>(pvNames.size());
    List<PostProcessor> postProcessors = new ArrayList<>(pvNames.size());
    for (int i = 0; i < pvNames.size(); i++) {
        postProcessorUserArgs.add(postProcessorUserArg);

        if (pvNames.get(i).contains("(")) {
            if (!pvNames.get(i).contains(")")) {
                String msg = "Unbalanced paren " + pvNames.get(i);
                logger.error(msg);
                resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
                return;
            }
            String[] components = pvNames.get(i).split("[(,)]");
            postProcessorUserArg = components[0];
            postProcessorUserArgs.set(i, postProcessorUserArg);
            pvNames.set(i, components[1]);
            if (components.length > 2) {
                for (int j = 2; j < components.length; j++) {
                    postProcessorUserArgs.set(i, postProcessorUserArgs.get(i) + "_" + components[j]);
                }
            }
            logger.info("After parsing the function call syntax pvName is " + pvNames.get(i)
                    + " and postProcessorUserArg is " + postProcessorUserArg);
        }
        postProcessors.add(PostProcessors.findPostProcessor(postProcessorUserArg));
    }

    List<PVTypeInfo> typeInfos = new ArrayList<PVTypeInfo>(pvNames.size());
    for (int i = 0; i < pvNames.size(); i++) {
        typeInfos.add(PVNames.determineAppropriatePVTypeInfo(pvNames.get(i), configService));
    }
    pmansProfiler.mark("After PVTypeInfo");

    for (int i = 0; i < pvNames.size(); i++)
        if (typeInfos.get(i) == null && RetrievalState.includeExternalServers(req)) {
            logger.debug(
                    "Checking to see if pv " + pvNames.get(i) + " is served by a external Archiver Server");
            typeInfos.set(i,
                    checkIfPVisServedByExternalServer(pvNames.get(i), start, req, resp, useChunkedEncoding));
        }

    for (int i = 0; i < pvNames.size(); i++) {
        if (typeInfos.get(i) == null) {
            // TODO Only needed if we're forwarding the request to another server.
            if (resp.isCommitted()) {
                logger.debug("Proxied the data thru an external server for PV " + pvNames.get(i));
                return;
            }

            if (retiredPVTemplate != null) {
                PVTypeInfo templateTypeInfo = PVNames.determineAppropriatePVTypeInfo(retiredPVTemplate,
                        configService);
                if (templateTypeInfo != null) {
                    typeInfos.set(i, new PVTypeInfo(pvNames.get(i), templateTypeInfo));
                    typeInfos.get(i).setPaused(true);
                    typeInfos.get(i).setApplianceIdentity(configService.getMyApplianceInfo().getIdentity());
                    // Somehow tell the code downstream that this is a fake typeInfos.
                    typeInfos.get(i).setSamplingMethod(SamplingMethod.DONT_ARCHIVE);
                    logger.debug("Using a template PV for " + pvNames.get(i)
                            + " Need to determine the actual DBR type.");
                    setActualDBRTypeFromData(pvNames.get(i), typeInfos.get(i), configService);
                }
            }
        }

        if (typeInfos.get(i) == null) {
            String msg = "Unable to find typeinfo for pv " + pvNames.get(i);
            logger.error(msg);
            resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
            return;
        }

        if (postProcessors.get(i) == null) {
            if (useReduced) {
                String defaultPPClassName = configService.getInstallationProperties().getProperty(
                        "org.epics.archiverappliance.retrieval.DefaultUseReducedPostProcessor",
                        FirstSamplePP.class.getName());
                logger.debug("Using the default usereduced preprocessor " + defaultPPClassName);
                try {
                    postProcessors.set(i, (PostProcessor) Class.forName(defaultPPClassName).newInstance());
                } catch (Exception ex) {
                    logger.error("Exception constructing new instance of post processor " + defaultPPClassName,
                            ex);
                    postProcessors.set(i, null);
                }
            }
        }

        if (postProcessors.get(i) == null) {
            logger.debug("Using the default raw preprocessor");
            postProcessors.set(i, new DefaultRawPostProcessor());
        }
    }

    // Get the appliances for each of the PVs
    List<ApplianceInfo> applianceForPVs = new ArrayList<ApplianceInfo>(pvNames.size());
    for (int i = 0; i < pvNames.size(); i++) {
        applianceForPVs.add(configService.getApplianceForPV(pvNames.get(i)));
        if (applianceForPVs.get(i) == null) {
            // TypeInfo cannot be null here...
            assert (typeInfos.get(i) != null);
            applianceForPVs.set(i, configService.getAppliance(typeInfos.get(i).getApplianceIdentity()));
        }
    }

    /*
     * Retrieving the external appliances if the current appliance has not got the PV assigned to it, and
     * storing the associated information of the PVs in that appliance.
     */
    Map<String, ArrayList<PVInfoForClusterRetrieval>> applianceToPVs = new HashMap<String, ArrayList<PVInfoForClusterRetrieval>>();
    for (int i = 0; i < pvNames.size(); i++) {
        if (!applianceForPVs.get(i).equals(configService.getMyApplianceInfo())) {

            ArrayList<PVInfoForClusterRetrieval> appliancePVs = applianceToPVs
                    .get(applianceForPVs.get(i).getMgmtURL());
            appliancePVs = (appliancePVs == null) ? new ArrayList<>() : appliancePVs;
            PVInfoForClusterRetrieval pvInfoForRetrieval = new PVInfoForClusterRetrieval(pvNames.get(i),
                    typeInfos.get(i), postProcessors.get(i), applianceForPVs.get(i));
            appliancePVs.add(pvInfoForRetrieval);
            applianceToPVs.put(applianceForPVs.get(i).getRetrievalURL(), appliancePVs);
        }
    }

    List<List<Future<EventStream>>> listOfEventStreamFuturesLists = new ArrayList<List<Future<EventStream>>>();
    Set<String> retrievalURLs = applianceToPVs.keySet();
    if (retrievalURLs.size() > 0) {
        // Get list of PVs and redirect them to appropriate appliance to be retrieved.
        String retrievalURL;
        ArrayList<PVInfoForClusterRetrieval> pvInfos;
        while (!((retrievalURL = retrievalURLs.iterator().next()) != null)) {
            // Get array list of PVs for appliance
            pvInfos = applianceToPVs.get(retrievalURL);
            try {
                List<List<Future<EventStream>>> resultFromForeignAppliances = retrieveEventStreamFromForeignAppliance(
                        req, resp, pvInfos, requestTimes, useChunkedEncoding,
                        retrievalURL + "/../data/getDataForPVs.raw", start, end);
                listOfEventStreamFuturesLists.addAll(resultFromForeignAppliances);
            } catch (Exception ex) {
                logger.error("Failed to retrieve " + StringUtils.join(pvNames, ", ") + " from " + retrievalURL
                        + ".");
                return;
            }
        }
    }

    pmansProfiler.mark("After Appliance Info");

    // Setting post processor for PVs, taking into account whether there is a field in the PV name
    List<String> pvNamesFromRequests = new ArrayList<String>(pvNames.size());
    for (int i = 0; i < pvNames.size(); i++) {
        String pvName = pvNames.get(i);
        pvNamesFromRequests.add(pvName);
        PVTypeInfo typeInfo = typeInfos.get(i);
        postProcessorUserArg = postProcessorUserArgs.get(i);

        // If a field is specified in a PV name, it will create a post processor for that
        String fieldName = PVNames.getFieldName(pvName);
        if (fieldName != null && !fieldName.equals("") && !pvName.equals(typeInfo.getPvName())) {
            logger.debug("We reset the pvName " + pvName + " to one from the typeinfo " + typeInfo.getPvName()
                    + " as that determines the name of the stream. " + "Also using ExtraFieldsPostProcessor.");
            pvNames.set(i, typeInfo.getPvName());
            postProcessors.set(i, new ExtraFieldsPostProcessor(fieldName));
        }

        try {
            // Postprocessors get their mandatory arguments from the request.
            // If user does not pass in the expected request, throw an exception.
            postProcessors.get(i).initialize(postProcessorUserArg, pvName);
        } catch (Exception ex) {
            String msg = "Postprocessor threw an exception during initialization for " + pvName;
            logger.error(msg, ex);
            resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
            return;
        }
    }

    /*
     * MergeDedupConsumer is what writes PB data in its respective format to the HTML response.
     * The response, after the MergeDedupConsumer is created, contains the following:
     * 
     * 1) The content type for the response.
     * 2) Any additional headers for the particular MIME response.
     * 
     * Additionally, the MergeDedupConsumer instance holds a reference to the output stream
     * that is used to write to the HTML response. It is stored under the name `os`.
     */
    MergeDedupConsumer mergeDedupCountingConsumer;
    try {
        mergeDedupCountingConsumer = createMergeDedupConsumer(resp, extension, useChunkedEncoding);
    } catch (ServletException se) {
        String msg = "Exception when retrieving data " + "-->" + se.toString();
        logger.error(msg, se);
        resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, msg);
        return;
    }

    /* 
     * BasicContext contains the PV name and the expected return type. Used to access PB files.
     * RetrievalExecutorResult contains a thread service class and the time spans Presumably, the 
     * thread service is what retrieves the data, and the BasicContext is the context in which it 
     * works.
     */
    List<HashMap<String, String>> engineMetadatas = new ArrayList<HashMap<String, String>>();
    try {
        List<BasicContext> retrievalContexts = new ArrayList<BasicContext>(pvNames.size());
        List<RetrievalExecutorResult> executorResults = new ArrayList<RetrievalExecutorResult>(pvNames.size());
        for (int i = 0; i < pvNames.size(); i++) {
            if (fetchLatestMetadata) {
                // Make a call to the engine to fetch the latest metadata.
                engineMetadatas.add(fetchLatestMedataFromEngine(pvNames.get(i), applianceForPVs.get(i)));
            }
            retrievalContexts.add(new BasicContext(typeInfos.get(i).getDBRType(), pvNamesFromRequests.get(i)));
            executorResults.add(determineExecutorForPostProcessing(pvNames.get(i), typeInfos.get(i),
                    requestTimes, req, postProcessors.get(i)));
        }

        /*
         * There are as many Future objects in the eventStreamFutures List as there are periods over 
         * which to fetch data. Retrieval of data happen here in parallel.
         */
        List<LinkedList<Future<RetrievalResult>>> listOfRetrievalResultFuturesLists = new ArrayList<LinkedList<Future<RetrievalResult>>>();
        for (int i = 0; i < pvNames.size(); i++) {
            listOfRetrievalResultFuturesLists.add(resolveAllDataSources(pvNames.get(i), typeInfos.get(i),
                    postProcessors.get(i), applianceForPVs.get(i), retrievalContexts.get(i),
                    executorResults.get(i), req, resp));
        }
        pmansProfiler.mark("After data source resolution");

        for (int i = 0; i < pvNames.size(); i++) {
            // Data is retrieved here
            List<Future<EventStream>> eventStreamFutures = getEventStreamFuturesFromRetrievalResults(
                    executorResults.get(i), listOfRetrievalResultFuturesLists.get(i));
            listOfEventStreamFuturesLists.add(eventStreamFutures);
        }

    } catch (Exception ex) {
        if (ex != null && ex.toString() != null && ex.toString().contains("ClientAbortException")) {
            // We check for ClientAbortException etc this way to avoid including tomcat jars in the build path.
            logger.debug("Exception when retrieving data ", ex);
        } else {
            logger.error("Exception when retrieving data " + "-->" + ex.toString(), ex);
        }
    }

    long s1 = System.currentTimeMillis();
    String currentlyProcessingPV = null;

    /*
     * The following try bracket goes through each of the streams in the list of event stream futures.
     * 
     * It is intended that the process goes through one PV at a time.
     */
    try {
        for (int i = 0; i < pvNames.size(); i++) {
            List<Future<EventStream>> eventStreamFutures = listOfEventStreamFuturesLists.get(i);
            String pvName = pvNames.get(i);
            PVTypeInfo typeInfo = typeInfos.get(i);
            HashMap<String, String> engineMetadata = fetchLatestMetadata ? engineMetadatas.get(i) : null;
            PostProcessor postProcessor = postProcessors.get(i);

            logger.debug("Done with the RetrievalResults; moving onto the individual event stream "
                    + "from each source for " + StringUtils.join(pvNames, ", "));
            pmansProfiler.mark("After retrieval results");
            for (Future<EventStream> future : eventStreamFutures) {
                EventStreamDesc sourceDesc = null;

                // Gets the result of a data retrieval
                try (EventStream eventStream = future.get()) {
                    sourceDesc = null; // Reset it for each loop iteration.
                    sourceDesc = eventStream.getDescription();
                    if (sourceDesc == null) {
                        logger.warn("Skipping event stream without a desc for pv " + pvName);
                        continue;
                    }

                    logger.debug("Processing event stream for pv " + pvName + " from source "
                            + ((eventStream.getDescription() != null) ? eventStream.getDescription().getSource()
                                    : " unknown"));

                    try {
                        mergeTypeInfo(typeInfo, sourceDesc, engineMetadata);
                    } catch (MismatchedDBRTypeException mex) {
                        logger.error(mex.getMessage(), mex);
                        continue;
                    }

                    if (currentlyProcessingPV == null || !currentlyProcessingPV.equals(pvName)) {
                        logger.debug("Switching to new PV " + pvName + " In some mime responses we insert "
                                + "special headers at the beginning of the response. Calling the hook for "
                                + "that");
                        currentlyProcessingPV = pvName;
                        /*
                         * Goes through the PB data stream over a period of time. The relevant MIME response
                         * actually deal with the processing of the PV. `start` and `end` refer to the very
                         * beginning and very end of the time period being retrieved over, regardless of
                         * whether it is divided up or not.
                         */
                        mergeDedupCountingConsumer.processingPV(currentlyProcessingPV, start, end,
                                (eventStream != null) ? sourceDesc : null);
                    }

                    try {
                        // If the postProcessor does not have a consolidated event stream, we send each eventstream across as we encounter it.
                        // Else we send the consolidatedEventStream down below.
                        if (!(postProcessor instanceof PostProcessorWithConsolidatedEventStream)) {
                            /*
                             * The eventStream object contains all the data over the current period.
                             */
                            mergeDedupCountingConsumer.consumeEventStream(eventStream);
                            resp.flushBuffer();
                        }
                    } catch (Exception ex) {
                        if (ex != null && ex.toString() != null
                                && ex.toString().contains("ClientAbortException")) {
                            // We check for ClientAbortException etc this way to avoid including tomcat jars in the build path.
                            logger.debug(
                                    "Exception when consuming and flushing data from " + sourceDesc.getSource(),
                                    ex);
                        } else {
                            logger.error("Exception when consuming and flushing data from "
                                    + sourceDesc.getSource() + "-->" + ex.toString(), ex);
                        }
                    }
                    pmansProfiler.mark("After event stream " + eventStream.getDescription().getSource());
                } catch (Exception ex) {
                    if (ex != null && ex.toString() != null && ex.toString().contains("ClientAbortException")) {
                        // We check for ClientAbortException etc this way to avoid including tomcat jars in the build path.
                        logger.debug("Exception when consuming and flushing data from "
                                + (sourceDesc != null ? sourceDesc.getSource() : "N/A"), ex);
                    } else {
                        logger.error("Exception when consuming and flushing data from "
                                + (sourceDesc != null ? sourceDesc.getSource() : "N/A") + "-->" + ex.toString(),
                                ex);
                    }
                }
            }

            // TODO Go through data from other appliances here

            if (postProcessor instanceof PostProcessorWithConsolidatedEventStream) {
                try (EventStream eventStream = ((PostProcessorWithConsolidatedEventStream) postProcessor)
                        .getConsolidatedEventStream()) {
                    EventStreamDesc sourceDesc = eventStream.getDescription();
                    if (sourceDesc == null) {
                        logger.error("Skipping event stream without a desc for pv " + pvName
                                + " and post processor " + postProcessor.getExtension());
                    } else {
                        mergeDedupCountingConsumer.consumeEventStream(eventStream);
                        resp.flushBuffer();
                    }
                }
            }

            // If the postProcessor needs to send final data across, give it a chance now...
            if (postProcessor instanceof AfterAllStreams) {
                EventStream finalEventStream = ((AfterAllStreams) postProcessor).anyFinalData();
                if (finalEventStream != null) {
                    mergeDedupCountingConsumer.consumeEventStream(finalEventStream);
                    resp.flushBuffer();
                }
            }

            pmansProfiler.mark("After writing all eventstreams to response");
        }
    } catch (Exception ex) {
        if (ex != null && ex.toString() != null && ex.toString().contains("ClientAbortException")) {
            // We check for ClientAbortException etc this way to avoid including tomcat jars in the build path.
            logger.debug("Exception when retrieving data ", ex);
        } else {
            logger.error("Exception when retrieving data " + "-->" + ex.toString(), ex);
        }
    }

    long s2 = System.currentTimeMillis();
    logger.info("For the complete request, found a total of " + mergeDedupCountingConsumer.totalEventsForAllPVs
            + " in " + (s2 - s1) + "(ms)" + " skipping " + mergeDedupCountingConsumer.skippedEventsForAllPVs
            + " events" + " deduping involved " + mergeDedupCountingConsumer.comparedEventsForAllPVs
            + " compares.");

    pmansProfiler.mark("After all closes and flushing all buffers");

    // Till we determine all the if conditions where we log this, we log sparingly..
    if (pmansProfiler.totalTimeMS() > 5000) {
        logger.error("Retrieval time for " + StringUtils.join(pvNames, ", ") + " from " + startTimeStr + " to "
                + endTimeStr + ": " + pmansProfiler.toString());
    }

    mergeDedupCountingConsumer.close();
}

From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java

public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from w  ww  .j  a v  a 2s .  co  m
        printRequest(request);

        sessionId.set(request.getSession().getId());
        String dataSource = request.getParameter("_dataSource");

        // List grid export
        if ("export".equals(request.getParameter("_operationType"))) {
            exportData(dataSource, response);
            return;
        }

        response.setContentType("text/plain;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "-1");

        if ("getMenu".equals(dataSource)) {
            response.getWriter().write(listServices());
        } else if ("userInfo".equals(dataSource)) {
            ServiceContext ctx = ServiceContextStore.get();
            PrintWriter out = response.getWriter();
            out.print(ctx.getUserId());
            for (String role : ctx.getRoles()) {
                out.print(",");
                out.print(role);
            }
            out.flush();
        } else if ("createDataSource".equals(dataSource)) {
            HashMap<String, String> classToServiceName = new HashMap<String, String>();
            for (ServiceDescription serviceDesc : getServiceDescription()) {
                log.log(Level.INFO, "Service translation from {0} to {1}",
                        new Object[] { serviceDesc.getExpectedClass().getName(), serviceDesc.getName() });
                classToServiceName.put(serviceDesc.getExpectedClass().getName(), serviceDesc.getName());
            }
            GuiDataSourceService dataSourceService = getGuiDataSourceService();
            dataSourceService.setServiceMapping(ServiceContextStore.get(), classToServiceName);

            StringBuilder output = new StringBuilder();
            output.append("dataSources###");
            List<GuiDataSource> allDataSources = dataSourceService.findAll(ServiceContextStore.get());
            for (GuiDataSource dataSourceDef : allDataSources) {
                ds2Ref.put(dataSourceDef.getBaseClass(), dataSourceDef.getTitleField());
                dataSourceDef.setBaseClass(null);
                log.log(Level.INFO, "Entity def for {0}", dataSourceDef.getXxxID());
                dataSourceDef.setDataURL(getServiceUrl(request));

                output.append("$wnd.isc.RestDataSource.create(")
                        .append(mapObjToOutput(dataSourceDef, 6, new Stack<Object>(), true, false))
                        .append(");\n");
            }

            ListSettingsService listInstance = (ListSettingsService) findService(LIST_SETTINGS_SERVICE)
                    .getInstance();
            List<ListSettings> guiList = listInstance.findUserSettings(ServiceContextStore.get());
            for (ListSettings listSettings : guiList) {
                output.append("\n###").append(listSettings.getListID()).append("###")
                        .append(listSettings.getSettings());
            }

            log.log(Level.INFO, "Create datasource {0}", output.toString());
            response.getWriter().append(output);

        } else if (findService(dataSource) != null) {
            ServiceDescription serviceDesc = findService(dataSource);
            String operationType = request.getParameter("_operationType");
            String methodName = request.getParameter("_operationId");

            if (methodName != null && !methodName.endsWith("_fetch")) {
                log.log(Level.FINER, "Executing method '" + dataSource + "." + methodName + "'");
                MethodDescription methodDescription = serviceDesc.getOtherMethods().get(methodName);
                if (methodDescription != null) {
                    Object valObj = null;
                    HashMap<String, Object> jsData = unifyRequest(request);
                    Object[] params = prepareMethodParam(jsData, true, methodDescription.parameterNames,
                            methodDescription.method.getParameterTypes());
                    // Resolve "ids" for iterations
                    int iterate = -1;
                    if (jsData.get("ids") != null) {
                        Class<?>[] paramTypes = methodDescription.method.getParameterTypes();
                        for (int i = 0; i < paramTypes.length; i++) {
                            if (Long.class.equals(paramTypes[i]) || paramTypes[i].equals(Long.TYPE)
                                    && methodDescription.parameterNames[i].equals("id") && params[i] == null) {
                                iterate = i;
                                break;
                            } else if (Collection.class.isAssignableFrom(paramTypes[i])
                                    && methodDescription.parameterNames[i].equals("ids") && params[i] == null) {
                                List<Long> longList = new ArrayList<Long>();
                                String ids = (String) jsData.get("ids");
                                String[] idSplit = ids.split(",");
                                for (int k = 0; k < idSplit.length; k++) {
                                    if (idSplit[i].length() > 0) {
                                        longList.add(Long.parseLong(idSplit[i]));
                                    }
                                }
                                params[i] = longList;
                                break;
                            }
                        }
                    }

                    if (iterate != -1) {
                        if (log.isLoggable(Level.FINER)) {
                            for (int j = 0; j < params.length; j++) {
                                log.log(Level.FINER, "     Parameter[{0}]={1}", new Object[] { j, params[j] });
                            }
                        }
                        String ids = (String) jsData.get("ids");
                        String[] idSplit = ids.split(",");
                        ArrayList<Object> listResult = new ArrayList<Object>();
                        valObj = listResult;
                        for (int i = 0; i < idSplit.length; i++) {
                            if (idSplit[i].length() > 0) {
                                params[iterate] = Long.parseLong(idSplit[i]);
                                Object subValObj = methodDescription.method.invoke(serviceDesc.getInstance(),
                                        params);
                                if (subValObj != null && subValObj instanceof Collection) {
                                    listResult.addAll((Collection) subValObj);
                                } else if (subValObj != null) {
                                    listResult.add(subValObj);
                                }
                            }
                        }
                        log.info("Return value: " + valObj);
                    } else if (params != null) {
                        if (log.isLoggable(Level.FINER)) {
                            for (int j = 0; j < params.length; j++) {
                                log.log(Level.FINER, "     Parameter[{0}]={1}", new Object[] { j, params[j] });
                            }
                        }
                        valObj = methodDescription.method.invoke(serviceDesc.getInstance(), params);
                        log.info("Return value: " + valObj);
                    }
                    Collection<Object> collResult;
                    PagedResult<?> pagedResult = null;
                    if (valObj == null) {
                        collResult = new ArrayList<Object>();
                        for (int i = 0; i < params.length; i++) {
                            if (params[i] != null
                                    && params[i].getClass().equals(serviceDesc.getExpectedClass())) {
                                collResult.add(params[i]);
                                break;
                            }
                        }
                    } else if (valObj instanceof Collection) {
                        collResult = (Collection) valObj;
                    } else if (valObj instanceof PagedResult) {
                        collResult = null;
                        pagedResult = (PagedResult) valObj;
                    } else {
                        ArrayList<Object> serviceResultArray = new ArrayList<Object>();
                        serviceResultArray.add(valObj);
                        collResult = serviceResultArray;
                    }
                    if (collResult != null) {
                        sendResponse(response.getWriter(), 0, collResult.size(), collResult);
                    } else if (pagedResult != null) {
                        sendResponse(response.getWriter(), pagedResult);
                    }
                } else {
                    throw new IllegalArgumentException(
                            "No " + methodName + " operation available on " + dataSource);
                }
            } else if (operationType == null) {
                throw makeApplicationException("Unsupported operation", "ERR9001", "NULL");
            } else if (operationType.equals("fetch") && request.getParameter("id") != null) {
                Long idVal = Long.parseLong(request.getParameter("id"));
                if (serviceDesc.getFindById() != null) {
                    Object serviceResult = serviceDesc.getFindById().invoke(serviceDesc.getInstance(),
                            ServiceContextStore.get(), idVal);
                    ArrayList<Object> serviceResultArray = new ArrayList<Object>();
                    serviceResultArray.add(serviceResult);

                    sendResponse(response.getWriter(), 0, 1, serviceResultArray);
                } else {
                    throw new IllegalArgumentException("No fetch operation available");
                }
            } else if (operationType.equals("fetch")) {
                List<?> serviceResult;
                PagedResult<?> pagedServiceResult = null;

                String sRow = request.getParameter("_startRow");
                int startRow = sRow == null ? 0 : Integer.parseInt(sRow);
                String eRow = request.getParameter("_endRow");
                int endRow = eRow == null ? 0 : Integer.parseInt(eRow);

                ArrayList<String> queryParams = new ArrayList();
                Enumeration pNames = request.getParameterNames();
                while (pNames.hasMoreElements()) {
                    String paramName = (String) pNames.nextElement();
                    if (!paramName.startsWith("_")) {
                        queryParams.add(paramName);
                    } else if ("_sortBy".equals(paramName)) {
                        queryParams.add("sortBy");
                    }
                }

                if (queryParams.size() > 0) {
                    Collection<MethodDescription> methods = serviceDesc.getOtherMethods().values();
                    MethodDescription matchedMethod = null;
                    int matchLength = 1000;
                    for (MethodDescription method : methods) {
                        String[] methodParamNames = method.parameterNames;
                        if (methodParamNames != null && methodParamNames.length >= queryParams.size()
                                && (List.class.isAssignableFrom(method.method.getReturnType())
                                        || PagedResult.class.isAssignableFrom(method.method.getReturnType()))) {
                            boolean matchParam = false;
                            for (String queryParam : queryParams) {
                                matchParam = false;
                                for (String methodParamName : methodParamNames) {
                                    if (queryParam.equals(methodParamName)) {
                                        matchParam = true;
                                        break;
                                    }
                                }
                                if (!matchParam) {
                                    break;
                                }
                            }
                            if (matchParam && method.parameterNames.length < matchLength) {
                                matchedMethod = method;
                                matchLength = method.parameterNames.length;
                            }
                        }
                    }

                    Object[] params = null;
                    if (matchedMethod != null) {
                        HashMap<String, Object> jsData = unifyRequest(request);
                        params = prepareMethodParam(jsData, true, matchedMethod.parameterNames,
                                matchedMethod.method.getParameterTypes());
                    } else {
                        List<ConditionalCriteria> conditions = new ArrayList();
                        for (MethodDescription method : methods) {
                            if (method.getMethodName().equals("findByCondition")) {
                                Class<?>[] parameterTypes = method.method.getParameterTypes();
                                if (List.class.isAssignableFrom(parameterTypes[0])) {
                                    params = new Object[] { conditions };
                                    matchedMethod = method;
                                    break;
                                } else if (parameterTypes.length == 3
                                        && ServiceContext.class.isAssignableFrom(parameterTypes[0])
                                        && List.class.isAssignableFrom(parameterTypes[1])
                                        && PagingParameter.class.isAssignableFrom(parameterTypes[2])) {
                                    endRow = endRow < startRow + LOOK_AHEAD ? startRow + LOOK_AHEAD : endRow;
                                    PagingParameter pagingParam = PagingParameter.rowAccess(startRow, endRow,
                                            LOOK_AHEAD);
                                    params = new Object[] { ServiceContextStore.get(), conditions,
                                            pagingParam };
                                    matchedMethod = method;
                                    break;
                                } else if (parameterTypes.length == 2
                                        && ServiceContext.class.isAssignableFrom(parameterTypes[0])
                                        && List.class.isAssignableFrom(parameterTypes[1])) {
                                    params = new Object[] { ServiceContextStore.get(), conditions };
                                    matchedMethod = method;
                                    break;
                                }
                            }
                        }
                        if (matchedMethod != null) {
                            for (String queryParam : queryParams) {
                                LeafProperty<?> queryProp = new LeafProperty(queryParam, ScServlet.class);
                                String matchStyle = request.getParameter("_textMatchStyle");
                                String queryValue = request.getParameter(queryParam);
                                if (queryParam.equals("sortBy")) {
                                    queryValue = normalizeAssoc(serviceDesc, request.getParameter("_sortBy"));
                                    if (queryValue.startsWith("+")) {
                                        LeafProperty<?> sortProp = new LeafProperty(queryValue.substring(1),
                                                ScServlet.class);
                                        conditions.add(ConditionalCriteria.orderAsc(sortProp));
                                    } else if (queryValue.startsWith("-")) {
                                        LeafProperty<?> sortProp = new LeafProperty(queryValue.substring(1),
                                                ScServlet.class);
                                        conditions.add(ConditionalCriteria.orderDesc(sortProp));
                                    } else {
                                        LeafProperty<?> sortProp = new LeafProperty(queryValue,
                                                ScServlet.class);
                                        conditions.add(ConditionalCriteria.orderAsc(sortProp));
                                    }
                                } else if (queryValue.indexOf('%') != -1) {
                                    conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp,
                                            request.getParameter(queryParam) + "%"));
                                } else {
                                    String[] queryParamSplit = queryParam.split("\\.");
                                    Class watchClass = serviceDesc.getExpectedClass();
                                    Object otherEqVal = null;
                                    boolean isString = false;
                                    for (String queryParamPart : queryParamSplit) {
                                        try {
                                            Method method = watchClass.getMethod(
                                                    makeGetMethodName(queryParamPart), (Class[]) null);
                                            watchClass = method.getReturnType();
                                            if (Collection.class.isAssignableFrom(watchClass)) {
                                                // TODO look deeper into class of collection
                                                break;
                                            } else if (Enum.class.isAssignableFrom(watchClass)) {
                                                otherEqVal = Enum.valueOf(watchClass, queryValue);
                                                break;
                                            } else if (String.class.equals(watchClass)) {
                                                isString = true;
                                                break;
                                            } else if (Long.class.equals(watchClass)) {
                                                isString = true;
                                                otherEqVal = Long.parseLong(queryValue);
                                                break;
                                            } else if (Integer.class.equals(watchClass)) {
                                                isString = true;
                                                otherEqVal = Integer.parseInt(queryValue);
                                                break;
                                            } else if (Double.class.equals(watchClass)) {
                                                isString = true;
                                                otherEqVal = Double.parseDouble(queryValue);
                                                break;
                                            } else if (Date.class.equals(watchClass)) {
                                                otherEqVal = dateFormat.parse(queryValue);
                                                break;
                                            } else if (findServiceByClassName(watchClass.getName()) != null
                                                    && "null".equals(queryValue)) {
                                                otherEqVal = "null";
                                                break;
                                            } else if (findServiceByClassName(watchClass.getName()) != null
                                                    && findServiceByClassName(watchClass.getName())
                                                            .getFindById() != null) {
                                                ServiceDescription srvc = findServiceByClassName(
                                                        watchClass.getName());
                                                otherEqVal = srvc.getFindById().invoke(srvc.getInstance(),
                                                        ServiceContextStore.get(), Long.parseLong(queryValue));
                                            }
                                        } catch (NoSuchMethodException nsme) {
                                            // Ignore error, isString will stay false
                                            break;
                                        }
                                    }
                                    boolean isLike = "substring".equals(matchStyle)
                                            || "startsWith".equals(matchStyle);
                                    if ("null".equals(otherEqVal)) {
                                        conditions.add(ConditionalCriteria.isNull(queryProp));
                                    } else if (otherEqVal instanceof Date) {
                                        DateMidnight start = (new DateTime(otherEqVal)).toDateMidnight();
                                        DateMidnight stop = start.plusDays(1);
                                        conditions.add(ConditionalCriteria.between(queryProp, start.toDate(),
                                                stop.toDate()));
                                    } else if (isString && otherEqVal != null && isLike) {
                                        conditions.add(ConditionalCriteria.like(queryProp, otherEqVal));
                                    } else if (isString && "substring".equals(matchStyle)) {
                                        conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp,
                                                "%" + request.getParameter(queryParam) + "%"));
                                    } else if (isString && "startsWith".equals(matchStyle)) {
                                        conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp,
                                                request.getParameter(queryParam) + "%"));
                                    } else if (otherEqVal != null) {
                                        conditions.add(ConditionalCriteria.equal(queryProp, otherEqVal));
                                    } else {
                                        conditions.add(ConditionalCriteria.equal(queryProp, queryValue));
                                    }
                                }
                            }
                        }
                    }

                    if (matchedMethod != null && params != null) {
                        for (int j = 0; j < params.length; j++) {
                            log.log(Level.FINER, "     Parameter[{0}]={1}", new Object[] { j, params[j] });
                        }
                        if (matchedMethod.method.getReturnType().equals(PagedResult.class)) {
                            serviceResult = null;
                            pagedServiceResult = (PagedResult) matchedMethod.method
                                    .invoke(serviceDesc.getInstance(), params);
                        } else {
                            serviceResult = (List<?>) matchedMethod.method.invoke(serviceDesc.getInstance(),
                                    params);
                        }
                    } else {
                        throw makeApplicationException("You can''t filter with such condition.", "ERR9015",
                                (Serializable[]) null);
                    }
                } else if (queryParams.size() == 0 && serviceDesc.getFindAll() != null) {
                    Class<?>[] paramTypes = serviceDesc.getFindAll().getParameterTypes();
                    if (paramTypes.length == 2 && paramTypes[0].equals(ServiceContext.class)
                            && paramTypes[1].equals(PagingParameter.class)
                            && serviceDesc.getFindAll().getReturnType().equals(PagedResult.class)) {
                        endRow = endRow < startRow + LOOK_AHEAD ? startRow + LOOK_AHEAD : endRow;
                        PagingParameter pagingParam = PagingParameter.rowAccess(startRow, endRow, LOOK_AHEAD);
                        pagedServiceResult = (PagedResult<?>) serviceDesc.getFindAll()
                                .invoke(serviceDesc.getInstance(), ServiceContextStore.get(), pagingParam);
                        serviceResult = null;
                    } else if (paramTypes.length == 1 && paramTypes[0].equals(ServiceContext.class)) {
                        serviceResult = (List<? extends Object>) serviceDesc.getFindAll()
                                .invoke(serviceDesc.getInstance(), ServiceContextStore.get());
                    } else {
                        serviceResult = null;
                    }
                } else {
                    throw new ApplicationException("", "No fetch operation available");
                }

                if (pagedServiceResult != null) {
                    sendResponse(response.getWriter(), pagedServiceResult);
                } else {
                    int resultSize = serviceResult == null ? 0 : serviceResult.size();
                    endRow = (endRow == 0 ? resultSize : endRow);
                    sendResponse(response.getWriter(), startRow, endRow < resultSize ? endRow : resultSize,
                            serviceResult);
                }
            } else if (operationType.equals("update") && request.getParameter("id") != null) {
                Object val = serviceDesc.getFindById().invoke(serviceDesc.getInstance(),
                        ServiceContextStore.get(), Long.parseLong(request.getParameter("id")));
                HashMap<String, Object> reqData = unifyRequest(request);
                mapRequestToObj(reqData, serviceDesc.getExpectedClass(), val);
                serviceDesc.getOtherMethods().get("save").method.invoke(serviceDesc.getInstance(),
                        ServiceContextStore.get(), val);
                ArrayList<Object> list = new ArrayList<Object>();
                list.add(val);
                sendResponse(response.getWriter(), 0, 1, list);
            } else if ((operationType.equals("add") || operationType.equals("update"))
                    && request.getParameter("id") == null) {
                HashMap<String, Object> reqData = unifyRequest(request);
                Object val = makeNewInstance(serviceDesc.getExpectedClass(), reqData);
                if (val != null) {
                    mapRequestToObj(reqData, serviceDesc.getExpectedClass(), val);
                    serviceDesc.getOtherMethods().get("save").method.invoke(serviceDesc.getInstance(),
                            ServiceContextStore.get(), val);
                    ArrayList<Object> list = new ArrayList<Object>();
                    list.add(val);
                    sendResponse(response.getWriter(), 0, 1, list);
                } else {
                    throw makeApplicationException("Can't create new instance", "ERR9003",
                            serviceDesc.getExpectedClass().getName());
                }
            } else {
                throw makeApplicationException("Unsupported operation", "ERR9001", operationType);
            }
        } else {
            throw makeApplicationException("Wrong datasource name", "ERR9002", dataSource);
        }
    } catch (Throwable ex) {
        // Find most relevant exception in embedded exceptions
        ApplicationException appException = null;
        Throwable relevantException = ex;
        while (ex != null) {
            relevantException = ex;
            if (ex instanceof ApplicationException) {
                appException = (ApplicationException) ex;
                break;
            }
            if (ex instanceof ValidationException) {
                break;
            }

            ex = ex.getCause();
        }

        // Prepare message
        String msg = null;
        if (appException != null) {
            msg = translate(appException.getMessage());
            Serializable[] msgParams = appException.getMessageParameters();
            if (msgParams != null) {
                Object[] params = new Object[msgParams.length];
                for (int i = 0; i < msgParams.length; i++) {
                    if (msgParams[i] instanceof Translatable) {
                        params[i] = translate(((Translatable) msgParams[i]).getContent());
                    } else {
                        params[i] = msgParams[i];
                    }
                }
                msg = MessageFormat.format(msg, params);
            }
        } else if (relevantException instanceof ValidationException) {
            StringBuilder b = new StringBuilder();
            for (InvalidValue iv : ((ValidationException) relevantException).getInvalidValues()) {
                b.append("<b>").append(translate(iv.getPropertyName()) + ":</b> " + iv.getMessage())
                        .append("<br/>");
            }
            msg = b.toString();
        } else {
            msg = translate("ERR9000");
            msg = MessageFormat.format(msg,
                    new Object[] { relevantException.getClass().getName(), relevantException.getMessage() });
        }

        // Print stack trace
        log.log(Level.WARNING, "Relevant exception", relevantException);

        if (msg != null) {
            log.log(Level.WARNING, "SENDING BACK ERROR '" + msg + "'");
            response.getWriter()
                    .write("{response:{ status:-1, data:\""
                            + msg.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"")
                            + "\", startRow:0, endRow:0, totalRows:0}}");
        }
        response.flushBuffer();
        // response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        throw new ServletException(msg);
    }
    response.flushBuffer();
}

From source file:org.kchine.r.server.http.frontend.CommandServlet.java

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

    HttpSession session = null;/*  w  ww. jav  a2  s .  com*/
    Object result = null;

    try {
        final String command = request.getParameter("method");
        do {

            if (command.equals("ping")) {
                result = "pong";
                break;
            } else if (command.equals("logon")) {

                session = request.getSession(false);
                if (session != null) {
                    result = session.getId();
                    break;
                }

                String login = (String) PoolUtils.hexToObject(request.getParameter("login"));
                String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd"));
                boolean namedAccessMode = login.contains("@@");
                String sname = null;
                if (namedAccessMode) {
                    sname = login.substring(login.indexOf("@@") + "@@".length());
                    login = login.substring(0, login.indexOf("@@"));
                }

                System.out.println("login :" + login);
                System.out.println("pwd :" + pwd);

                if (_rkit == null && (!login.equals(System.getProperty("login"))
                        || !pwd.equals(System.getProperty("pwd")))) {
                    result = new BadLoginPasswordException();
                    break;
                }

                HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils
                        .hexToObject(request.getParameter("options"));
                if (options == null)
                    options = new HashMap<String, Object>();
                System.out.println("options:" + options);

                RPFSessionInfo.get().put("LOGIN", login);
                RPFSessionInfo.get().put("REMOTE_ADDR", request.getRemoteAddr());
                RPFSessionInfo.get().put("REMOTE_HOST", request.getRemoteHost());

                boolean nopool = !options.keySet().contains("nopool")
                        || ((String) options.get("nopool")).equals("")
                        || !((String) options.get("nopool")).equalsIgnoreCase("false");
                boolean save = options.keySet().contains("save")
                        && ((String) options.get("save")).equalsIgnoreCase("true");
                boolean selfish = options.keySet().contains("selfish")
                        && ((String) options.get("selfish")).equalsIgnoreCase("true");

                String privateName = (String) options.get("privatename");

                int memoryMin = DEFAULT_MEMORY_MIN;
                int memoryMax = DEFAULT_MEMORY_MAX;
                try {
                    if (options.get("memorymin") != null)
                        memoryMin = Integer.decode((String) options.get("memorymin"));
                    if (options.get("memorymax") != null)
                        memoryMax = Integer.decode((String) options.get("memorymax"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                boolean privateEngineMode = false;
                RServices r = null;
                URL[] codeUrls = null;

                if (_rkit == null) {

                    if (namedAccessMode) {

                        try {
                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                if (PoolUtils.isStubCandidate(sname)) {
                                    r = (RServices) PoolUtils.hexToStub(sname,
                                            PoolUtils.class.getClassLoader());
                                } else {
                                    r = (RServices) ((DBLayerInterface) SSHTunnelingProxy.getDynamicProxy(
                                            System.getProperty("submit.ssh.host"),
                                            Integer.decode(System.getProperty("submit.ssh.port")),
                                            System.getProperty("submit.ssh.user"),
                                            System.getProperty("submit.ssh.password"),
                                            System.getProperty("submit.ssh.biocep.home"),
                                            "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                            "db", new Class<?>[] { DBLayerInterface.class })).lookup(sname);
                                }

                            } else {

                                if (PoolUtils.isStubCandidate(sname)) {
                                    r = (RServices) PoolUtils.hexToStub(sname,
                                            PoolUtils.class.getClassLoader());
                                } else {
                                    ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                                    if (spFactory == null) {
                                        result = new NoRegistryAvailableException();
                                        break;
                                    }
                                    r = (RServices) spFactory.getServantProvider().getRegistry().lookup(sname);
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
                        if (nopool) {

                            /*                         
                            ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                                    
                            if (spFactory == null) {
                               result = new NoRegistryAvailableException();
                               break;
                            }
                                    
                            String nodeName = options.keySet().contains("node") ? (String) options.get("node") : System
                                  .getProperty("private.servant.node.name");
                            Registry registry = spFactory.getServantProvider().getRegistry();
                            NodeManager nm = null;
                            try {
                               nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name") + "_" + nodeName);
                            } catch (NotBoundException nbe) {
                               nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name"));
                            } catch (Exception e) {
                               result = new NoNodeManagerFound();
                               break;
                            }
                            r = (RServices) nm.createPrivateServant(nodeName);
                             */

                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                DBLayerInterface dbLayer = (DBLayerInterface) SSHTunnelingProxy.getDynamicProxy(
                                        System.getProperty("submit.ssh.host"),
                                        Integer.decode(System.getProperty("submit.ssh.port")),
                                        System.getProperty("submit.ssh.user"),
                                        System.getProperty("submit.ssh.password"),
                                        System.getProperty("submit.ssh.biocep.home"),
                                        "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                        "db", new Class<?>[] { DBLayerInterface.class });
                                if (privateName != null && !privateName.equals("")) {
                                    try {
                                        r = (RServices) dbLayer.lookup(privateName);
                                    } catch (Exception e) {
                                        //e.printStackTrace();
                                    }
                                }

                                if (r == null) {

                                    final String uid = (privateName != null && !privateName.equals(""))
                                            ? privateName
                                            : UUID.randomUUID().toString();
                                    final String[] jobIdHolder = new String[1];
                                    new Thread(new Runnable() {
                                        public void run() {
                                            try {

                                                String command = "java -Dlog.file="
                                                        + System.getProperty("submit.ssh.biocep.home")
                                                        + "/log/%{uid}.log" + " -Drmi.port.start="
                                                        + System.getProperty("submit.ssh.rmi.port.start")
                                                        + " -Dname=%{uid}" + " -Dnaming.mode=db" + " -Ddb.host="
                                                        + System.getProperty("submit.ssh.host") + " -Dwait=true"
                                                        + " -jar "
                                                        + System.getProperty("submit.ssh.biocep.home")
                                                        + "/biocep-core.jar";

                                                jobIdHolder[0] = SSHUtils.execSshBatch(command, uid,
                                                        System.getProperty("submit.ssh.prefix"),
                                                        System.getProperty("submit.ssh.host"),
                                                        Integer.decode(System.getProperty("submit.ssh.port")),
                                                        System.getProperty("submit.ssh.user"),
                                                        System.getProperty("submit.ssh.password"),
                                                        System.getProperty("submit.ssh.biocep.home"));
                                                System.out.println("jobId:" + jobIdHolder[0]);

                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }).start();

                                    long TIMEOUT = Long.decode(System.getProperty("submit.ssh.timeout"));
                                    long tStart = System.currentTimeMillis();
                                    while ((System.currentTimeMillis() - tStart) < TIMEOUT) {
                                        try {
                                            r = (RServices) dbLayer.lookup(uid);
                                        } catch (Exception e) {

                                        }
                                        if (r != null)
                                            break;
                                        try {
                                            Thread.sleep(10);
                                        } catch (Exception e) {
                                        }
                                    }

                                    if (r != null) {
                                        try {
                                            r.setJobId(jobIdHolder[0]);
                                        } catch (Exception e) {
                                            r = null;
                                        }
                                    }

                                }

                            } else {
                                System.out.println("LocalHttpServer.getLocalHttpServerPort():"
                                        + LocalHttpServer.getLocalHttpServerPort());
                                System.out.println("LocalRmiRegistry.getLocalRmiRegistryPort():"
                                        + LocalHttpServer.getLocalHttpServerPort());
                                if (privateName != null && !privateName.equals("")) {
                                    try {
                                        r = (RServices) LocalRmiRegistry.getInstance().lookup(privateName);
                                    } catch (Exception e) {
                                        //e.printStackTrace();
                                    }
                                }

                                if (r == null) {
                                    codeUrls = (URL[]) options.get("urls");
                                    System.out.println("CODE URL->" + Arrays.toString(codeUrls));
                                    //String 
                                    r = ServerManager.createR(System.getProperty("r.binary"), false, false,
                                            PoolUtils.getHostIp(), LocalHttpServer.getLocalHttpServerPort(),
                                            ServerManager.getRegistryNamingInfo(PoolUtils.getHostIp(),
                                                    LocalRmiRegistry.getLocalRmiRegistryPort()),
                                            memoryMin, memoryMax, privateName, false, codeUrls, null,
                                            (_webAppMode ? "javaws" : "standard"), null, "127.0.0.1");
                                }

                                privateEngineMode = true;
                            }

                        } else {

                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                ServantProvider servantProvider = (ServantProvider) SSHTunnelingProxy
                                        .getDynamicProxy(System.getProperty("submit.ssh.host"),
                                                Integer.decode(System.getProperty("submit.ssh.port")),
                                                System.getProperty("submit.ssh.user"),
                                                System.getProperty("submit.ssh.password"),
                                                System.getProperty("submit.ssh.biocep.home"),
                                                "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                                "servant.provider", new Class<?>[] { ServantProvider.class });
                                boolean wait = options.keySet().contains("wait")
                                        && ((String) options.get("wait")).equalsIgnoreCase("true");
                                String poolname = ((String) options.get("poolname"));
                                if (wait) {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? servantProvider.borrowServantProxy()
                                            : servantProvider.borrowServantProxy(poolname));
                                } else {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? servantProvider.borrowServantProxyNoWait()
                                            : servantProvider.borrowServantProxyNoWait(poolname));
                                }

                                System.out.println("---> borrowed : " + r);

                            } else {
                                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();

                                if (spFactory == null) {
                                    result = new NoRegistryAvailableException();
                                    break;
                                }

                                boolean wait = options.keySet().contains("wait")
                                        && ((String) options.get("wait")).equalsIgnoreCase("true");
                                String poolname = ((String) options.get("poolname"));
                                if (wait) {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? spFactory.getServantProvider().borrowServantProxy()
                                            : spFactory.getServantProvider().borrowServantProxy(poolname));
                                } else {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? spFactory.getServantProvider().borrowServantProxyNoWait()
                                            : spFactory.getServantProvider()
                                                    .borrowServantProxyNoWait(poolname));
                                }
                            }
                        }
                    }
                } else {
                    r = _rkit.getR();
                }

                if (r == null) {
                    result = new NoServantAvailableException();
                    break;
                }

                session = request.getSession(true);

                Integer sessionTimeOut = null;
                try {
                    if (options.get("sessiontimeout") != null)
                        sessionTimeOut = Integer.decode((String) options.get("sessiontimeout"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (sessionTimeOut != null) {
                    session.setMaxInactiveInterval(sessionTimeOut);
                }

                session.setAttribute("TYPE", "RS");
                session.setAttribute("R", r);
                session.setAttribute("NOPOOL", nopool);
                session.setAttribute("SAVE", save);
                session.setAttribute("LOGIN", login);
                session.setAttribute("NAMED_ACCESS_MODE", namedAccessMode);
                session.setAttribute("PROCESS_ID", r.getProcessId());
                session.setAttribute("JOB_ID", r.getJobId());
                session.setAttribute("SELFISH", selfish);
                session.setAttribute("IS_RELAY", _rkit != null);

                if (privateName != null)
                    session.setAttribute("PRIVATE_NAME", privateName);

                if (codeUrls != null && codeUrls.length > 0) {
                    session.setAttribute("CODEURLS", codeUrls);
                }

                session.setAttribute("THREADS", new ThreadsHolder());

                ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP"))
                        .put(session.getId(), session);
                saveSessionAttributes(session);

                Vector<HttpSession> sessionVector = ((HashMap<RServices, Vector<HttpSession>>) getServletContext()
                        .getAttribute("R_SESSIONS")).get(r);
                if (sessionVector == null) {
                    sessionVector = new Vector<HttpSession>();
                    ((HashMap<RServices, Vector<HttpSession>>) getServletContext().getAttribute("R_SESSIONS"))
                            .put(r, sessionVector);
                }

                sessionVector.add(session);

                if (_rkit == null && save) {
                    UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"), r);
                }

                System.out.println("---> Has Collaboration Listeners:" + r.hasRCollaborationListeners());
                if (selfish || !r.hasRCollaborationListeners()) {
                    try {
                        if (_rkit != null && _safeModeEnabled)
                            ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();

                        GDDevice[] devices = r.listDevices();
                        for (int i = 0; i < devices.length; ++i) {
                            String deviceName = devices[i].getId();
                            System.out.println("??? ---- deviceName=" + deviceName);
                            session.setAttribute(deviceName, devices[i]);
                        }

                    } finally {
                        if (_rkit != null && _safeModeEnabled)
                            ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                    }
                }

                if (privateEngineMode) {

                    if (options.get("newdevice") != null) {
                        GDDevice deviceProxy = null;
                        GDDevice[] dlist = r.listDevices();
                        if (dlist == null || dlist.length == 0) {
                            deviceProxy = r.newDevice(480, 480);
                        } else {
                            deviceProxy = dlist[0];
                        }
                        String deviceName = deviceProxy.getId();
                        session.setAttribute(deviceName, deviceProxy);
                        session.setAttribute("maindevice", deviceProxy);
                        saveSessionAttributes(session);
                    }

                    if (options.get("newgenericcallbackdevice") != null) {
                        GenericCallbackDevice genericCallBackDevice = null;
                        GenericCallbackDevice[] clist = r.listGenericCallbackDevices();
                        if (clist == null || clist.length == 0) {
                            genericCallBackDevice = r.newGenericCallbackDevice();
                        } else {
                            genericCallBackDevice = clist[0];
                        }
                        String genericCallBackDeviceName = genericCallBackDevice.getId();
                        session.setAttribute(genericCallBackDeviceName, genericCallBackDevice);
                        session.setAttribute("maingenericcallbackdevice", genericCallBackDevice);
                        saveSessionAttributes(session);
                    }

                }

                result = session.getId();

                break;

            } else if (command.equals("logondb")) {

                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                if (spFactory == null) {
                    result = new NoRegistryAvailableException();
                    break;
                }

                String login = (String) PoolUtils.hexToObject(request.getParameter("login"));
                String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd"));
                HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils
                        .hexToObject(request.getParameter("options"));
                if (options == null)
                    options = new HashMap<String, Object>();
                System.out.println("options:" + options);

                session = request.getSession(true);

                Integer sessionTimeOut = null;
                try {
                    if (options.get("sessiontimeout") != null)
                        sessionTimeOut = Integer.decode((String) options.get("sessiontimeout"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (sessionTimeOut != null) {
                    session.setMaxInactiveInterval(sessionTimeOut);
                }

                session.setAttribute("TYPE", "DBS");
                session.setAttribute("REGISTRY", (DBLayer) spFactory.getServantProvider().getRegistry());
                session.setAttribute("SUPERVISOR",
                        new SupervisorUtils((DBLayer) spFactory.getServantProvider().getRegistry()));
                session.setAttribute("THREADS", new ThreadsHolder());
                ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP"))
                        .put(session.getId(), session);
                saveSessionAttributes(session);

                result = session.getId();

                break;

            }

            session = request.getSession(false);
            if (session == null) {
                result = new NotLoggedInException();
                break;
            }

            if (command.equals("logoff")) {

                if (session.getAttribute("TYPE").equals("RS")) {
                    if (_rkit != null) {
                        /*
                        Enumeration<String> attributeNames = session.getAttributeNames();
                        while (attributeNames.hasMoreElements()) {
                           String aname = attributeNames.nextElement();
                           if (session.getAttribute(aname) instanceof GDDevice) {
                              try {
                                 _rkit.getRLock().lock();
                                 ((GDDevice) session.getAttribute(aname)).dispose();
                              } catch (Exception e) {
                                 e.printStackTrace();
                              } finally {
                                 _rkit.getRLock().unlock();
                              }
                           }
                        }
                        */
                    }
                }

                try {

                    session.invalidate();

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                result = null;
                break;
            }

            final boolean[] stop = { false };
            final HttpSession currentSession = session;

            if (command.equals("invoke")) {

                String servantName = (String) PoolUtils.hexToObject(request.getParameter("servantname"));
                final Object servant = session.getAttribute(servantName);
                if (servant == null) {
                    throw new Exception("Bad Servant Name :" + servantName);
                }
                String methodName = (String) PoolUtils.hexToObject(request.getParameter("methodname"));

                ClassLoader urlClassLoader = this.getClass().getClassLoader();
                if (session.getAttribute("CODEURLS") != null) {
                    urlClassLoader = new URLClassLoader((URL[]) session.getAttribute("CODEURLS"),
                            this.getClass().getClassLoader());
                }

                Class<?>[] methodSignature = (Class[]) PoolUtils
                        .hexToObject(request.getParameter("methodsignature"));

                final Method m = servant.getClass().getMethod(methodName, methodSignature);
                if (m == null) {
                    throw new Exception("Bad Method Name :" + methodName);
                }
                final Object[] methodParams = (Object[]) PoolUtils
                        .hexToObject(request.getParameter("methodparameters"), urlClassLoader);
                final Object[] resultHolder = new Object[1];
                Runnable rmiRunnable = new Runnable() {
                    public void run() {
                        try {
                            if (_rkit != null && _safeModeEnabled)
                                ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                            resultHolder[0] = m.invoke(servant, methodParams);
                            if (resultHolder[0] == null)
                                resultHolder[0] = RMICALL_DONE;
                        } catch (InvocationTargetException ite) {
                            if (ite.getCause() instanceof ConnectException) {
                                currentSession.invalidate();
                                resultHolder[0] = new NotLoggedInException();
                            } else {
                                resultHolder[0] = ite.getCause();
                            }
                        } catch (Exception e) {
                            final boolean wasInterrupted = Thread.interrupted();
                            if (wasInterrupted) {
                                resultHolder[0] = new RmiCallInterrupted();
                            } else {
                                resultHolder[0] = e;
                            }
                        } finally {
                            if (_rkit != null && _safeModeEnabled)
                                ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                        }
                    }
                };

                Thread rmiThread = InterruptibleRMIThreadFactory.getInstance().newThread(rmiRunnable);
                ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().add(rmiThread);
                rmiThread.start();

                long t1 = System.currentTimeMillis();

                while (resultHolder[0] == null) {

                    if ((System.currentTimeMillis() - t1) > RMICALL_TIMEOUT_MILLISEC || stop[0]) {
                        rmiThread.interrupt();
                        resultHolder[0] = new RmiCallTimeout();
                        break;
                    }

                    try {
                        Thread.sleep(10);
                    } catch (Exception e) {
                    }
                }
                try {
                    ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().remove(rmiThread);
                } catch (IllegalStateException e) {
                }

                if (resultHolder[0] instanceof Throwable) {
                    throw (Throwable) resultHolder[0];
                }

                if (resultHolder[0] == RMICALL_DONE) {
                    result = null;
                } else {
                    result = resultHolder[0];
                }

                break;

            }

            if (command.equals("interrupt")) {
                final Vector<Thread> tvec = (Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS"))
                        .getThreads().clone();
                for (int i = 0; i < tvec.size(); ++i) {
                    try {
                        tvec.elementAt(i).interrupt();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                stop[0] = true;
                ((Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS")).getThreads())
                        .removeAllElements();
                result = null;
                break;
            } else if (command.equals("saveimage")) {
                UserUtils.saveWorkspace((String) session.getAttribute("LOGIN"),
                        (RServices) session.getAttribute("R"));
                result = null;
                break;
            } else if (command.equals("loadimage")) {
                UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"),
                        (RServices) session.getAttribute("R"));
                result = null;
                break;
            } else if (command.equals("newdevice")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                    boolean broadcasted = new Boolean(request.getParameter("broadcasted"));
                    GDDevice deviceProxy = null;
                    if (broadcasted) {
                        deviceProxy = ((RServices) session.getAttribute("R")).newBroadcastedDevice(
                                Integer.decode(request.getParameter("width")),
                                Integer.decode(request.getParameter("height")));
                    } else {
                        deviceProxy = ((RServices) session.getAttribute("R")).newDevice(
                                Integer.decode(request.getParameter("width")),
                                Integer.decode(request.getParameter("height")));
                    }

                    String deviceName = deviceProxy.getId();
                    System.out.println("deviceName=" + deviceName);
                    session.setAttribute(deviceName, deviceProxy);
                    saveSessionAttributes(session);
                    result = deviceName;
                    break;
                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("listdevices")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();

                    result = new Vector<String>();
                    for (Enumeration<String> e = session.getAttributeNames(); e.hasMoreElements();) {
                        String attributeName = e.nextElement();
                        if (attributeName.startsWith("device_")) {
                            ((Vector<String>) result).add(attributeName);
                        }
                    }

                    break;

                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("newgenericcallbackdevice")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                    GenericCallbackDevice genericCallBackDevice = ((RServices) session.getAttribute("R"))
                            .newGenericCallbackDevice();

                    String genericCallBackDeviceName = genericCallBackDevice.getId();
                    session.setAttribute(genericCallBackDeviceName, genericCallBackDevice);
                    saveSessionAttributes(session);

                    result = genericCallBackDeviceName;

                    break;
                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("newspreadsheetmodeldevice")) {

                String spreadsheetModelDeviceId = request.getParameter("id");
                SpreadsheetModelRemote model = null;

                if (spreadsheetModelDeviceId == null || spreadsheetModelDeviceId.equals("")) {
                    model = ((RServices) session.getAttribute("R")).newSpreadsheetTableModelRemote(
                            Integer.decode(request.getParameter("rowcount")),
                            Integer.decode(request.getParameter("colcount")));
                } else {
                    model = ((RServices) session.getAttribute("R"))
                            .getSpreadsheetTableModelRemote(spreadsheetModelDeviceId);
                }

                SpreadsheetModelDevice spreadsheetDevice = model.newSpreadsheetModelDevice();
                String spreadsheetDeviceId = spreadsheetDevice.getId();
                session.setAttribute(spreadsheetDeviceId, spreadsheetDevice);
                saveSessionAttributes(session);
                result = spreadsheetDeviceId;
                break;

            } else if (command.equals("list")) {
                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                if (spFactory == null) {
                    result = new NoRegistryAvailableException();
                    break;
                }
                result = spFactory.getServantProvider().getRegistry().list();
                break;
            }

        } while (true);

    } catch (TunnelingException te) {
        result = te;
        te.printStackTrace();
    } catch (Throwable e) {
        result = new TunnelingException("Server Side", e);
        e.printStackTrace();
    }
    response.setContentType("application/x-java-serialized-object");
    new ObjectOutputStream(response.getOutputStream()).writeObject(result);
    response.flushBuffer();

}

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);//w w  w.  j a  va2  s . 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();
}