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:com.ephesoft.dcma.webservice.util.WebServiceHelper.java

/**
 * This method will return the number of files available in MultiValueMap for a particular extention
 * //from   w w  w .  jav  a 2  s.  c om
 * @param fileExtension {@link String} the extension of the file whose count is required
 * @param fileMap {@link MultiValueMap} the MultiValuemapMultiValueMap<String, MultipartFile>
 * @return count {@link int } the number of files present in the MultiValueMap
 */

private int checkFileCountForExtentionType(String fileExtension, MultiValueMap<String, MultipartFile> fileMap) {
    // TODO Auto-generated method stub
    LOGGER.info("Getting number of files present with speified file type in multi part request");
    int count = 0;
    if (fileExtension != null && !fileExtension.isEmpty() && !fileExtension.trim().equalsIgnoreCase("")
            && fileMap != null) {
        for (final String fileName : fileMap.keySet()) {
            if (fileName.toLowerCase().indexOf(FileType.XML.getExtension()) > -1) {
                count++;
            }
        }
    }
    return count;
}

From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

/**
 * To classify Barcode Image./*from   w ww . ja v a  2  s.c om*/
 * @param req {@link HttpServletRequest}
 * @param resp {@link HttpServletResponse}
 */
@RequestMapping(value = "/classifyBarcodeImage", method = RequestMethod.POST)
@ResponseBody
public void classifyBarcodeImage(final HttpServletRequest req, final HttpServletResponse resp) {
    LOGGER.info("Start processing web service for classifyBarcode.");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    InputStream instream = null;
    OutputStream outStream = null;
    if (req instanceof DefaultMultipartHttpServletRequest) {
        try {
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);

            final DefaultMultipartHttpServletRequest multipartReq = (DefaultMultipartHttpServletRequest) req;
            String batchClassId = WebServiceUtil.EMPTY_STRING;
            for (final Enumeration<String> params = multipartReq.getParameterNames(); params
                    .hasMoreElements();) {
                final String paramName = params.nextElement();
                if (paramName.equalsIgnoreCase("batchClassId")) {
                    batchClassId = multipartReq.getParameter(paramName);
                    break;
                }
            }
            Map<BarcodeProperties, String> batchClassConfigMap = new HashMap<BarcodeProperties, String>();

            if (batchClassId == null || batchClassId.isEmpty()) {
                respStr = "Batch Class identifier not specified.";
            } else {
                BatchClass batchClass = bcService.getBatchClassByIdentifier(batchClassId);
                if (batchClass == null) {
                    respStr = "Batch class with the specified identifier: " + batchClassId + " does not exist.";
                    LOGGER.error(SERVER_ERROR_MSG + respStr);
                } else {
                    Set<String> loggedInUserRole = getUserRoles(req);
                    if (!isBatchClassViewableToUser(batchClassId, loggedInUserRole, isSuperAdmin(req))) {
                        respStr = USER_NOT_AUTHORIZED_TO_VIEW_THE_BATCH_CLASS + batchClassId;
                        LOGGER.error(SERVER_ERROR_MSG + respStr);
                    } else {
                        BatchPlugin barcodeReader = batchClassPPService.getPluginProperties(batchClassId,
                                ICommonConstants.BARCODE_READER_PLUGIN);
                        BatchPlugin docAssemblyPlugin = batchClassPPService.getPluginProperties(batchClassId,
                                DocumentAssemblerConstants.DOCUMENT_ASSEMBLER_PLUGIN);
                        if (barcodeReader == null || docAssemblyPlugin == null) {
                            respStr = "Either Barcode Reader plugin or document assembly plugin does not exist for the specified batch class id: "
                                    + batchClassId;
                        } else if (docAssemblyPlugin.getPluginConfigurations(
                                DocumentAssemblerProperties.DA_BARCODE_CONFIDENCE) == null) {
                            respStr = "Incomplete properties of the Document assembler plugin for the specified batch class id:"
                                    + batchClassId;
                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                        } else if (barcodeReader
                                .getPluginConfigurations(BarcodeProperties.BARCODE_VALID_EXTNS) == null
                                || barcodeReader
                                        .getPluginConfigurations(BarcodeProperties.BARCODE_READER_TYPES) == null
                                || barcodeReader
                                        .getPluginConfigurations(BarcodeProperties.MAX_CONFIDENCE) == null
                                || barcodeReader
                                        .getPluginConfigurations(BarcodeProperties.MIN_CONFIDENCE) == null) {
                            respStr = "Incomplete properties of the Barcode reader plugin for the specified batch class id: "
                                    + batchClassId;
                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                        }
                    }
                }
            }
            if (respStr.isEmpty()) {
                batchClassConfigMap.put(BarcodeProperties.BARCODE_VALID_EXTNS,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.BARCODE_READER_PLUGIN, BarcodeProperties.BARCODE_VALID_EXTNS));
                batchClassConfigMap.put(BarcodeProperties.BARCODE_READER_TYPES,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.BARCODE_READER_PLUGIN,
                                BarcodeProperties.BARCODE_READER_TYPES));
                batchClassConfigMap.put(BarcodeProperties.MAX_CONFIDENCE,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.BARCODE_READER_PLUGIN, BarcodeProperties.MAX_CONFIDENCE));
                batchClassConfigMap.put(BarcodeProperties.MIN_CONFIDENCE,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.BARCODE_READER_PLUGIN, BarcodeProperties.MIN_CONFIDENCE));

                final MultiValueMap<String, MultipartFile> fileMap = multipartReq.getMultiFileMap();

                if (fileMap.size() == 1) {
                    String tiffFileName = WebServiceUtil.EMPTY_STRING;
                    for (final String fileName : fileMap.keySet()) {
                        // only single tiff/tif file is expected as input
                        try {
                            if ((fileName.toLowerCase(Locale.getDefault())
                                    .indexOf(FileType.TIF.getExtension()) > -1
                                    || fileName.toLowerCase(Locale.getDefault())
                                            .indexOf(FileType.TIFF.getExtension()) > -1)) {

                                final MultipartFile multiPartFile = multipartReq.getFile(fileName);
                                instream = multiPartFile.getInputStream();
                                final File file = new File(workingDir + File.separator + fileName);
                                outStream = new FileOutputStream(file);
                                final byte buf[] = new byte[WebserviceConstants.BUF];
                                int len = instream.read(buf);
                                while (len > 0) {
                                    outStream.write(buf, 0, len);
                                    len = instream.read(buf);
                                }

                                if (TIFFUtil.getTIFFPageCount(file.getAbsolutePath()) > 1) {
                                    respStr = ONLY_ONE_SINGLE_PAGE_TIFF_EXPECTED;
                                }
                                tiffFileName = file.getName();
                                break;
                            } else {
                                respStr = "Improper input to server. Expected only one tiff file. Returning without processing the results.";
                            }
                        } finally {
                            IOUtils.closeQuietly(instream);
                            IOUtils.closeQuietly(outStream);
                        }
                    }
                    if (respStr.isEmpty()) {
                        ObjectFactory objectFactory = new ObjectFactory();

                        Pages pages = new Pages();
                        List<Page> listOfPages = pages.getPage();
                        List<Document> xmlDocuments = new ArrayList<Document>();
                        Document doc = objectFactory.createDocument();
                        xmlDocuments.add(doc);
                        doc.setPages(pages);

                        Page pageType = objectFactory.createPage();
                        pageType.setIdentifier(EphesoftProperty.PAGE.getProperty() + "0");
                        pageType.setNewFileName(tiffFileName);
                        listOfPages.add(pageType);
                        String batchInstanceIdentifier = new File(workingDir).getName() + Math.random();
                        barcodeService.extractPageBarCodeAPI(xmlDocuments, batchInstanceIdentifier, workingDir,
                                batchClassConfigMap);

                        try {
                            // invoke the document assembler plugin
                            xmlDocuments = docAssembler.createDocumentAPI(DocumentClassificationFactory.BARCODE,
                                    batchClassId, listOfPages);
                            Documents docs = new Documents();
                            docs.getDocument().addAll(xmlDocuments);
                            StreamResult result;
                            try {
                                result = new StreamResult(resp.getOutputStream());
                                resp.setStatus(HttpServletResponse.SC_OK);
                                batchSchemaDao.getJAXB2Template().getJaxb2Marshaller().marshal(docs, result);
                            } catch (final IOException e) {
                                respStr = INTERNAL_SERVER_ERROR + e;
                                LOGGER.error(SERVER_ERROR_MSG + respStr);
                            }
                        } catch (final DCMAApplicationException e) {
                            respStr = "Error while executing plugin. Detailed exception is " + e;
                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                        }
                    }
                } else {
                    respStr = IMPROPER_INPUT_ONLY_ONE_HTML_FILE_EXPECTED;
                    LOGGER.error(SERVER_ERROR_MSG + respStr);
                }
            }
        } catch (final XmlMappingException xmle) {
            respStr = ERROR_IN_MAPPING_INPUT + xmle;
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final DCMAException dcmae) {
            respStr = ERROR_PROCESSING_REQUEST + dcmae;
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final Exception e) {
            respStr = INTERNAL_SERVER_ERROR + e;
            LOGGER.error(SERVER_ERROR_MSG + respStr);
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        }
    } else {
        respStr = "Improper input to server. Expected multipart request. Returing without processing the results.";
        LOGGER.error(SERVER_ERROR_MSG + respStr);
    }

    if (!workingDir.isEmpty()) {
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final IOException ioe) {
            LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe);
        }
    }
}

From source file:com.ephesoft.dcma.webservice.util.WebServiceHelper.java

/**
 * performs table extraction on the HOCR file provided ,accepts input xml with HOCR page and document type classification along
 * with HOCR pages on whuich extraction is to be performed
 * //from  w w w  .j  a  v a  2s .c om
 * @param req
 * @param resp
 * @return
 * @throws ValidationException
 * @throws InternalServerException
 */
public Batch.Documents processtableExtractionHOCR(final HttpServletRequest req, final HttpServletResponse resp)
        throws ValidationException, InternalServerException {
    LOGGER.info("Start processing web service for table extraction....");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String xmlFileName = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    Batch.Documents documents = null;
    InputStream instream = null;
    int responseCode = 0;
    if (req instanceof DefaultMultipartHttpServletRequest) {
        final String webServiceFolderPath = bsService.getWebServicesFolderPath();
        try {
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;
            final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();
            boolean isFileHOCR = false;
            boolean isFilePlainXML = false;
            if (fileMap.size() >= WebServiceConstants.MINIMUM_FILE_COUNT_FOR_TABLE_EXTRACTION) {
                for (final String inputFileName : fileMap.keySet()) {
                    try {
                        isFileHOCR = inputFileName.trim().endsWith(WebServiceConstants.HOCR_EXTENSION);
                        isFilePlainXML = inputFileName.toLowerCase()
                                .endsWith(FileType.XML.getExtensionWithDot());
                        if (!(isFileHOCR || isFilePlainXML)) {
                            respStr = WebServiceConstants.INVALID_FILES_TABLE_EXTRACTION;
                            responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
                            createAndThrowValidationException(null, responseCode, respStr);
                        }
                        if (!isFileHOCR) {
                            xmlFileName = inputFileName;
                        }
                        final MultipartFile multiPartFile = multiPartRequest.getFile(inputFileName);
                        instream = multiPartFile.getInputStream();
                        WebServiceUtil.copyFile(workingDir, inputFileName, instream);
                    } catch (FileNotFoundException fileNotFoundException) {
                        respStr = WebServiceConstants.ERROR;
                        responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE;
                    }
                }
                LOGGER.info("XML file name is" + xmlFileName);
                final File xmlFile = new File(
                        EphesoftStringUtil.concatenate(workingDir, File.separator, xmlFileName));
                final FileInputStream inputStream = new FileInputStream(xmlFile);
                final Source source = XMLUtil.createSourceFromStream(inputStream);
                String response = WebServiceUtil.EMPTY_STRING;
                ExtractTableParam extractTableParams = (ExtractTableParam) batchSchemaDao.getJAXB2Template()
                        .getJaxb2Marshaller().unmarshal(source);
                List<com.ephesoft.dcma.batch.schema.ExtractTableParam.Documents.Document> docList = extractTableParams
                        .getDocuments().getDocument();
                final String batchClassIdentifier = extractTableParams.getBatchClassId();
                Map<DocumentType, List<HocrPages>> documentHOCRMap = new HashMap<DocumentType, List<HocrPages>>();
                if (EphesoftStringUtil.isNullOrEmpty(batchClassIdentifier)) {
                    responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
                    respStr = WebServiceConstants.UNDEFINED_BATCH_IDENTIFIER;
                    createAndThrowValidationException(null, responseCode, respStr);
                }
                final BatchClass batchClass = bcService.getBatchClassByIdentifier(batchClassIdentifier);
                if (null == batchClass) {
                    response = WebServiceUtil.BATCH_NOT_EXISTS;
                }
                if (EphesoftStringUtil.isNullOrEmpty(response)) {
                    String tableExtractionSwitch = WebServiceConstants.EMPTY_STRING;
                    try {
                        tableExtractionSwitch = batchClassPPService.getPropertyValue(batchClassIdentifier,
                                WebServiceConstants.TABLE_EXTRACTION_PLUGIN,
                                TableExtractionProperties.TABLE_EXTRACTION_SWITCH);
                    } catch (NullPointerException nullPointerException) {
                        responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
                        respStr = EphesoftStringUtil.concatenate(
                                WebServiceConstants.UNDEFINED_TABLE_EXTRACTION_SWITCH, batchClassIdentifier);
                        createAndThrowConfigurationException(responseCode, respStr);
                    }
                    if (WebServiceUtil.OFF_STRING.equals(tableExtractionSwitch)) {
                        respStr = EphesoftStringUtil.concatenate(
                                WebServiceConstants.TABLE_EXTRACCTION_SWITCH_OFF_MESSAGE, batchClassIdentifier);
                        responseCode = WebServiceConstants.TABLE_EXTRACTION_SWITCH_OFF_CODE;
                        createAndThrowConfigurationException(responseCode, respStr);
                    }
                    final List<DocumentType> docTypeList = batchClass.getDocumentTypes();
                    List<String> docTypesName = obtainDocumentNameList(docTypeList);
                    documentHOCRMap = generateDocumentMapHOCR(docList, workingDir, docTypesName,
                            batchClassIdentifier);
                    if (documentHOCRMap.isEmpty()) {
                        respStr = WebServiceConstants.INVALID_MAPPING_DOCUMENT_HOCR_PAGES;
                        responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
                        createAndThrowValidationException(null, responseCode, respStr);
                    }
                    final int gapBetweenColumnWords = tableFinderService.getGapBetweenColumnWords();
                    documents = tableExtraction.processDocPageForTableExtractionWebService(
                            gapBetweenColumnWords, documentHOCRMap, docTypeList, docTypesName);
                } else {
                    respStr = response;
                    responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
                    createAndThrowValidationException(null, responseCode, respStr);
                }

            } else {
                respStr = WebServiceConstants.TABLE_EXTRACTION_MINIMUM_PARAMETERS_REQUIRED_ERROR_MESSAGE;
                responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
                createAndThrowValidationException(null, responseCode, respStr);
            }
        } catch (ClassCastException classCastException) {
            LOGGER.error(EphesoftStringUtil.concatenate("Not an Object of extract table Params",
                    classCastException.getMessage()));
            respStr = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_MESSAGE;
            responseCode = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_CODE;
        } catch (DCMABusinessException dcmaBusinessException) {
            LOGGER.error(EphesoftStringUtil.concatenate("Invalid HOCR xml file uploaded",
                    dcmaBusinessException.getMessage()));
            respStr = WebServiceConstants.INVALID_HOCR_FILE_UPLOAD_MESSAGE;
            responseCode = WebServiceConstants.INVALID_HOCR_FILE_UPLOADED_CODE;
        } catch (org.springframework.oxm.UnmarshallingFailureException unmarshallingFailureException) {
            LOGGER.error(EphesoftStringUtil.concatenate("Not an Object of extract table Params",
                    unmarshallingFailureException.getMessage()));
            respStr = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_MESSAGE;
            responseCode = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_CODE;
        } catch (Exception exception) {
            LOGGER.error(EphesoftStringUtil.concatenate("Error generated is ", exception.getMessage()));
            if (EphesoftStringUtil.isNullOrEmpty(respStr)) {
                respStr = WebServiceConstants.INVALID_MULTIPART_REQUEST;
                responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE;
            }
        } finally {
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        }
    } else {
        if (EphesoftStringUtil.isNullOrEmpty(respStr)) {
            respStr = WebServiceConstants.INVALID_MULTIPART_REQUEST;
            responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE;
        }
    }
    validateResponse(responseCode, respStr);
    return documents;
}

From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

/**
 * To classify Hocr.//ww  w . j  a v a 2 s.  co m
 * @param req {@link HttpServletRequest}
 * @param resp {@link HttpServletResponse}
 */
@RequestMapping(value = "/classifyHocr", method = RequestMethod.POST)
@ResponseBody
public void classifyHocr(final HttpServletRequest req, final HttpServletResponse resp) {
    LOGGER.info("Start processing web service for classifyHocr.");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    InputStream instream = null;
    OutputStream outStream = null;
    if (req instanceof DefaultMultipartHttpServletRequest) {
        try {
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);

            final DefaultMultipartHttpServletRequest multipartReq = (DefaultMultipartHttpServletRequest) req;
            String batchClassId = WebServiceUtil.EMPTY_STRING;
            for (final Enumeration<String> params = multipartReq.getParameterNames(); params
                    .hasMoreElements();) {
                final String paramName = params.nextElement();
                if (paramName.equalsIgnoreCase("batchClassId")) {
                    batchClassId = multipartReq.getParameter(paramName);
                    break;
                }
            }
            Map<LuceneProperties, String> batchClassConfigMap = new HashMap<LuceneProperties, String>();

            if (batchClassId == null || batchClassId.isEmpty()) {
                respStr = "Batch Class identifier not specified.";
                LOGGER.error(SERVER_ERROR_MSG + respStr);
            } else {
                BatchClass batchClass = bcService.getBatchClassByIdentifier(batchClassId);
                if (batchClass == null) {
                    respStr = "Batch class with the specified identifier : " + batchClassId
                            + " does not exist.";
                    LOGGER.error(SERVER_ERROR_MSG + respStr);
                } else {
                    Set<String> loggedInUserRole = getUserRoles(req);
                    if (!isBatchClassViewableToUser(batchClassId, loggedInUserRole, isSuperAdmin(req))) {
                        respStr = USER_NOT_AUTHORIZED_TO_VIEW_THE_BATCH_CLASS + batchClassId;
                        LOGGER.error(SERVER_ERROR_MSG + respStr);
                    } else {
                        BatchPlugin searchClassPlugin = batchClassPPService.getPluginProperties(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN);
                        BatchPlugin docAssemblyPlugin = batchClassPPService.getPluginProperties(batchClassId,
                                DocumentAssemblerConstants.DOCUMENT_ASSEMBLER_PLUGIN);
                        if (searchClassPlugin == null || docAssemblyPlugin == null) {
                            respStr = "Either Search Classification plugin or document assembly plugin does not exist for the specified batch class id: "
                                    + batchClassId;
                        } else if (docAssemblyPlugin
                                .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_FP_MP_LP) == null
                                || docAssemblyPlugin
                                        .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_FP) == null
                                || docAssemblyPlugin
                                        .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_MP) == null
                                || docAssemblyPlugin
                                        .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_LP) == null
                                || docAssemblyPlugin.getPluginConfigurations(
                                        DocumentAssemblerProperties.DA_RULE_FP_LP) == null
                                || docAssemblyPlugin.getPluginConfigurations(
                                        DocumentAssemblerProperties.DA_RULE_FP_MP) == null
                                || docAssemblyPlugin.getPluginConfigurations(
                                        DocumentAssemblerProperties.DA_RULE_MP_LP) == null) {
                            respStr = "Incomplete properties of the Document assembler plugin for the specified batch class id :"
                                    + batchClassId;
                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                        } else if (searchClassPlugin
                                .getPluginConfigurations(LuceneProperties.LUCENE_VALID_EXTNS) == null
                                || searchClassPlugin
                                        .getPluginConfigurations(LuceneProperties.LUCENE_INDEX_FIELDS) == null
                                || searchClassPlugin
                                        .getPluginConfigurations(LuceneProperties.LUCENE_STOP_WORDS) == null
                                || searchClassPlugin
                                        .getPluginConfigurations(LuceneProperties.LUCENE_MIN_TERM_FREQ) == null
                                || searchClassPlugin
                                        .getPluginConfigurations(LuceneProperties.LUCENE_MIN_DOC_FREQ) == null
                                || searchClassPlugin.getPluginConfigurations(
                                        LuceneProperties.LUCENE_MIN_WORD_LENGTH) == null
                                || searchClassPlugin.getPluginConfigurations(
                                        LuceneProperties.LUCENE_MAX_QUERY_TERMS) == null
                                || searchClassPlugin.getPluginConfigurations(
                                        LuceneProperties.LUCENE_TOP_LEVEL_FIELD) == null
                                || searchClassPlugin
                                        .getPluginConfigurations(LuceneProperties.LUCENE_NO_OF_PAGES) == null
                                || searchClassPlugin.getPluginConfigurations(
                                        LuceneProperties.LUCENE_MAX_RESULT_COUNT) == null
                                || searchClassPlugin.getPluginConfigurations(
                                        LuceneProperties.LUCENE_FIRST_PAGE_CONF_WEIGHTAGE) == null
                                || searchClassPlugin.getPluginConfigurations(
                                        LuceneProperties.LUCENE_MIDDLE_PAGE_CONF_WEIGHTAGE) == null
                                || searchClassPlugin.getPluginConfigurations(
                                        LuceneProperties.LUCENE_LAST_PAGE_CONF_WEIGHTAGE) == null) {
                            respStr = "Incomplete properties of the Search Classification plugin for the specified batch class id :"
                                    + batchClassId;
                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                        }
                    }
                }
            }
            if (respStr.isEmpty()) {
                batchClassConfigMap.put(LuceneProperties.LUCENE_VALID_EXTNS,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_VALID_EXTNS));
                batchClassConfigMap.put(LuceneProperties.LUCENE_INDEX_FIELDS,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_INDEX_FIELDS));
                batchClassConfigMap.put(LuceneProperties.LUCENE_STOP_WORDS,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_STOP_WORDS));
                batchClassConfigMap.put(LuceneProperties.LUCENE_MIN_TERM_FREQ,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_MIN_TERM_FREQ));
                batchClassConfigMap.put(LuceneProperties.LUCENE_MIN_DOC_FREQ,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_MIN_DOC_FREQ));
                batchClassConfigMap.put(LuceneProperties.LUCENE_MIN_WORD_LENGTH,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_MIN_WORD_LENGTH));
                batchClassConfigMap.put(LuceneProperties.LUCENE_MAX_QUERY_TERMS,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_MAX_QUERY_TERMS));
                batchClassConfigMap.put(LuceneProperties.LUCENE_TOP_LEVEL_FIELD,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_TOP_LEVEL_FIELD));
                batchClassConfigMap.put(LuceneProperties.LUCENE_NO_OF_PAGES,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_NO_OF_PAGES));
                batchClassConfigMap.put(LuceneProperties.LUCENE_MAX_RESULT_COUNT,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_MAX_RESULT_COUNT));
                batchClassConfigMap.put(LuceneProperties.LUCENE_FIRST_PAGE_CONF_WEIGHTAGE,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_FIRST_PAGE_CONF_WEIGHTAGE));
                batchClassConfigMap.put(LuceneProperties.LUCENE_MIDDLE_PAGE_CONF_WEIGHTAGE,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_MIDDLE_PAGE_CONF_WEIGHTAGE));
                batchClassConfigMap.put(LuceneProperties.LUCENE_LAST_PAGE_CONF_WEIGHTAGE,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_LAST_PAGE_CONF_WEIGHTAGE));

                final MultiValueMap<String, MultipartFile> fileMap = multipartReq.getMultiFileMap();

                if (fileMap.size() == 1) {
                    String hocrFileName = "";
                    for (final String fileName : fileMap.keySet()) {
                        // only single html file is expected as input
                        try {
                            if (fileName.toLowerCase(Locale.getDefault())
                                    .indexOf(FileType.HTML.getExtension()) > -1) {
                                // only HTML file is expected
                                hocrFileName = fileName;
                                final MultipartFile multiPartFile = multipartReq.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 = instream.read(buf);
                                while (len > 0) {
                                    outStream.write(buf, 0, len);
                                    len = instream.read(buf);
                                }

                                break;
                            } else {
                                respStr = IMPROPER_INPUT_ONLY_ONE_HTML_FILE_EXPECTED;
                                LOGGER.error(SERVER_ERROR_MSG + respStr);
                            }
                        } finally {
                            IOUtils.closeQuietly(instream);
                            IOUtils.closeQuietly(outStream);
                        }
                    }
                    if (respStr.isEmpty()) {
                        ObjectFactory objectFactory = new ObjectFactory();

                        Pages pages = new Pages();
                        List<Page> listOfPages = pages.getPage();
                        List<Document> xmlDocuments = new ArrayList<Document>();
                        Document doc = objectFactory.createDocument();
                        xmlDocuments.add(doc);
                        doc.setPages(pages);
                        String fileName = workingDir + File.separator + hocrFileName;

                        // generate hocr file from html file.
                        HocrPages hocrPages = new HocrPages();
                        List<HocrPage> hocrPageList = hocrPages.getHocrPage();
                        HocrPage hocrPage = new HocrPage();
                        String pageID = WebServiceUtil.PG0;
                        hocrPage.setPageID(pageID);
                        hocrPageList.add(hocrPage);
                        bsService.hocrGenerationAPI(workingDir, WebServiceUtil.PG0, fileName, hocrPage);

                        Page pageType = objectFactory.createPage();
                        pageType.setIdentifier(EphesoftProperty.PAGE.getProperty() + "0");
                        pageType.setHocrFileName(hocrFileName);
                        listOfPages.add(pageType);
                        scService.generateConfidenceScoreAPI(xmlDocuments, hocrPages, workingDir,
                                batchClassConfigMap, batchClassId);

                        try {
                            // invoke the document assembler plugin
                            xmlDocuments = docAssembler.createDocumentAPI(
                                    DocumentClassificationFactory.SEARCHCLASSIFICATION, batchClassId,
                                    listOfPages);
                            Documents docs = new Documents();
                            docs.getDocument().addAll(xmlDocuments);
                            StreamResult result;
                            try {
                                result = new StreamResult(resp.getOutputStream());
                                resp.setStatus(HttpServletResponse.SC_OK);
                                batchSchemaDao.getJAXB2Template().getJaxb2Marshaller().marshal(docs, result);
                            } catch (final IOException e) {
                                respStr = INTERNAL_SERVER_ERROR + e;
                                LOGGER.error(SERVER_ERROR_MSG + respStr);
                            }
                        } catch (final DCMAApplicationException e) {
                            respStr = "Error while executing plugin. Detailed exception is " + e;
                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                        }
                    }
                } else {
                    respStr = IMPROPER_INPUT_ONLY_ONE_HTML_FILE_EXPECTED;
                    LOGGER.error(SERVER_ERROR_MSG + respStr);
                }
            }
        } catch (final XmlMappingException xmle) {
            respStr = ERROR_IN_MAPPING_INPUT + xmle;
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final DCMAException dcmae) {
            respStr = ERROR_PROCESSING_REQUEST + dcmae;
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final Exception e) {
            respStr = INTERNAL_SERVER_ERROR + e;
            LOGGER.error(SERVER_ERROR_MSG + respStr);
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }

        }
    } else {
        respStr = "Improper input to server. Expected multipart request. Returing without processing the results.";
        LOGGER.error(SERVER_ERROR_MSG + respStr);
    }

    if (!workingDir.isEmpty()) {
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final IOException ioe) {
            LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe);
        }
    }
}

From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

/**
 * To classify Multi Page Hocr./*from   w w w .j  a v  a 2 s. com*/
 * @param req {@link HttpServletRequest}
 * @param resp {@link HttpServletResponse}
 */
@RequestMapping(value = "/classifyMultiPageHocr", method = RequestMethod.POST)
@ResponseBody
public void classifyMultiPageHocr(final HttpServletRequest req, final HttpServletResponse resp) {
    LOGGER.info("Start processing web service for classifyHocr.");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    InputStream instream = null;
    OutputStream outStream = null;
    if (req instanceof DefaultMultipartHttpServletRequest) {
        try {
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);

            final DefaultMultipartHttpServletRequest multipartReq = (DefaultMultipartHttpServletRequest) req;
            String batchClassId = WebServiceUtil.EMPTY_STRING;
            for (final Enumeration<String> params = multipartReq.getParameterNames(); params
                    .hasMoreElements();) {
                final String paramName = params.nextElement();
                if (paramName.equalsIgnoreCase("batchClassId")) {
                    batchClassId = multipartReq.getParameter(paramName);
                    break;
                }
            }
            Map<LuceneProperties, String> batchClassConfigMap = new HashMap<LuceneProperties, String>();

            if (batchClassId == null || batchClassId.isEmpty()) {
                respStr = "Batch Class identifier not specified.";
                LOGGER.error("Error response at server:" + respStr);
            } else {
                BatchClass bc = bcService.getBatchClassByIdentifier(batchClassId);
                if (bc == null) {
                    respStr = "Batch class with the specified identifier : " + batchClassId
                            + " does not exist.";
                    LOGGER.error("Error response at server:" + respStr);
                } else {
                    Set<String> loggedInUserRole = getUserRoles(req);
                    if (!isBatchClassViewableToUser(batchClassId, loggedInUserRole, isSuperAdmin(req))) {
                        respStr = "User is not authorized to view the batch class for given identifier:"
                                + batchClassId;
                        LOGGER.error("Error response at server:" + respStr);
                    } else {
                        BatchPlugin searchClassPlugin = batchClassPPService.getPluginProperties(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN);
                        BatchPlugin docAssemblyPlugin = batchClassPPService.getPluginProperties(batchClassId,
                                DocumentAssemblerConstants.DOCUMENT_ASSEMBLER_PLUGIN);
                        if (searchClassPlugin == null || docAssemblyPlugin == null) {
                            respStr = "Either Search Classification plugin or document assembly plugin does not exist for the specified batch class id: "
                                    + batchClassId;
                        } else if (docAssemblyPlugin
                                .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_FP_MP_LP) == null
                                || docAssemblyPlugin
                                        .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_FP) == null
                                || docAssemblyPlugin
                                        .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_MP) == null
                                || docAssemblyPlugin
                                        .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_LP) == null
                                || docAssemblyPlugin.getPluginConfigurations(
                                        DocumentAssemblerProperties.DA_RULE_FP_LP) == null
                                || docAssemblyPlugin.getPluginConfigurations(
                                        DocumentAssemblerProperties.DA_RULE_FP_MP) == null
                                || docAssemblyPlugin.getPluginConfigurations(
                                        DocumentAssemblerProperties.DA_RULE_MP_LP) == null) {
                            respStr = "Incomplete properties of the Document assembler plugin for the specified batch class id :"
                                    + batchClassId;
                            LOGGER.error("Error response at server:" + respStr);
                        } else if (searchClassPlugin
                                .getPluginConfigurations(LuceneProperties.LUCENE_VALID_EXTNS) == null
                                || searchClassPlugin
                                        .getPluginConfigurations(LuceneProperties.LUCENE_INDEX_FIELDS) == null
                                || searchClassPlugin
                                        .getPluginConfigurations(LuceneProperties.LUCENE_STOP_WORDS) == null
                                || searchClassPlugin
                                        .getPluginConfigurations(LuceneProperties.LUCENE_MIN_TERM_FREQ) == null
                                || searchClassPlugin
                                        .getPluginConfigurations(LuceneProperties.LUCENE_MIN_DOC_FREQ) == null
                                || searchClassPlugin.getPluginConfigurations(
                                        LuceneProperties.LUCENE_MIN_WORD_LENGTH) == null
                                || searchClassPlugin.getPluginConfigurations(
                                        LuceneProperties.LUCENE_MAX_QUERY_TERMS) == null
                                || searchClassPlugin.getPluginConfigurations(
                                        LuceneProperties.LUCENE_TOP_LEVEL_FIELD) == null
                                || searchClassPlugin
                                        .getPluginConfigurations(LuceneProperties.LUCENE_NO_OF_PAGES) == null
                                || searchClassPlugin.getPluginConfigurations(
                                        LuceneProperties.LUCENE_MAX_RESULT_COUNT) == null
                                || searchClassPlugin.getPluginConfigurations(
                                        LuceneProperties.LUCENE_FIRST_PAGE_CONF_WEIGHTAGE) == null
                                || searchClassPlugin.getPluginConfigurations(
                                        LuceneProperties.LUCENE_MIDDLE_PAGE_CONF_WEIGHTAGE) == null
                                || searchClassPlugin.getPluginConfigurations(
                                        LuceneProperties.LUCENE_LAST_PAGE_CONF_WEIGHTAGE) == null) {
                            respStr = "Incomplete properties of the Search Classification plugin for the specified batch class id :"
                                    + batchClassId;
                            LOGGER.error("Error response at server:" + respStr);
                        }
                    }
                }
            }
            if (respStr.isEmpty()) {
                batchClassConfigMap.put(LuceneProperties.LUCENE_VALID_EXTNS,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_VALID_EXTNS));
                batchClassConfigMap.put(LuceneProperties.LUCENE_INDEX_FIELDS,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_INDEX_FIELDS));
                batchClassConfigMap.put(LuceneProperties.LUCENE_STOP_WORDS,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_STOP_WORDS));
                batchClassConfigMap.put(LuceneProperties.LUCENE_MIN_TERM_FREQ,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_MIN_TERM_FREQ));
                batchClassConfigMap.put(LuceneProperties.LUCENE_MIN_DOC_FREQ,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_MIN_DOC_FREQ));
                batchClassConfigMap.put(LuceneProperties.LUCENE_MIN_WORD_LENGTH,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_MIN_WORD_LENGTH));
                batchClassConfigMap.put(LuceneProperties.LUCENE_MAX_QUERY_TERMS,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_MAX_QUERY_TERMS));
                batchClassConfigMap.put(LuceneProperties.LUCENE_TOP_LEVEL_FIELD,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_TOP_LEVEL_FIELD));
                batchClassConfigMap.put(LuceneProperties.LUCENE_NO_OF_PAGES,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_NO_OF_PAGES));
                batchClassConfigMap.put(LuceneProperties.LUCENE_MAX_RESULT_COUNT,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_MAX_RESULT_COUNT));
                batchClassConfigMap.put(LuceneProperties.LUCENE_FIRST_PAGE_CONF_WEIGHTAGE,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_FIRST_PAGE_CONF_WEIGHTAGE));
                batchClassConfigMap.put(LuceneProperties.LUCENE_MIDDLE_PAGE_CONF_WEIGHTAGE,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_MIDDLE_PAGE_CONF_WEIGHTAGE));
                batchClassConfigMap.put(LuceneProperties.LUCENE_LAST_PAGE_CONF_WEIGHTAGE,
                        batchClassPPService.getPropertyValue(batchClassId,
                                ICommonConstants.SEARCH_CLASSIFICATION_PLUGIN,
                                LuceneProperties.LUCENE_LAST_PAGE_CONF_WEIGHTAGE));

                final MultiValueMap<String, MultipartFile> fileMap = multipartReq.getMultiFileMap();

                if (fileMap.size() == 1) {
                    String path = "";
                    for (final String fileName : fileMap.keySet()) {
                        // only single zip file is expected as input containing multiple HTML files.
                        try {
                            boolean isZipContent = multipartReq.getFile(fileName).getContentType().toLowerCase()
                                    .contains(APPLICATION_ZIP);
                            if (fileName.toLowerCase()
                                    .indexOf(FileType.ZIP.getExtension()) > -WebserviceConstants.ONE
                                    || isZipContent) {
                                // only HTML file is expected
                                final MultipartFile f = multipartReq.getFile(fileName);
                                instream = f.getInputStream();
                                path = workingDir + File.separator + fileName;
                                if (isZipContent
                                        && !fileName.toLowerCase().endsWith(FileType.ZIP.getExtension())) {
                                    path = workingDir + File.separator + fileName
                                            + FileType.ZIP.getExtensionWithDot();
                                }
                                final File file = new File(path);
                                outStream = new FileOutputStream(file);
                                final byte buf[] = new byte[WebServiceUtil.bufferSize];
                                int len;
                                while ((len = instream.read(buf)) > WebserviceConstants.ZERO) {
                                    outStream.write(buf, 0, len);
                                }
                                break;
                            } else {
                                respStr = "Improper input to server. Expected only one zip file. Returning without processing the results.";
                                LOGGER.error("Error response at server:" + respStr);
                            }
                        } finally {
                            IOUtils.closeQuietly(instream);
                            IOUtils.closeQuietly(outStream);
                        }
                    }
                    if (respStr.isEmpty()) {
                        zipService.unzipFiles(new File(path), workingDir);
                        CustomFileFilter filter = new CustomFileFilter(false, FileType.HTML.getExtension());
                        String htmlFileList[] = new File(workingDir).list(filter);
                        if (htmlFileList != null && htmlFileList.length > WebserviceConstants.ZERO) {
                            ObjectFactory objectFactory = new ObjectFactory();
                            List<Document> xmlDocuments = new ArrayList<Document>();
                            HocrPages hocrPages = new HocrPages();
                            Pages pages = new Pages();
                            List<Page> listOfPages = pages.getPage();
                            Document doc = objectFactory.createDocument();
                            xmlDocuments.add(doc);
                            doc.setPages(pages);

                            for (int index = 0; index < htmlFileList.length; index++) {
                                // generate hocr file from html file.
                                String htmlFile = htmlFileList[index];
                                String htmlFilePath = workingDir + File.separator + htmlFile;
                                HocrPage hocrPage = new HocrPage();
                                List<HocrPage> hocrPageList = hocrPages.getHocrPage();
                                String pageID = PG_IDENTIFIER + index;
                                hocrPage.setPageID(pageID);
                                hocrPageList.add(hocrPage);
                                bsService.hocrGenerationAPI(workingDir, pageID, htmlFilePath, hocrPage);

                                Page pageType = objectFactory.createPage();
                                pageType.setIdentifier(EphesoftProperty.PAGE.getProperty() + index);
                                pageType.setHocrFileName(htmlFile);
                                listOfPages.add(pageType);
                            }

                            scService.generateConfidenceScoreAPI(xmlDocuments, hocrPages, workingDir,
                                    batchClassConfigMap, batchClassId);

                            try {
                                // invoke the document assembler plugin
                                xmlDocuments = docAssembler.createDocumentAPI(
                                        DocumentClassificationFactory.SEARCHCLASSIFICATION, batchClassId,
                                        listOfPages);
                                Documents docs = new Documents();
                                docs.getDocument().addAll(xmlDocuments);
                                StreamResult result;
                                try {
                                    result = new StreamResult(resp.getOutputStream());
                                    resp.setStatus(HttpServletResponse.SC_OK);
                                    batchSchemaDao.getJAXB2Template().getJaxb2Marshaller().marshal(docs,
                                            result);
                                } catch (final IOException e) {
                                    respStr = INTERNAL_SERVER_ERROR + e;
                                    LOGGER.error("Error response at server:" + respStr);
                                }
                            } catch (final DCMAApplicationException e) {
                                respStr = "Error while executing plugin. Detailed exception is " + e;
                                LOGGER.error("Error response at server:" + respStr);
                            }
                        } else {
                            respStr = "Improper input to server. Expected HTML file inside zip file.";
                            LOGGER.error("Error response at server:" + respStr);
                        }
                    }
                } else {
                    respStr = "Improper input to server. Expected only one zip file. Returning without processing the results.";
                    LOGGER.error("Error response at server:" + respStr);
                }
            }
        } 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;
            LOGGER.error("Error response at server:" + respStr);
        } catch (final DCMAException dcmae) {
            respStr = "Error in processing request. Detailed exception is " + dcmae;
            LOGGER.error("Error response at server:" + respStr);
        } catch (final Exception e) {
            respStr = INTERNAL_SERVER_ERROR + e;
            LOGGER.error("Error response at server:" + respStr);
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        }
    } else {
        respStr = "Improper input to server. Expected multipart request. Returing without processing the results.";
        LOGGER.error("Error response at server:" + respStr);
    }

    if (!workingDir.isEmpty()) {
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
            LOGGER.error("Error response at server:" + respStr);
        } catch (final IOException ioe) {
            LOGGER.info(
                    "Exception in sending the error code to client. Logged the exception for debugging:" + ioe,
                    ioe);
        }
    }
}

From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

/**
 * To classify Image.// w w  w  .j  a v  a  2s.c  o  m
 * @param req {@link HttpServletRequest}
 * @param resp {@link HttpServletResponse}
 */
@RequestMapping(value = "/classifyImage", method = RequestMethod.POST)
@ResponseBody
public void classifyImage(final HttpServletRequest req, final HttpServletResponse resp) {
    LOGGER.info("Start processing web service for classifyImage.");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    InputStream instream = null;
    OutputStream outStream = null;
    if (req instanceof DefaultMultipartHttpServletRequest) {
        try {
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);

            final DefaultMultipartHttpServletRequest multipartReq = (DefaultMultipartHttpServletRequest) req;
            String batchClassId = WebServiceUtil.EMPTY_STRING;
            for (final Enumeration<String> params = multipartReq.getParameterNames(); params
                    .hasMoreElements();) {
                final String paramName = params.nextElement();
                if (paramName.equalsIgnoreCase("batchClassId")) {
                    batchClassId = multipartReq.getParameter(paramName);
                    break;
                }
            }

            if (batchClassId == null || batchClassId.isEmpty()) {
                respStr = "Batch Class identifier not specified.";
            } else {

                BatchClass batchClass = bcService.getBatchClassByIdentifier(batchClassId);
                if (batchClass == null) {
                    respStr = "Batch class with the specified identifier:" + batchClassId + " does not exist.";
                    LOGGER.error(SERVER_ERROR_MSG + respStr);
                } else {
                    Set<String> loggedInUserRole = getUserRoles(req);
                    if (!isBatchClassViewableToUser(batchClassId, loggedInUserRole, isSuperAdmin(req))) {
                        respStr = USER_NOT_AUTHORIZED_TO_VIEW_THE_BATCH_CLASS + batchClassId;
                        LOGGER.error(SERVER_ERROR_MSG + respStr);
                    } else {
                        BatchPlugin createThumbPlugin = batchClassPPService.getPluginProperties(batchClassId,
                                ImageMagicKConstants.CREATE_THUMBNAILS_PLUGIN);
                        BatchPlugin classifyImgPlugin = batchClassPPService.getPluginProperties(batchClassId,
                                ImageMagicKConstants.CLASSIFY_IMAGES_PLUGIN);
                        BatchPlugin docAssemblyPlugin = batchClassPPService.getPluginProperties(batchClassId,
                                DocumentAssemblerConstants.DOCUMENT_ASSEMBLER_PLUGIN);
                        if (createThumbPlugin == null || classifyImgPlugin == null
                                || docAssemblyPlugin == null) {
                            respStr = "Either create Thumbnails plugin or Classify Image plugin or document assembly plugin does not exist for the specified batch class id: "
                                    + batchClassId;
                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                        } else if (createThumbPlugin.getPluginConfigurations(
                                ImageMagicProperties.CREATE_THUMBNAILS_OUTPUT_IMAGE_PARAMETERS) == null
                                || createThumbPlugin.getPluginConfigurations(
                                        ImageMagicProperties.CREATE_THUMBNAILS_COMP_THUMB_WIDTH) == null
                                || createThumbPlugin.getPluginConfigurations(
                                        ImageMagicProperties.CREATE_THUMBNAILS_COMP_THUMB_HEIGHT) == null) {
                            respStr = "Create Thumbnails Height or width or output image parameters does not exist for the specified batch class id: "
                                    + batchClassId;
                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                        } else if (classifyImgPlugin.getPluginConfigurations(
                                ImageMagicProperties.CLASSIFY_IMAGES_COMP_METRIC) == null
                                || classifyImgPlugin.getPluginConfigurations(
                                        ImageMagicProperties.CLASSIFY_IMAGES_MAX_RESULTS) == null
                                || classifyImgPlugin.getPluginConfigurations(
                                        ImageMagicProperties.CLASSIFY_IMAGES_FUZZ_PERCNT) == null) {
                            respStr = "Classify Images comp metric or fuzz percent or max results does not exist for the specified batch class id: "
                                    + batchClassId;
                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                        } else if (docAssemblyPlugin
                                .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_FP_MP_LP) == null
                                || docAssemblyPlugin
                                        .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_FP) == null
                                || docAssemblyPlugin
                                        .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_MP) == null
                                || docAssemblyPlugin
                                        .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_LP) == null
                                || docAssemblyPlugin.getPluginConfigurations(
                                        DocumentAssemblerProperties.DA_RULE_FP_LP) == null
                                || docAssemblyPlugin.getPluginConfigurations(
                                        DocumentAssemblerProperties.DA_RULE_FP_MP) == null
                                || docAssemblyPlugin.getPluginConfigurations(
                                        DocumentAssemblerProperties.DA_RULE_MP_LP) == null) {
                            respStr = "Incomplete properties of the Document assembler plugin for the specified batch class id: "
                                    + batchClassId;
                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                        }
                    }
                }
            }
            if (respStr.isEmpty()) {

                final String outputParams = batchClassPPService.getPropertyValue(batchClassId,
                        ImageMagicKConstants.CREATE_THUMBNAILS_PLUGIN,
                        ImageMagicProperties.CREATE_THUMBNAILS_OUTPUT_IMAGE_PARAMETERS);

                final MultiValueMap<String, MultipartFile> fileMap = multipartReq.getMultiFileMap();

                if (fileMap.size() == 1) {
                    String[][] sListOfTiffFiles = new String[fileMap.size()][WebserviceConstants.THREE];
                    for (final String fileName : fileMap.keySet()) {
                        // only single tiff file is expected as input
                        try {
                            if ((fileName.toLowerCase(Locale.getDefault())
                                    .indexOf(FileType.TIF.getExtension()) > -1
                                    || fileName.toLowerCase(Locale.getDefault())
                                            .indexOf(FileType.TIFF.getExtension()) > -1)) {

                                final MultipartFile multipartFile = multipartReq.getFile(fileName);
                                instream = multipartFile.getInputStream();
                                final File file = new File(workingDir + File.separator + fileName);
                                outStream = new FileOutputStream(file);
                                final byte buf[] = new byte[WebserviceConstants.BUF];
                                int len = instream.read(buf);
                                while (len > WebserviceConstants.ZERO) {
                                    outStream.write(buf, 0, len);
                                    len = instream.read(buf);
                                }

                                if (TIFFUtil
                                        .getTIFFPageCount(file.getAbsolutePath()) > WebserviceConstants.ONE) {
                                    respStr = ONLY_ONE_SINGLE_PAGE_TIFF_EXPECTED;
                                }
                                break;
                            } else {
                                respStr = "Improper input to server. Expected only one tiff file. Returning without processing the results.";
                            }
                        } finally {
                            IOUtils.closeQuietly(instream);
                            IOUtils.closeQuietly(outStream);
                        }
                    }
                    if (respStr.isEmpty()) {
                        String compareThumbnailH = batchClassPPService.getPropertyValue(batchClassId,
                                ImageMagicKConstants.CREATE_THUMBNAILS_PLUGIN,
                                ImageMagicProperties.CREATE_THUMBNAILS_COMP_THUMB_HEIGHT);
                        String compareThumbnailW = batchClassPPService.getPropertyValue(batchClassId,
                                ImageMagicKConstants.CREATE_THUMBNAILS_PLUGIN,
                                ImageMagicProperties.CREATE_THUMBNAILS_COMP_THUMB_WIDTH);

                        String batchId = new File(workingDir).getName() + Math.random();
                        ObjectFactory objectFactory = new ObjectFactory();
                        Pages pages = new Pages();
                        List<Page> listOfPages = pages.getPage();
                        String[] imageFiles = new File(workingDir).list(new CustomFileFilter(false,
                                FileType.TIFF.getExtensionWithDot(), FileType.TIF.getExtensionWithDot()));
                        for (int i = 0; i < imageFiles.length; i++) {
                            String fileName = workingDir + File.separator + imageFiles[i];
                            String thumbFileName = "th" + FileType.TIF.getExtensionWithDot();
                            String fileTiffPath = workingDir + File.separator + thumbFileName;
                            sListOfTiffFiles[i][0] = fileName;
                            sListOfTiffFiles[i][1] = fileTiffPath;
                            sListOfTiffFiles[i][2] = Integer.toString(i);

                            Page pageType = objectFactory.createPage();
                            pageType.setIdentifier(EphesoftProperty.PAGE.getProperty() + i);
                            pageType.setNewFileName(fileName);
                            pageType.setOldFileName(fileName);
                            pageType.setDirection(Direction.NORTH);
                            pageType.setIsRotated(false);
                            pageType.setComparisonThumbnailFileName(thumbFileName);
                            listOfPages.add(pageType);
                        }

                        final BatchInstanceThread threadList = imService.createCompThumbForImage(batchId,
                                workingDir, sListOfTiffFiles, outputParams, compareThumbnailH,
                                compareThumbnailW);

                        try {
                            threadList.execute();
                            // invoke the Classification Image plugin
                            String imMetric = batchClassPPService.getPropertyValue(batchClassId,
                                    ImageMagicKConstants.CLASSIFY_IMAGES_PLUGIN,
                                    ImageMagicProperties.CLASSIFY_IMAGES_COMP_METRIC);
                            String imFuzz = batchClassPPService.getPropertyValue(batchClassId,
                                    ImageMagicKConstants.CLASSIFY_IMAGES_PLUGIN,
                                    ImageMagicProperties.CLASSIFY_IMAGES_FUZZ_PERCNT);
                            String maxVal = batchClassPPService.getPropertyValue(batchClassId,
                                    ImageMagicKConstants.CLASSIFY_IMAGES_PLUGIN,
                                    ImageMagicProperties.CLASSIFY_IMAGES_MAX_RESULTS);

                            imService.classifyImagesAPI(maxVal, imMetric, imFuzz, batchId, batchClassId,
                                    workingDir, listOfPages);

                            // invoke the document assembler plugin
                            List<Document> doc = docAssembler.createDocumentAPI(
                                    DocumentClassificationFactory.IMAGE, batchClassId, listOfPages);
                            Documents docs = new Documents();
                            docs.getDocument().addAll(doc);
                            StreamResult result;
                            try {
                                result = new StreamResult(resp.getOutputStream());
                                batchSchemaDao.getJAXB2Template().getJaxb2Marshaller().marshal(docs, result);
                            } catch (final IOException e) {
                                respStr = INTERNAL_SERVER_ERROR + e;
                                LOGGER.error(SERVER_ERROR_MSG + respStr);
                            }
                        } catch (final DCMAApplicationException e) {
                            threadList.remove();
                            respStr = "Error while executing threadpool. Detailed exception is " + e;
                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                        } catch (final DCMAException e) {
                            threadList.remove();
                            respStr = "Error while executing threadpool. Detailed exception is " + e;
                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                        }
                    }
                } else {
                    respStr = "Improper input to server. Expected only one tiff file. Returning without processing the results.";
                    LOGGER.error(SERVER_ERROR_MSG + respStr);
                }
            }
        } catch (final Exception e) {
            respStr = INTERNAL_SERVER_ERROR + e;
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        }
    } else {
        respStr = IMPROPER_INPUT_TO_SERVER;
    }
    if (!workingDir.isEmpty()) {
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final IOException ioe) {
            LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe);
        }
    }
}

From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

private void processBarcodeExtarction(final HttpServletRequest req, final HttpServletResponse resp) {
    LOGGER.info("Start processing web service for barcode extraction");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    InputStream instream = null;//from ww w. j a va 2  s . c om
    OutputStream outStream = null;
    if (req instanceof DefaultMultipartHttpServletRequest) {
        try {
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;
            final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();

            if (fileMap.size() != 2) {
                respStr = "Invalid number of files. Expected input should be 1 tif file and 1 xml file.";
            }
            if (respStr.isEmpty()) {
                String xmlFileName = WebServiceUtil.EMPTY_STRING;
                for (final String fileName : fileMap.keySet()) {
                    if (fileName.endsWith(FileType.XML.getExtensionWithDot())) {
                        xmlFileName = fileName;
                    }
                    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 = instream.read(buf);
                    while (len > 0) {
                        outStream.write(buf, 0, len);
                        len = instream.read(buf);
                    }
                }
                if (!xmlFileName.isEmpty()) {
                    WebServiceParams webServiceParams = null;
                    final File xmlFile = new File(workingDir + File.separator + xmlFileName);
                    if (xmlFile.exists()) {
                        final FileInputStream inputStream = new FileInputStream(xmlFile);
                        Source source = XMLUtil.createSourceFromStream(inputStream);
                        webServiceParams = (WebServiceParams) batchSchemaDao.getJAXB2Template()
                                .getJaxb2Marshaller().unmarshal(source);
                    }
                    if (webServiceParams != null) {
                        List<Param> paramList = webServiceParams.getParams().getParam();
                        if (paramList == null || paramList.isEmpty()) {
                            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                            respStr = IMPROPER_XML_PARAMETER;
                        } else {
                            String batchClassIdentifier = WebServiceUtil.EMPTY_STRING;
                            String imageName = WebServiceUtil.EMPTY_STRING;
                            String docType = WebServiceUtil.EMPTY_STRING;
                            for (final Param param : paramList) {
                                LOGGER.error("Parameter: " + param.getName() + " Value: " + param.getValue());
                                if (param.getName().equalsIgnoreCase(WebServiceUtil.BATCH_CLASS_IDENTIFIER)) {
                                    batchClassIdentifier = param.getValue();
                                    continue;
                                }
                                if (param.getName().equalsIgnoreCase(WebServiceUtil.IMAGE_NAME)) {
                                    imageName = param.getValue();
                                    continue;
                                }
                                if (param.getName().equalsIgnoreCase(WebServiceUtil.DOC_TYPE)) {
                                    docType = param.getValue();
                                    continue;
                                }
                            }
                            String results = WebServiceUtil.validateBarcodeExtractionInput(batchClassIdentifier,
                                    imageName, docType);
                            if (!results.isEmpty()) {
                                respStr = results;
                            } else {
                                Set<String> loggedInUserRole = getUserRoles(req);
                                if (loggedInUserRole == null || loggedInUserRole.isEmpty()) {
                                    respStr = "User not authorized to view this API.";
                                } else {
                                    boolean isBatchClassViewableToUser = isBatchClassViewableToUser(
                                            batchClassIdentifier, loggedInUserRole, isSuperAdmin(req));
                                    if (isBatchClassViewableToUser) {
                                        BatchClass batchClass = bcService
                                                .getBatchClassByIdentifier(batchClassIdentifier);
                                        if (batchClass != null) {
                                            List<DocField> updtDocFdTyList = new ArrayList<DocField>();
                                            updtDocFdTyList = barcodeExtractionService.extractPageBarCodeAPI(
                                                    batchClassIdentifier, workingDir, imageName, docType);
                                            LOGGER.info(
                                                    "Generating document level fields for the output result");
                                            final DocumentLevelFields dlfs = new DocumentLevelFields();
                                            dlfs.getDocumentLevelField().addAll(updtDocFdTyList);
                                            Documents docs = new Documents();
                                            Document doc = new Document();
                                            docs.getDocument().add(doc);
                                            doc.setDocumentLevelFields(dlfs);

                                            StreamResult result;
                                            try {
                                                result = new StreamResult(resp.getOutputStream());
                                                resp.setStatus(HttpServletResponse.SC_OK);
                                                batchSchemaDao.getJAXB2Template().getJaxb2Marshaller()
                                                        .marshal(docs, result);
                                            } catch (final IOException e) {
                                                respStr = INTERNAL_SERVER_ERROR + e.getMessage();
                                                LOGGER.error(SERVER_ERROR_MSG + respStr);
                                            }
                                        }
                                    } else {
                                        respStr = "User not authorized to view this batch class id:"
                                                + batchClassIdentifier;
                                    }
                                }

                            }
                        }
                    }
                } else {
                    respStr = "Invalid format specified in the input. Expected XML found " + xmlFileName;
                }
            }
        } catch (final XmlMappingException xmle) {
            respStr = ERROR_IN_MAPPING_INPUT + xmle;
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final DCMAException dcmae) {
            respStr = ERROR_PROCESSING_REQUEST + dcmae;
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final Exception e) {
            respStr = INTERNAL_SERVER_ERROR + e;
            LOGGER.error(SERVER_ERROR_MSG + respStr);
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        } finally {
            IOUtils.closeQuietly(instream);
            IOUtils.closeQuietly(outStream);
        }

        if (!workingDir.isEmpty()) {
            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
        }
        if (!respStr.isEmpty()) {
            try {
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
                LOGGER.error(SERVER_ERROR_MSG + respStr);
            } catch (final IOException ioe) {
                LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe);
            }
        }
    }
}

From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

/**
 * To split Multi page File.//from   w ww .j a  v  a2  s  . co  m
 * @param req {@link HttpServletRequest}
 * @param resp {@link HttpServletResponse}
 * 
 */
@RequestMapping(value = "/splitMultipageFile", method = RequestMethod.POST)
@ResponseBody
public void splitMultipageFile(final HttpServletRequest req, final HttpServletResponse resp) {
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;

    InputStream instream = null;
    OutputStream outStream = null;
    try {
        if (req instanceof DefaultMultipartHttpServletRequest) {
            LOGGER.info("Start spliting multipage file");
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            LOGGER.info("Web Service Folder Path:" + webServiceFolderPath);
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            LOGGER.info("web service workingDir:" + workingDir);
            final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir);
            LOGGER.info("web service outputDir:" + outputDir);
            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;

            final BatchInstanceThread threadList = new BatchInstanceThread(
                    new File(workingDir).getName() + Math.random());
            String inputParams = WebServiceUtil.EMPTY_STRING;
            String outputParams = WebServiceUtil.EMPTY_STRING;
            boolean isGSTool = false;
            for (final Enumeration<String> params = multiPartRequest.getParameterNames(); params
                    .hasMoreElements();) {
                final String paramName = params.nextElement();
                if (paramName.equalsIgnoreCase(WebServiceUtil.IS_GHOSTSCRIPT)) {
                    isGSTool = Boolean.parseBoolean(multiPartRequest.getParameter(paramName));
                    LOGGER.info("Value for isGhostscript parameter is " + isGSTool);
                    continue;
                }

                if (paramName.equalsIgnoreCase(WebServiceUtil.INPUT_PARAMS)) {
                    inputParams = multiPartRequest.getParameter(paramName);
                    LOGGER.info("Value for inputParams parameter is " + inputParams);
                    continue;
                }

                if (paramName.equalsIgnoreCase(WebServiceUtil.OUTPUT_PARAMS)) {
                    outputParams = multiPartRequest.getParameter(paramName);
                    LOGGER.info("Value for outputParams parameter is " + outputParams);
                    continue;
                }
            }
            final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();
            // perform validation on input fields
            String results = WebServiceUtil.validateSplitAPI(fileMap, isGSTool, outputParams, inputParams);
            if (!results.isEmpty()) {
                respStr = results;
            } else {
                LOGGER.info("List of input file names:");
                for (final String fileName : fileMap.keySet()) {
                    LOGGER.info(fileName + WebserviceConstants.COMMA);

                }
                for (final String fileName : fileMap.keySet()) {
                    if (fileName.toLowerCase(Locale.getDefault())
                            .indexOf(FileType.PDF.getExtension()) > -WebserviceConstants.ONE
                            || fileName.toLowerCase(Locale.getDefault())
                                    .indexOf(FileType.TIF.getExtension()) > -WebserviceConstants.ONE
                            || fileName.toLowerCase(Locale.getDefault())
                                    .indexOf(FileType.TIFF.getExtension()) > -WebserviceConstants.ONE) {
                        // only tiffs and RSP file is expected
                        if (isGSTool && (fileName.toLowerCase(Locale.getDefault())
                                .indexOf(FileType.TIF.getExtension()) > -WebserviceConstants.ONE
                                || fileName.toLowerCase(Locale.getDefault())
                                        .indexOf(FileType.TIFF.getExtension()) > -WebserviceConstants.ONE)) {
                            respStr = "Only PDF files expected with GhostScript tool.";
                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                            break;
                        }
                        try {
                            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 = instream.read(buf);
                            while (len > WebserviceConstants.ZERO) {
                                outStream.write(buf, WebserviceConstants.ZERO, len);
                                len = instream.read(buf);
                            }
                        } finally {
                            IOUtils.closeQuietly(instream);
                            IOUtils.closeQuietly(outStream);

                        }
                    } else {
                        respStr = "Files other than tiff, tif and pdf formats are provided.";
                        LOGGER.error(SERVER_ERROR_MSG + respStr);
                        break;
                    }
                }
                if (respStr.isEmpty()) {
                    respStr = performSplitAPIInternal(resp, workingDir, outputDir, threadList, inputParams,
                            outputParams, isGSTool, fileMap);
                }
            }
        } else {
            respStr = IMPROPER_INPUT_TO_SERVER;
        }
    } catch (Exception e) {
        respStr = INTERNAL_SERVER_ERROR + e;
        LOGGER.error(SERVER_ERROR_MSG + respStr);
    }
    if (!workingDir.isEmpty()) {
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final IOException ioe) {
            LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe);
        }
    }
}

From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

/**
 * To import Batch Class.//from  w w  w .  j  av  a2s. c o  m
 * @param req {@link HttpServletRequest}
 * @param resp {@link HttpServletResponse}
 */
@RequestMapping(value = "/importBatchClass", method = RequestMethod.POST)
@ResponseBody
public void importBatchClass(final HttpServletRequest req, final HttpServletResponse resp) {
    String respStr = WebServiceUtil.EMPTY_STRING;
    LOGGER.info("Start processing import batch class web service");
    String workingDir = WebServiceUtil.EMPTY_STRING;
    if (req instanceof DefaultMultipartHttpServletRequest) {
        InputStream instream = null;
        OutputStream outStream = null;
        final String webServiceFolderPath = bsService.getWebServicesFolderPath();
        LOGGER.info("web Service Folder Path" + webServiceFolderPath);
        final DefaultMultipartHttpServletRequest mPartReq = (DefaultMultipartHttpServletRequest) req;
        final MultiValueMap<String, MultipartFile> fileMap = mPartReq.getMultiFileMap();

        if (fileMap.size() == 2) {
            try {
                workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
                LOGGER.info("Created the web service working directory successfully  :" + workingDir);
                ImportBatchClassOptions option = null;
                String zipFilePath = WebServiceUtil.EMPTY_STRING;
                for (final String fileName : fileMap.keySet()) {
                    try {
                        final MultipartFile multiPartFile = mPartReq.getFile(fileName);
                        instream = multiPartFile.getInputStream();
                        if (fileName.toLowerCase(Locale.getDefault())
                                .indexOf(FileType.XML.getExtension().toLowerCase()) > -1) {
                            final Source source = XMLUtil.createSourceFromStream(instream);
                            option = (ImportBatchClassOptions) batchSchemaDao.getJAXB2Template()
                                    .getJaxb2Marshaller().unmarshal(source);
                            continue;
                        } else if (fileName.toLowerCase(Locale.getDefault())
                                .indexOf(FileType.ZIP.getExtension().toLowerCase()) > -1) {
                            zipFilePath = workingDir + File.separator + fileName;
                            LOGGER.info("Zip file is using for importing batch class is " + zipFilePath);
                            final File file = new File(zipFilePath);
                            outStream = new FileOutputStream(file);
                            final byte[] buf = new byte[WebServiceUtil.bufferSize];
                            int len = instream.read(buf);
                            while (len > 0) {
                                outStream.write(buf, 0, len);
                                len = instream.read(buf);
                            }
                            continue;
                        }
                    } finally {
                        IOUtils.closeQuietly(instream);
                        IOUtils.closeQuietly(outStream);
                    }
                }

                respStr = importBatchClassInternal(resp, respStr, workingDir, option, zipFilePath);

            } catch (final XmlMappingException xmle) {
                respStr = ERROR_IN_MAPPING_INPUT + xmle;
            } catch (final Exception e) {
                respStr = INTERNAL_SERVER_ERROR + e.getMessage();
            } finally {

                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        } else {
            respStr = "Improper input to server. Expected two files: zip and xml file. Returning without processing the results.";
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        }
    } else {
        respStr = IMPROPER_INPUT_TO_SERVER;
        LOGGER.error(SERVER_ERROR_MSG + respStr);
    }
    if (!workingDir.isEmpty()) {
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final IOException ioe) {
            LOGGER.error("Error while sending error reponse.");
        }
    }
}

From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

private void processKVExtraction(final HttpServletRequest req, final HttpServletResponse resp) {
    String respStr = WebServiceUtil.EMPTY_STRING;
    LOGGER.info("Processing key value extraction using web service.");
    String workingDir = WebServiceUtil.EMPTY_STRING;

    if (req instanceof DefaultMultipartHttpServletRequest) {
        InputStream instream = null;
        OutputStream outStream = null;
        final String webServiceFolderPath = bsService.getWebServicesFolderPath();
        LOGGER.info("Web Service Folder Path:" + webServiceFolderPath);
        final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;
        final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();

        if (fileMap.size() == 2) {
            try {
                workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
                LOGGER.info("Created web service working directory:" + workingDir + "successfully");
                ExtractKVParams params = null;
                String filePath = WebServiceUtil.EMPTY_STRING;
                for (final String fileName : fileMap.keySet()) {
                    try {
                        final MultipartFile multipartFile = multiPartRequest.getFile(fileName);
                        instream = multipartFile.getInputStream();
                        if (fileName.toLowerCase(Locale.getDefault())
                                .indexOf(FileType.XML.getExtension().toLowerCase()) > -1) {
                            final Source source = XMLUtil.createSourceFromStream(instream);
                            params = (ExtractKVParams) batchSchemaDao.getJAXB2Template().getJaxb2Marshaller()
                                    .unmarshal(source);
                            continue;
                        } else if (fileName.toLowerCase(Locale.getDefault())
                                .indexOf(FileType.HTML.getExtension().toLowerCase()) > -1) {
                            filePath = workingDir + File.separator + fileName;
                            LOGGER.info("HTML file for processing is " + filePath);
                            final File file = new File(filePath);
                            outStream = new FileOutputStream(file);
                            final byte[] buf = new byte[WebServiceUtil.bufferSize];
                            int len = instream.read(buf);
                            while (len > 0) {
                                outStream.write(buf, 0, len);
                                len = instream.read(buf);
                            }// ww  w  .  j av a 2 s  . com
                            continue;
                        }
                    } finally {
                        IOUtils.closeQuietly(instream);
                        IOUtils.closeQuietly(outStream);
                    }
                }

                respStr = validateExtractKV(respStr, params, filePath);
                if (respStr.isEmpty()) {
                    respStr = performExtractKVInternal(resp, respStr, workingDir, params, filePath);
                }

            } catch (final XmlMappingException xmle) {
                respStr = "Error in mapping input XML or the hocr file in the desired format. Please send it in the specified format. Detailed exception is "
                        + xmle;
                LOGGER.error(SERVER_ERROR_MSG + respStr);
            } catch (final DCMAException dcmae) {
                respStr = ERROR_PROCESSING_REQUEST + dcmae;
                LOGGER.error(SERVER_ERROR_MSG + respStr);
            } catch (final Exception e) {
                respStr = "Internal Server error.Please check logs for further details." + e;
                LOGGER.error(SERVER_ERROR_MSG + respStr);
            } finally {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        } else {
            respStr = "Improper input to server. Expected two files: hocr and xml parameter file. Returning without processing the results.";
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        }
    } else {
        respStr = IMPROPER_INPUT_TO_SERVER;
        LOGGER.error(SERVER_ERROR_MSG + respStr);
    }

    if (!workingDir.isEmpty()) {
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final IOException ioe) {
            LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe);
        }
    }
}