Example usage for org.springframework.util MultiValueMap keySet

List of usage examples for org.springframework.util MultiValueMap keySet

Introduction

In this page you can find the example usage for org.springframework.util MultiValueMap keySet.

Prototype

Set<K> keySet();

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:jails.http.converter.FormHttpMessageConverter.java

private void writeForm(MultiValueMap<String, String> form, HttpOutputMessage outputMessage) throws IOException {
    outputMessage.getHeaders().setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    StringBuilder builder = new StringBuilder();
    for (Iterator<String> nameIterator = form.keySet().iterator(); nameIterator.hasNext();) {
        String name = nameIterator.next();
        for (Iterator<String> valueIterator = form.get(name).iterator(); valueIterator.hasNext();) {
            String value = valueIterator.next();
            builder.append(URLEncoder.encode(name, charset.name()));
            if (value != null) {
                builder.append('=');
                builder.append(URLEncoder.encode(value, charset.name()));
                if (valueIterator.hasNext()) {
                    builder.append('&');
                }//from  ww w . j  ava2  s . c  om
            }
        }
        if (nameIterator.hasNext()) {
            builder.append('&');
        }
    }
    FileCopyUtils.copy(builder.toString(), new OutputStreamWriter(outputMessage.getBody(), charset));
}

From source file:com.vedri.mtp.frontend.support.stomp.DefaultSubscriptionRegistry.java

private MultiValueMap<String, String> filterSubscriptions(MultiValueMap<String, String> allMatches,
        Message<?> message) {/* w ww. j  av a2  s  .  c o m*/

    if (!this.selectorHeaderInUse) {
        return allMatches;
    }
    EvaluationContext context = null;
    MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(allMatches.size());
    for (String sessionId : allMatches.keySet()) {
        for (String subId : allMatches.get(sessionId)) {
            SessionSubscriptionInfo info = this.subscriptionRegistry.getSubscriptions(sessionId);
            if (info == null) {
                continue;
            }
            Subscription sub = info.getSubscription(subId);
            if (sub == null) {
                continue;
            }
            Expression expression = sub.getSelectorExpression();
            if (expression == null) {
                result.add(sessionId, subId);
                continue;
            }
            if (context == null) {
                context = new StandardEvaluationContext(message);
                context.getPropertyAccessors().add(new SimpMessageHeaderPropertyAccessor());
            }
            try {
                if (expression.getValue(context, boolean.class)) {
                    result.add(sessionId, subId);
                }
            } catch (SpelEvaluationException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Failed to evaluate selector: " + ex.getMessage());
                }
            } catch (Throwable ex) {
                logger.debug("Failed to evaluate selector", ex);
            }
        }
    }
    return result;
}

From source file:com.httpMessageConvert.FormHttpMessageConverter.java

private void writeForm(MultiValueMap<String, String> form, MediaType contentType,
        HttpOutputMessage outputMessage) throws IOException {
    Charset charset;//from w  w  w .j a  v  a  2  s . c o m
    if (contentType != null) {
        outputMessage.getHeaders().setContentType(contentType);
        charset = contentType.getCharSet() != null ? contentType.getCharSet() : this.charset;
    } else {
        outputMessage.getHeaders().setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        charset = this.charset;
    }
    StringBuilder builder = new StringBuilder();
    for (Iterator<String> nameIterator = form.keySet().iterator(); nameIterator.hasNext();) {
        String name = nameIterator.next();
        for (Iterator<String> valueIterator = form.get(name).iterator(); valueIterator.hasNext();) {
            String value = valueIterator.next();
            builder.append(URLEncoder.encode(name, charset.name()));
            if (value != null) {
                builder.append('=');
                builder.append(URLEncoder.encode(value, charset.name()));
                if (valueIterator.hasNext()) {
                    builder.append('&');
                }
            }
        }
        if (nameIterator.hasNext()) {
            builder.append('&');
        }
    }
    byte[] bytes = builder.toString().getBytes(charset.name());
    outputMessage.getHeaders().setContentLength(bytes.length);
    StreamUtils.copy(bytes, outputMessage.getBody());
}

From source file:puma.application.evaluation.AdvancedDocumentController.java

private puma.peputils.Object constructAuthzObject(Document doc, MultiValueMap<String, String> params) {
    puma.peputils.Object object = new puma.peputils.Object("" + doc.getId());
    object.addAttributeValue(new ObjectAttributeValue("type", "document"));
    object.addAttributeValue(new ObjectAttributeValue("name", doc.getName()));
    object.addAttributeValue(new ObjectAttributeValue("sent-date", doc.getDate()));
    object.addAttributeValue(new ObjectAttributeValue("creating-tenant", doc.getCreatingTenant()));
    //object.addAttributeValue(new ObjectAttributeValue("owning-tenant", doc.getDestination()));
    object.addAttributeValue(new ObjectAttributeValue("content", "TODO.pdf"));
    object.addAttributeValue(new ObjectAttributeValue("origin", doc.getOrigin()));
    object.addAttributeValue(new ObjectAttributeValue("destination", doc.getDestination()));
    for (String nextKey : params.keySet())
        for (String nextValue : params.get(nextKey))
            addAttribute(object, nextKey, nextValue);
    return object;
}

From source file:com.htmlhifive.sync.service.SyncResourceProcessor.java

/**
 * ?????.<br/>//from w  w w .  ja  v  a2  s  .  co m
 * sync?????????.
 *
 * @param requestMessages
 * @throws AbstractResourceException
 */
private void processDownloadControl(RequestMessageContainer requestMessages) throws AbstractResourceException {

    DownloadControlType controlType = DownloadControlType
            .valueOf(syncConfigurationParameter.DOWNLOAD_CONTROL_TYPE);

    switch (controlType) {

    // LOCK???????
    case LOCK:

        MultiValueMap<ResourceItemCommonDataId, RequestMessage> messageMap = new LinkedMultiValueMap<>();
        for (RequestMessage requestMessage : requestMessages.getMessages()) {
            ResourceItemCommonDataId resourceItemCommonDataId = (ResourceItemCommonDataId) requestMessage
                    .get(syncConfigurationParameter.RESOURCE_ITEM_COMMON_DATA_ID);
            messageMap.add(resourceItemCommonDataId, requestMessage);
        }
        List<ResourceItemCommonDataId> commonDataIdList = new ArrayList<>(messageMap.keySet());
        Collections.sort(commonDataIdList);

        for (ResourceItemCommonDataId itemCommonDataId : commonDataIdList) {

            List<RequestMessage> messagesForId = messageMap.get(itemCommonDataId);
            for (RequestMessage message : messagesForId) {

                // ??
                ResourceMethodInvoker resourceMethod = getResourceManager().getResourceMethodByName(
                        itemCommonDataId.getResourceName(), syncConfigurationParameter.ACTION_FOR_GETFORUPDATE,
                        message);
                applyDefaultSynchronizer(resourceMethod);

                // ???
                @SuppressWarnings("unchecked")
                List<ResourceItemCommonData> got = (List<ResourceItemCommonData>) resourceMethod
                        .invoke(message);
                message.put(syncConfigurationParameter.RESOURCE_ITEM_COMMON_DATA, got);
            }
        }

    case NONE:
    default:
        break;
    }
}

From source file:com.htmlhifive.sync.service.SyncResourceProcessor.java

/**
 * ?????.<br/>/*from   w  w w  .  j  av  a 2  s.c om*/
 * sync?????????.
 *
 * @param requestMessages 
 * @throws AbstractResourceException
 */
private void processUploadControl(RequestMessageContainer requestMessages) throws AbstractResourceException {

    UploadControlType controlType = UploadControlType.valueOf(syncConfigurationParameter.UPLOAD_CONTROL_TYPE);

    if (controlType == UploadControlType.NONE) {
        return;
    }

    MultiValueMap<ResourceItemCommonDataId, RequestMessage> messageMap = new LinkedMultiValueMap<>();
    for (RequestMessage requestMessage : requestMessages.getMessages()) {
        ResourceItemCommonDataId resourceItemCommonDataId = (ResourceItemCommonDataId) requestMessage
                .get(syncConfigurationParameter.RESOURCE_ITEM_COMMON_DATA_ID);
        messageMap.add(resourceItemCommonDataId, requestMessage);
    }

    // ID?
    List<ResourceItemCommonDataId> commonDataIdList = new ArrayList<>(messageMap.keySet());
    Collections.sort(commonDataIdList);

    switch (controlType) {
    case SORT:

        // Container?Message???
        List<RequestMessage> sorted = new ArrayList<>();
        for (ResourceItemCommonDataId itemCommonDataId : commonDataIdList) {
            List<RequestMessage> messagesForId = messageMap.get(itemCommonDataId);
            for (RequestMessage message : messagesForId) {
                sorted.add(message);
            }
        }
        requestMessages.setMessages(sorted);

        break;

    case LOCK:

        // ????
        for (ResourceItemCommonDataId itemCommonDataId : commonDataIdList) {
            List<RequestMessage> messagesForId = messageMap.get(itemCommonDataId);
            for (RequestMessage message : messagesForId) {

                // ??
                ResourceMethodInvoker resourceMethod = getResourceManager().getResourceMethodByName(
                        itemCommonDataId.getResourceName(), syncConfigurationParameter.ACTION_FOR_GETFORUPDATE,
                        message);
                applyDefaultSynchronizer(resourceMethod);

                // ???
                // ????????
                @SuppressWarnings("unchecked")
                List<ResourceItemCommonData> got = (List<ResourceItemCommonData>) resourceMethod
                        .invoke(message);
                message.put(syncConfigurationParameter.RESOURCE_ITEM_COMMON_DATA, got);
            }
        }

        break;

    default:
        break;

    }
}

From source file:com.ephesoft.dcma.webservice.service.EphesoftWebService.java

/**
 * Sign up method.//from   w  w w.j  a v  a 2  s .  c o m
 * @param request {@link HttpServletRequest}
 * @param response {@link HttpServletResponse}
 */
@RequestMapping(value = "/signUp", method = RequestMethod.POST)
@ResponseBody
public void signUp(final HttpServletRequest request, final HttpServletResponse response) {
    LOGGER.info("Start processing sign up process");
    String workingDir = WebServiceUtil.EMPTY_STRING;
    InputStream instream = null;
    if (request instanceof DefaultMultipartHttpServletRequest) {
        UserInformation userInformation = null;
        User user = null;
        String receiverName = null;
        try {
            final String webServiceFolderPath = batchSchemaService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            LOGGER.info("workingDir:" + workingDir);
            final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir);
            LOGGER.info("outputDir:" + outputDir);
            final DefaultMultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest) request;
            final String batchClassId = request.getParameter("batchClassId");
            final String batchClassPriority = request.getParameter("batchClassPriority");
            final String batchClassDescription = request.getParameter("batchClassDescription");
            String batchClassName = request.getParameter("batchClassName");
            batchClassName = getUniqueBatchClassName(batchClassName);
            final String batchInstanceLimit = request.getParameter("batchInstanceLimit");
            final String noOfDays = request.getParameter("noOfDays");
            final String pageCount = request.getParameter("pageCount");
            String uncFolder = "unc" + ICommonConstants.HYPHEN + batchClassName;
            LOGGER.info("Batch Class ID value is: " + batchClassId);
            LOGGER.info("Batch Class Priority value is: " + batchClassPriority);
            LOGGER.info("Batch Class Description value is: " + batchClassDescription);
            LOGGER.info("Batch Class Name value is: " + batchClassName);
            LOGGER.info("UNC Folder value is: " + uncFolder);
            final MultiValueMap<String, MultipartFile> fileMap = multipartRequest.getMultiFileMap();
            for (final String fileName : fileMap.keySet()) {
                if (fileName.toLowerCase(Locale.getDefault())
                        .indexOf(FileType.XML.getExtension().toLowerCase()) > -WebserviceConstants.ONE) {
                    final MultipartFile multipartFile = multipartRequest.getFile(fileName);
                    instream = multipartFile.getInputStream();
                    final Source source = XMLUtil.createSourceFromStream(instream);
                    userInformation = (UserInformation) batchSchemaDao.getJAXB2Template().getJaxb2Marshaller()
                            .unmarshal(source);
                    user = createUserObjectFromUserInformation(userInformation);
                    break;
                }
            }
            if (userInformation != null && user != null) {
                LOGGER.info("Recevier name created: " + receiverName);
                userConnectivityService.addUser(userInformation);
                LOGGER.info("Successfully added user for email id: " + userInformation.getEmail());
                userConnectivityService.addGroup(userInformation);
                LOGGER.info("Successfully added group for email id: " + userInformation.getEmail());
                BatchClass batchClass = batchClassService.copyBatchClass(
                        batchClassId, batchClassName, batchClassDescription, userInformation.getCompanyName()
                                + ICommonConstants.UNDERSCORE + userInformation.getEmail(),
                        batchClassPriority, uncFolder, true);
                LOGGER.info("Adding user information into database");
                user.setBatchClass(batchClass);
                userService.createUser(user);
                LOGGER.info("Successfully added user information into database");
                BatchClassCloudConfig batchClassCloudConfig = createBatchClassCloudConfig(batchInstanceLimit,
                        noOfDays, pageCount, batchClass);
                batchClassCloudConfigService.createBatchClassCloudConfig(batchClassCloudConfig);
                LOGGER.info("Successfully copied batch class for batch class: " + batchClassId);
                deploymentService.createAndDeployBatchClassJpdl(batchClass);
                LOGGER.info("Batch Class deployed successfully");
                wizardMailService.sendConfirmationMail(userInformation, false, null);
                LOGGER.info("User login information sent for email id: " + userInformation.getEmail());
            } else {
                LOGGER.error(
                        "user Information file is invalid. Unable create the User Information Object from XML.");
            }
        } catch (WizardMailException wizardMailException) {
            try {
                response.sendError(HttpServletResponse.SC_CREATED);
            } catch (IOException e) {
                LOGGER.error(ERROR_IN_SENDING_STATUS_USING_WEB_SERVICE);
            }
        } catch (Exception e) {
            LOGGER.error("Exception occurs while sign up process: " + e.getMessage(), e);
            if (userInformation != null && user != null) {
                LOGGER.info("Deleting created user/groups while signup for : " + userInformation.getEmail());
                userConnectivityService.deleteUser(userInformation.getEmail());
                userConnectivityService.deleteGroup(userInformation.getCompanyName()
                        + ICommonConstants.UNDERSCORE + userInformation.getEmail());
                userService.deleteUser(user);
                LOGGER.info(
                        "Successfully deleted user/groups while signup for : " + userInformation.getEmail());
                LOGGER.info("Sending error mail");
                try {
                    wizardMailService.sendConfirmationMail(userInformation, true,
                            ExceptionUtils.getStackTrace(e));
                    LOGGER.info("Error mail sent succesfully");
                } catch (WizardMailException e1) {
                    LOGGER.error("Error in sending error mail to client");
                }
            }
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            } catch (IOException e1) {
                LOGGER.error(ERROR_IN_SENDING_STATUS_USING_WEB_SERVICE);
            }

        }
    }
}

From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java

@RequestMapping(value = "/runReporting", method = RequestMethod.POST)
@ResponseBody//from   w  ww.  jav a 2s .c om
public void runReporting(final HttpServletRequest req, final HttpServletResponse resp) {
    logger.info("Start processing the run reporting web service");
    String respStr = WebServiceUtil.EMPTY_STRING;
    try {
        if (req instanceof DefaultMultipartHttpServletRequest) {

            InputStream instream = null;
            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;
            final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();
            for (final String fileName : fileMap.keySet()) {
                final MultipartFile multiPartFile = multiPartRequest.getFile(fileName);
                instream = multiPartFile.getInputStream();
                final Source source = XMLUtil.createSourceFromStream(instream);
                final ReportingOptions option = (ReportingOptions) batchSchemaDao.getJAXB2Template()
                        .getJaxb2Marshaller().unmarshal(source);
                final String installerPath = option.getInstallerPath();
                if (installerPath == null || installerPath.isEmpty()
                        || !installerPath.toLowerCase().contains("build.xml")) {
                    respStr = "Improper input to server. Installer path not specified or it does not contain the build.xml path.";
                } else {
                    logger.info("synchronizing the database");
                    reportingService.syncDatabase(installerPath);
                    break;
                }
            }

        } else {
            respStr = "Improper input to server. Expected multipart request. Returning without processing the results.";
        }
    } catch (final XmlMappingException xmle) {
        respStr = "Error in mapping input XML in the desired format. Please send it in the specified format. Detailed exception is "
                + xmle;
    } catch (final Exception e) {
        respStr = "Internal Server error.Please check logs for further details." + e;
    }

    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {

        }
    }
}

From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java

@RequestMapping(value = "/convertTiffToPdf", method = RequestMethod.POST)
@ResponseBody/*from  w w w  .j  av a  2  s . com*/
public void convertTiffToPdf(final HttpServletRequest req, final HttpServletResponse resp) {
    logger.info("Start processing web service for extract fuzzy DB for given HOCR file");
    String respStr = "";
    String workingDir = "";
    if (req instanceof DefaultMultipartHttpServletRequest) {
        try {
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir);

            InputStream instream = null;
            OutputStream outStream = null;

            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;

            final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();
            if (!fileMap.keySet().isEmpty()) {
                for (final String fileName : fileMap.keySet()) {
                    if (fileName.endsWith(FileType.TIF.getExtensionWithDot())
                            || fileName.endsWith(FileType.TIFF.getExtensionWithDot())) {
                    } else {
                        respStr = "Invalid file. Please passed the valid tif/tiff file";
                        break;
                    }
                    final MultipartFile multiPartFile = multiPartRequest.getFile(fileName);
                    instream = multiPartFile.getInputStream();
                    final File file = new File(workingDir + File.separator + fileName);
                    outStream = new FileOutputStream(file);
                    final byte[] buf = new byte[WebServiceUtil.bufferSize];
                    int len;
                    while ((len = instream.read(buf)) > 0) {
                        outStream.write(buf, 0, len);
                    }
                    if (instream != null) {
                        instream.close();
                    }

                    if (outStream != null) {
                        outStream.close();
                    }
                }
            } else {
                respStr = "Please passed the input files for processing";
            }

            if (respStr.isEmpty()) {
                String inputParams = WebServiceUtil.EMPTY_STRING;
                String outputParams = WebServiceUtil.EMPTY_STRING;
                String pdfGeneratorEngine = WebServiceUtil.EMPTY_STRING;
                for (final Enumeration<String> params = multiPartRequest.getParameterNames(); params
                        .hasMoreElements();) {
                    final String paramName = params.nextElement();
                    if (paramName.equalsIgnoreCase("inputParams")) {
                        inputParams = multiPartRequest.getParameter(paramName);
                        logger.info("Value for batchClassIdentifier parameter is " + inputParams);
                        continue;
                    }
                    if (paramName.equalsIgnoreCase("outputParams")) {
                        outputParams = multiPartRequest.getParameter(paramName);
                        logger.info("Value for hocrFile parameter is " + outputParams);
                        continue;
                    }
                    if (paramName.equalsIgnoreCase("pdfGeneratorEngine")) {
                        pdfGeneratorEngine = multiPartRequest.getParameter(paramName);
                        logger.info("Value for hocrFile parameter is " + pdfGeneratorEngine);
                        continue;
                    }
                }

                respStr = WebServiceUtil.validateConvertTiffToPdfAPI(pdfGeneratorEngine, inputParams,
                        outputParams);

                if (respStr.isEmpty()) {
                    Set<String> outputFileList = new HashSet<String>();
                    File file = new File(workingDir);
                    String[] fileList = file.list(new CustomFileFilter(false,
                            FileType.TIF.getExtensionWithDot(), FileType.TIFF.getExtensionWithDot()));

                    BatchInstanceThread batchInstanceThread = new BatchInstanceThread(workingDir);

                    for (String inputFile : fileList) {
                        String[] fileArray = new String[2];
                        String outputFile = inputFile.substring(0, inputFile.lastIndexOf(WebServiceUtil.DOT))
                                + FileType.PDF.getExtensionWithDot();
                        fileArray[0] = workingDir + File.separator + inputFile;
                        fileArray[1] = workingDir + File.separator + outputFile;
                        outputFileList.add(outputFile);
                        imService.createTifToPDF(pdfGeneratorEngine, fileArray, batchInstanceThread,
                                inputParams, outputParams);
                    }

                    batchInstanceThread.execute();

                    for (String outputFile : outputFileList) {
                        FileUtils.copyFile(new File(workingDir + File.separator + outputFile),
                                new File(outputDir + File.separator + outputFile));
                    }

                    ServletOutputStream out = null;
                    ZipOutputStream zout = null;
                    final String zipFileName = WebServiceUtil.serverOutputFolderName;
                    resp.setContentType("application/x-zip\r\n");
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName
                            + FileType.ZIP.getExtensionWithDot() + "\"\r\n");
                    try {
                        out = resp.getOutputStream();
                        zout = new ZipOutputStream(out);
                        FileUtils.zipDirectory(outputDir, zout, zipFileName);
                        resp.setStatus(HttpServletResponse.SC_OK);
                    } catch (final IOException e) {
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Error in creating output zip file.Please try again." + e.getMessage());
                    } finally {
                        if (zout != null) {
                            zout.close();
                        }
                        if (out != null) {
                            out.flush();
                        }
                        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                    }
                }
            }
        } catch (final XmlMappingException xmle) {
            respStr = "Error in mapping input XML in the desired format. Please send it in the specified format. Detailed exception is "
                    + xmle;
        } catch (final DCMAException dcmae) {
            respStr = "Error in processing request. Detailed exception is " + dcmae;
        } catch (final Exception e) {
            respStr = "Internal Server error.Please check logs for further details." + e;
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        }
    } else {
        respStr = "Improper input to server. Expected multipart request. Returning without processing the results.";
    }
    if (!respStr.isEmpty()) {
        try {
            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {

        }
    }
}

From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java

@RequestMapping(value = "/createSearchablePDF", method = RequestMethod.POST)
@ResponseBody//  w w w.j a  v  a 2s.c  o m
public void createSearchablePDF(final HttpServletRequest request, final HttpServletResponse response) {
    logger.info("Start processing web service for create searchable pdf");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    if (request instanceof DefaultMultipartHttpServletRequest) {
        try {
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir);

            InputStream instream = null;
            OutputStream outStream = null;
            final DefaultMultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest) request;
            final BatchInstanceThread batchInstanceThread = new BatchInstanceThread(
                    new File(workingDir).getName() + Math.random());

            final String isColorImage = request.getParameter("isColorImage");
            final String isSearchableImage = request.getParameter("isSearchableImage");
            final String outputPDFFileName = request.getParameter("outputPDFFileName");
            final String projectFile = request.getParameter("projectFile");
            String results = WebServiceUtil.validateSearchableAPI(outputPDFFileName, projectFile,
                    FileType.PDF.getExtensionWithDot(), isSearchableImage, isColorImage);
            if (!results.isEmpty()) {
                respStr = results;
            } else {
                logger.info("Value of isColorImage" + isColorImage);
                logger.info("Value of isSearchableImage" + isSearchableImage);
                logger.info("Value of outputPDFFileName" + outputPDFFileName);
                logger.info("Value of projectFile" + projectFile);

                final MultiValueMap<String, MultipartFile> fileMap = multipartRequest.getMultiFileMap();
                for (final String fileName : fileMap.keySet()) {
                    if (fileName.toLowerCase().indexOf(WebServiceUtil.RSP_EXTENSION) > -1
                            || fileName.toLowerCase().indexOf(FileType.TIF.getExtension()) > -1
                            || fileName.toLowerCase().indexOf(FileType.TIFF.getExtension()) > -1) {
                        // only tiffs and RSP file is expected
                        final MultipartFile f = multipartRequest.getFile(fileName);
                        instream = f.getInputStream();
                        final File file = new File(workingDir + File.separator + fileName);
                        outStream = new FileOutputStream(file);
                        final byte[] buf = new byte[WebServiceUtil.bufferSize];
                        int len;
                        while ((len = instream.read(buf)) > 0) {
                            outStream.write(buf, 0, len);
                        }
                        if (instream != null) {
                            instream.close();
                        }
                        if (outStream != null) {
                            outStream.close();
                        }
                    } else {
                        respStr = "Only tiff, tif and rsp files expected.";
                        break;
                    }
                }
                if (respStr.isEmpty()) {
                    String[] imageFiles = null;
                    final File file = new File(workingDir);

                    imageFiles = file.list(new CustomFileFilter(false, FileType.TIFF.getExtensionWithDot(),
                            FileType.TIF.getExtensionWithDot()));

                    if (imageFiles == null || imageFiles.length == 0) {
                        respStr = "No tif/tiff file found for processing.";
                    }

                    String rspProjectFile = workingDir + File.separator + projectFile;

                    File rspFile = new File(rspProjectFile);

                    if (rspProjectFile == null || !rspFile.exists()) {
                        respStr = "Invalid project file. Please verify the project file.";
                    }

                    if (respStr.isEmpty()) {
                        final String[] pages = new String[imageFiles.length + 1];
                        int index = 0;
                        for (final String imageFileName : imageFiles) {
                            pages[index] = workingDir + File.separator + imageFileName;
                            index++;

                            if (WebServiceUtil.TRUE.equalsIgnoreCase(isColorImage)) {
                                try {
                                    logger.info("Generating png image files");
                                    imService.generatePNGForImage(
                                            new File(workingDir + File.separator + imageFileName));
                                    final String pngFileName = imageFileName.substring(0,
                                            imageFileName.lastIndexOf(WebServiceUtil.DOT))
                                            + FileType.PNG.getExtensionWithDot();
                                    recostarService.createOCR(projectFile, workingDir, WebServiceUtil.ON_STRING,
                                            pngFileName, batchInstanceThread, workingDir);
                                } catch (final DCMAException e) {
                                    FileUtils.deleteDirectoryAndContentsRecursive(
                                            new File(workingDir).getParentFile());
                                    respStr = "Error in generating plugin output." + imageFileName + ". " + e;
                                }
                            } else {
                                try {
                                    recostarService.createOCR(projectFile, workingDir,
                                            WebServiceUtil.OFF_STRING, imageFileName, batchInstanceThread,
                                            workingDir);
                                } catch (final DCMAException e) {
                                    FileUtils.deleteDirectoryAndContentsRecursive(
                                            new File(workingDir).getParentFile());
                                    respStr = "Error in generating plugin output." + imageFileName + ". " + e;
                                }
                            }
                        }
                        try {
                            logger.info("Generating HOCR file for input images.");
                            batchInstanceThread.execute();
                            batchInstanceThread.remove();
                            final String outputPDFFile = workingDir + File.separator + outputPDFFileName;
                            pages[index] = outputPDFFile;
                            imService.createSearchablePDF(isColorImage, isSearchableImage, workingDir, pages,
                                    batchInstanceThread, WebServiceUtil.DOCUMENTID);
                            batchInstanceThread.execute();
                            logger.info("Copying output searchable file");
                            FileUtils.copyFile(new File(outputPDFFile),
                                    new File(outputDir + File.separator + outputPDFFileName));
                        } catch (final DCMAApplicationException e) {
                            batchInstanceThread.remove();
                            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                            respStr = "Error in generating searchable pdf." + e;
                        }
                        ServletOutputStream out = null;
                        ZipOutputStream zout = null;
                        final String zipFileName = WebServiceUtil.serverOutputFolderName;
                        response.setContentType("application/x-zip\r\n");
                        response.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName
                                + FileType.ZIP.getExtensionWithDot() + "\"\r\n");
                        try {
                            out = response.getOutputStream();
                            zout = new ZipOutputStream(out);
                            FileUtils.zipDirectory(outputDir, zout, zipFileName);
                            response.setStatus(HttpServletResponse.SC_OK);
                        } catch (final IOException e) {
                            respStr = "Unable to process web service request.Please try again." + e;
                        } finally {
                            // clean up code
                            if (zout != null) {
                                zout.close();
                            }
                            if (out != null) {
                                out.flush();
                            }
                            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                        }
                    }
                }

            }
        } catch (Exception e) {
            respStr = "Internal Server error.Please check logs for further details." + e;
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        }
    } else {
        respStr = "Improper input to server. Expected multipart request. Returning without processing the results.";
    }
    if (!workingDir.isEmpty()) {
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    if (!respStr.isEmpty()) {
        try {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {

        }
    }
}