Example usage for org.springframework.web.multipart.support DefaultMultipartHttpServletRequest getMultiFileMap

List of usage examples for org.springframework.web.multipart.support DefaultMultipartHttpServletRequest getMultiFileMap

Introduction

In this page you can find the example usage for org.springframework.web.multipart.support DefaultMultipartHttpServletRequest getMultiFileMap.

Prototype

@Override
    public MultiValueMap<String, MultipartFile> getMultiFileMap() 

Source Link

Usage

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

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

        }
    }
}

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

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

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

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

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

        }
    }
}

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

@RequestMapping(value = "/importBatchClass", method = RequestMethod.POST)
@ResponseBody/*  w  ww .  j a  va2s.com*/
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();
        final DefaultMultipartHttpServletRequest mPartReq = (DefaultMultipartHttpServletRequest) req;
        final MultiValueMap<String, MultipartFile> fileMap = mPartReq.getMultiFileMap();

        if (fileMap.size() == 2) {
            try {
                workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
                ImportBatchClassOptions option = null;
                String zipFilePath = WebServiceUtil.EMPTY_STRING;
                for (final String fileName : fileMap.keySet()) {
                    final MultipartFile f = mPartReq.getFile(fileName);
                    instream = f.getInputStream();
                    if (fileName.toLowerCase().indexOf(FileType.XML.getExtension().toLowerCase()) > -1) {
                        final Source source = XMLUtil.createSourceFromStream(instream);
                        option = (ImportBatchClassOptions) batchSchemaDao.getJAXB2Template()
                                .getJaxb2Marshaller().unmarshal(source);
                        continue;
                    } else if (fileName.toLowerCase().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;
                        while ((len = instream.read(buf)) > 0) {
                            outStream.write(buf, 0, len);
                        }
                        continue;
                    }
                }

                if (option != null && !zipFilePath.isEmpty()) {
                    final Map<Boolean, String> results = importBatchService.validateInputXML(option);
                    final String errorMessg = results.get(Boolean.FALSE);
                    if (errorMessg != null && !errorMessg.isEmpty()) {
                        respStr = errorMessg;
                    } else {
                        final File tempZipFile = new File(zipFilePath);
                        final String tempOutputUnZipDir = tempZipFile.getParent() + File.separator + tempZipFile
                                .getName().substring(0, tempZipFile.getName().indexOf(WebServiceUtil.DOT));
                        try {
                            FileUtils.unzip(tempZipFile, tempOutputUnZipDir);
                        } catch (final Exception e) {
                            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                            tempZipFile.delete();
                            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Unable to unzip file. Returning without processing the results.");
                        }

                        option.setZipFilePath(tempOutputUnZipDir);
                        logger.info("Importing batch class");
                        final boolean isDeployed = deploymentService.isDeployed(option.getName());
                        final Map<Boolean, String> resultsImport = importBatchService.importBatchClass(option,
                                isDeployed, true, null);
                        final String errorMessgImport = resultsImport.get(Boolean.FALSE);
                        if (errorMessgImport != null && !errorMessgImport.isEmpty()) {
                            respStr = errorMessgImport;
                        }
                    }
                } else {
                    respStr = "Improper input to the server.Proceeding without processing";
                }

            } catch (final XmlMappingException xmle) {
                respStr = "Error in mapping input XML in the desired format. Please send it in the specified format. Detailed exception is "
                        + xmle;
            } catch (final Exception e) {
                respStr = "Internal Server error.Please check logs for further details." + e.getMessage();
            } finally {
                IOUtils.closeQuietly(instream);
                IOUtils.closeQuietly(outStream);

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

        }
    }
}

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

@RequestMapping(value = "/createMultiPageFile", method = RequestMethod.POST)
@ResponseBody//from ww w .  j  a v  a 2 s  .  com
public void createMultiPageFile(final HttpServletRequest req, final HttpServletResponse resp) {
    logger.info("Start processing web service for createMultiPageFile.");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    if (req instanceof DefaultMultipartHttpServletRequest) {
        try {
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir);
            InputStream instream = null;
            OutputStream outStream = null;
            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;
            final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();
            String xmlFileName = WebServiceUtil.EMPTY_STRING;
            List<File> fileList = new ArrayList<File>();
            for (final String fileName : fileMap.keySet()) {
                if (fileName.endsWith(FileType.XML.getExtensionWithDot())
                        || fileName.endsWith(FileType.TIF.getExtensionWithDot())
                        || fileName.endsWith(FileType.TIFF.getExtensionWithDot())) {
                    final File file = new File(workingDir + File.separator + fileName);
                    if (fileName.endsWith(FileType.XML.getExtensionWithDot())) {
                        xmlFileName = fileName;
                    } else {
                        fileList.add(file);
                    }
                    final MultipartFile multiPartFile = multiPartRequest.getFile(fileName);
                    instream = multiPartFile.getInputStream();
                    outStream = new FileOutputStream(file);
                    final byte[] buf = new byte[WebServiceUtil.bufferSize];
                    int len;
                    while ((len = instream.read(buf)) > 0) {
                        outStream.write(buf, 0, len);
                    }
                    if (instream != null) {
                        instream.close();
                    }
                    if (outStream != null) {
                        outStream.close();
                    }
                } else {
                    respStr = "Expected only tif, tiff files.";
                }
            }
            if (respStr.isEmpty()) {
                final File xmlFile = new File(workingDir + File.separator + xmlFileName);
                final FileInputStream inputStream = new FileInputStream(xmlFile);
                Source source = XMLUtil.createSourceFromStream(inputStream);
                final WebServiceParams webServiceParams = (WebServiceParams) batchSchemaDao.getJAXB2Template()
                        .getJaxb2Marshaller().unmarshal(source);
                if (webServiceParams.getParams() == null || webServiceParams.getParams().getParam() == null
                        || webServiceParams.getParams().getParam().isEmpty()) {
                    FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                    respStr = "Improper input to server. Parameter XML is incorrect. Returning without processing the results.";
                } else {
                    List<Param> paramList = webServiceParams.getParams().getParam();
                    String imageProcessingAPI = WebServiceUtil.EMPTY_STRING;
                    String pdfOptimizationParams = WebServiceUtil.EMPTY_STRING;
                    String multipageTifSwitch = WebServiceUtil.EMPTY_STRING;
                    String pdfOptimizationSwitch = WebServiceUtil.EMPTY_STRING,
                            ghostscriptPdfParameters = WebServiceUtil.EMPTY_STRING;
                    for (final Param param : paramList) {
                        if (param.getName().equalsIgnoreCase("imageProcessingAPI")) {
                            imageProcessingAPI = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase("pdfOptimizationParams")) {
                            pdfOptimizationParams = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase("multipageTifSwitch")) {
                            multipageTifSwitch = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase("pdfOptimizationSwitch")) {
                            pdfOptimizationSwitch = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase("ghostscriptPdfParameters")) {
                            ghostscriptPdfParameters = param.getValue();
                            continue;
                        }
                    }
                    String results = WebServiceUtil.validateCreateMultiPageFile(ghostscriptPdfParameters,
                            imageProcessingAPI, pdfOptimizationSwitch, multipageTifSwitch,
                            pdfOptimizationParams);
                    if (!results.isEmpty()) {
                        respStr = results;
                    } else {
                        imService.createMultiPageFilesAPI(ghostscriptPdfParameters, pdfOptimizationParams,
                                multipageTifSwitch, imageProcessingAPI, pdfOptimizationSwitch, workingDir,
                                outputDir, fileList, new File(workingDir).getName() + Math.random());
                        ServletOutputStream out = null;
                        ZipOutputStream zout = null;
                        final String zipFileName = WebServiceUtil.serverOutputFolderName;
                        resp.setContentType("application/x-zip\r\n");
                        resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName
                                + FileType.ZIP.getExtensionWithDot() + "\"\r\n");
                        try {
                            out = resp.getOutputStream();
                            zout = new ZipOutputStream(out);
                            FileUtils.zipDirectory(outputDir, zout, zipFileName);
                            resp.setStatus(HttpServletResponse.SC_OK);
                        } catch (final IOException e) {
                            respStr = "Unable to process web service request.Please try again." + e;
                        } finally {
                            if (zout != null) {
                                zout.close();
                            }
                            if (out != null) {
                                out.flush();
                            }
                            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                        }
                    }
                }
            }
        } catch (final XmlMappingException xmle) {
            respStr = "Error in mapping input XML in the desired format. Please send it in the specified format. Detailed exception is "
                    + xmle;
        } catch (final DCMAException dcmae) {
            respStr = "Error in processing request. Detailed exception is " + dcmae;
        } catch (final Exception e) {
            respStr = "Internal Server error.Please check logs for further details." + e;
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        }
    } else {
        respStr = "Improper input to server. Expected multipart request. Returning without processing the results.";
    }
    if (!workingDir.isEmpty()) {
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {
        }
    }
}

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

@RequestMapping(value = "/extractKV", method = RequestMethod.POST)
@ResponseBody/*  ww w  . j ava2 s. com*/
public void extractKV(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();
        final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;
        final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();

        if (fileMap.size() == 2) {
            try {
                workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
                ExtractKVParams params = null;
                String filePath = WebServiceUtil.EMPTY_STRING;
                for (final String fileName : fileMap.keySet()) {
                    final MultipartFile multipartFile = multiPartRequest.getFile(fileName);
                    instream = multipartFile.getInputStream();
                    if (fileName.toLowerCase().indexOf(FileType.XML.getExtension().toLowerCase()) > -1) {
                        final Source source = XMLUtil.createSourceFromStream(instream);
                        params = (ExtractKVParams) batchSchemaDao.getJAXB2Template().getJaxb2Marshaller()
                                .unmarshal(source);
                        continue;
                    } else if (fileName.toLowerCase()
                            .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;
                        while ((len = instream.read(buf)) > 0) {
                            outStream.write(buf, 0, len);
                        }
                        continue;
                    }
                }

                if (params != null && params.getParams().size() > 0 && !filePath.isEmpty()) {
                    Params paramList = params.getParams().get(0);
                    if (paramList.getLocationType() == null || paramList.getLocationType().isEmpty()) {
                        respStr = "Please provide the location type. Accepted values are: TOP, RIGHT, LEFT, BOTTOM, TOP_RIGHT, TOP_LEFT, BOTTOM_LEFT, BOTTOM_RIGHT.";
                    }
                    if (respStr.isEmpty()
                            && !LocationType.valuesAsStringList().contains(paramList.getLocationType())) {
                        respStr = "Please provide the location type. Accepted values are: TOP, RIGHT, LEFT, BOTTOM, TOP_RIGHT, TOP_LEFT, BOTTOM_LEFT, BOTTOM_RIGHT.";
                    }
                    if (respStr.isEmpty() && (paramList.getKeyPattern() == null
                            || paramList.getKeyPattern().isEmpty() || paramList.getValuePattern() == null
                            || paramList.getValuePattern().isEmpty())) {
                        respStr = "Please provide the key and value patterns.";
                    }
                    if (paramList.isAdvancedKV()) {
                        if (respStr.isEmpty()
                                && (paramList.getMultiplier() > 1 || paramList.getMultiplier() <= 0)) {
                            respStr = "Please provide the multiplier for Advanced KV extraction. Range of values is between 0 to 1.";
                        }
                        if (respStr.isEmpty() && (paramList.getKVFetchValue() == null
                                || paramList.getKVFetchValue().isEmpty())) {
                            respStr = "Please provide the KVFetchValue for Advanced KV extraction. Expected values are:ALL, FIRST, LAST";
                        }
                        if (respStr.isEmpty()
                                && !(KVFetchValue.valuesAsStringList().contains(paramList.getKVFetchValue()))) {
                            respStr = "Please provide the KVFetchValue for Advanced KV extraction. Expected values are:ALL, FIRST, LAST";
                        }
                        if (respStr.isEmpty() && paramList.getLength() <= 0) {
                            respStr = "Please provide the length value greater than zero with advanced KV extraction.";
                        }
                        if (respStr.isEmpty() && paramList.getWidth() <= 0) {
                            respStr = "Please provide the width value greater than zero with advanced KV extraction.";
                        }
                    } else {
                        if (respStr.isEmpty() && paramList.getNoOfWords() < 0) {
                            respStr = "Please provide positive value for no of words with advanced KV extraction.";
                        }
                    }
                } else {
                    respStr = "Please send an hocr file as input. Improper input to the server.Proceeding without processing";
                }
                if (respStr.isEmpty()) {
                    // extract the hocr content from hocr files
                    // generate hocr from html file
                    HocrPages hocrPages = new HocrPages();
                    List<HocrPage> hocrPageList = hocrPages.getHocrPage();
                    HocrPage hocrPage = new HocrPage();
                    String pageID = "PG0";
                    hocrPage.setPageID(pageID);
                    hocrPageList.add(hocrPage);
                    bsService.hocrGenerationAPI(workingDir, "PG0", filePath, hocrPage);

                    final List<DocField> updtDocList = new ArrayList<DocField>();
                    final boolean isSuccess = kvService.extractKVDocumentFieldsFromHOCR(updtDocList, hocrPages,
                            params);
                    if (!isSuccess) {
                        respStr = "Internal Server error.Please check logs for further details.";
                    } else {
                        logger.info("Generating document level fields for the output result");

                        final DocumentLevelFields dlfs = new DocumentLevelFields();
                        dlfs.getDocumentLevelField().addAll(updtDocList);
                        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.Please check logs for further details."
                                    + e.getMessage();
                        }
                    }
                }

            } 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;
            } catch (final DCMAException dcmae) {
                respStr = "Error in processing request. Detailed exception is " + dcmae;
            } catch (final Exception e) {
                respStr = "Internal Server error.Please check logs for further details." + e;
            } finally {
                IOUtils.closeQuietly(instream);
                IOUtils.closeQuietly(outStream);
                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.";
        }
    } else {
        respStr = "Improper input to server. Expected multipart request. Returning without processing the results.";
    }

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

        }
    }
}

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

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

            InputStream instream = null;
            OutputStream outStream = null;

            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;

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

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

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

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

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

                    BatchInstanceThread batchInstanceThread = new BatchInstanceThread(workingDir);

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

                    batchInstanceThread.execute();

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

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

        }
    }
}

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

@RequestMapping(value = "/extractFixedForm", method = RequestMethod.POST)
@ResponseBody/*from   ww w .j  a  v  a  2s  . c  o  m*/
public void extractFixedForm(final HttpServletRequest req, final HttpServletResponse resp) throws Exception {
    logger.info("Start processing web service for extract fixed form");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    com.ephesoft.dcma.batch.schema.Documents documents = null;
    if (req instanceof DefaultMultipartHttpServletRequest) {
        final String webServiceFolderPath = bsService.getWebServicesFolderPath();
        workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
        final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir);

        InputStream instream = null;
        OutputStream outStream = null;

        final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;

        final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();
        String xmlFileName = WebServiceUtil.EMPTY_STRING;

        if (fileMap.size() != 3) {
            respStr = "Invalid number of files. We are supposed only 3 files.";
        }

        if (respStr.isEmpty()) {
            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;
                while ((len = instream.read(buf)) > 0) {
                    outStream.write(buf, 0, len);
                }
                if (instream != null) {
                    instream.close();
                }

                if (outStream != null) {
                    outStream.close();
                }
            }

            if (xmlFileName.isEmpty()) {
                respStr = "XML file is not found. Returning without processing the results.";
            }

            if (respStr.isEmpty()) {
                final File xmlFile = new File(workingDir + File.separator + xmlFileName);
                final FileInputStream inputStream = new FileInputStream(xmlFile);

                Source source = null;
                try {
                    source = XMLUtil.createSourceFromStream(inputStream);
                    if (respStr.isEmpty()) {
                        final WebServiceParams webServiceParams = (WebServiceParams) batchSchemaDao
                                .getJAXB2Template().getJaxb2Marshaller().unmarshal(source);

                        List<Param> paramList = null;

                        if (webServiceParams != null && webServiceParams.getParams() != null) {
                            paramList = webServiceParams.getParams().getParam();
                        } else {
                            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                            respStr = "Invalid xml file mapped. Returning without processing the results.";
                        }

                        if (respStr.isEmpty()) {
                            String colorSwitch = WebServiceUtil.EMPTY_STRING;
                            String projectFile = WebServiceUtil.EMPTY_STRING;
                            if (paramList == null || paramList.size() <= 0) {
                                respStr = "Improper input to server. Returning without processing the results.";
                            } else {
                                for (final Param param : paramList) {
                                    if (param.getName().equalsIgnoreCase("colorSwitch")) {
                                        colorSwitch = param.getValue();
                                        logger.info("Color Switch for recostar is :" + colorSwitch);
                                        continue;
                                    }
                                    if (param.getName().equalsIgnoreCase("projectFile")) {
                                        projectFile = param.getValue();
                                        logger.info("Project file for recostar is :" + projectFile);
                                        continue;
                                    }
                                }
                            }

                            String[] fileNames = null;
                            final File file = new File(workingDir);
                            respStr = WebServiceUtil.validateExtractFixedFormAPI(workingDir, projectFile,
                                    colorSwitch);

                            if (respStr.isEmpty()) {
                                if (colorSwitch.equalsIgnoreCase(WebServiceUtil.ON_STRING)) {
                                    logger.info("Picking up the png file for processing.");
                                    fileNames = file.list(
                                            new CustomFileFilter(false, FileType.PNG.getExtensionWithDot()));
                                } else {
                                    logger.info("Picking up the tif file for processing.");
                                    fileNames = file.list(
                                            new CustomFileFilter(false, FileType.TIF.getExtensionWithDot(),
                                                    FileType.TIFF.getExtensionWithDot()));
                                }
                                logger.info("Number of file is:" + fileNames.length);

                                if (fileNames != null && fileNames.length > 0) {
                                    for (final String fileName : fileNames) {
                                        logger.info("File processing for recostar is :" + fileName);
                                        documents = recostarExtractionService.extractDocLevelFieldsForRspFile(
                                                projectFile, workingDir, colorSwitch, fileName, workingDir);
                                    }
                                } else {
                                    if (colorSwitch.equalsIgnoreCase(WebServiceUtil.ON_STRING)) {
                                        respStr = "Image file of png type is not found for processing";
                                    } else {
                                        respStr = "Image file of tif type is not found for processing";
                                    }
                                }

                                if (respStr.isEmpty() && documents != null) {
                                    File outputxmlFile = new File(outputDir + File.separator + "OutputXML.xml");
                                    FileOutputStream stream = new FileOutputStream(outputxmlFile);
                                    StreamResult result = new StreamResult(stream);
                                    batchSchemaDao.getJAXB2Template().getJaxb2Marshaller().marshal(documents,
                                            result);

                                    ServletOutputStream out = null;
                                    ZipOutputStream zout = null;
                                    final String zipFileName = WebServiceUtil.serverOutputFolderName;
                                    resp.setContentType("application/x-zip\r\n");
                                    resp.setHeader("Content-Disposition", "attachment; filename=\""
                                            + zipFileName + FileType.ZIP.getExtensionWithDot() + "\"\r\n");
                                    try {
                                        out = resp.getOutputStream();
                                        zout = new ZipOutputStream(out);
                                        FileUtils.zipDirectory(outputDir, zout, zipFileName);
                                        resp.setStatus(HttpServletResponse.SC_OK);
                                    } catch (final IOException e) {
                                        respStr = "Error in creating output zip file.Please try again." + e;
                                    } finally {
                                        if (zout != null) {
                                            zout.close();
                                        }
                                        if (out != null) {
                                            out.flush();
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (final DCMAException e) {
                    respStr = "Error occuring while creating OCR file using recostar. Please try later. " + e;
                } catch (final Exception e) {
                    respStr = "Improper input to server. Returning without processing the results." + e;
                }
            }
        }
        if (!workingDir.isEmpty()) {
            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
        }
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {

        }
    }
}

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

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

            InputStream instream = null;
            OutputStream outStream = null;

            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;

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

                    if (outStream != null) {
                        outStream.close();
                    }
                }
            } else {
                respStr = "Invalid number of files. We are supposed only one file";
            }

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

            if (!hocrFileName.equalsIgnoreCase(htmlFile)) {
                respStr = "Please passed the valid hocr File";
            }

            String results = WebServiceUtil.validateExtractFuzzyDBAPI(workingDir, hocrFileName,
                    batchClassIdentifier, documentType);

            BatchClass batchClass = bcService.getBatchClassByIdentifier(batchClassIdentifier);
            if (batchClass == null) {
                respStr = "Please enter valid batch class identifier";
            } else {
                BatchPlugin fuzzyDBPlugin = batchClassPPService.getPluginProperties(batchClassIdentifier,
                        "FUZZYDB");
                if (fuzzyDBPlugin == null) {
                    respStr = "Fuzzy DB plugin is not configured for batch class : " + batchClassIdentifier
                            + " . Please select proper batch class";
                } else if (fuzzyDBPlugin.getPluginConfigurations(FuzzyDBProperties.FUZZYDB_STOP_WORDS) == null
                        || fuzzyDBPlugin
                                .getPluginConfigurations(FuzzyDBProperties.FUZZYDB_MIN_TERM_FREQ) == null
                        || fuzzyDBPlugin
                                .getPluginConfigurations(FuzzyDBProperties.FUZZYDB_MIN_WORD_LENGTH) == null
                        || fuzzyDBPlugin
                                .getPluginConfigurations(FuzzyDBProperties.FUZZYDB_MAX_QUERY_TERMS) == null
                        || fuzzyDBPlugin.getPluginConfigurations(FuzzyDBProperties.FUZZYDB_NO_OF_PAGES) == null
                        || fuzzyDBPlugin.getPluginConfigurations(FuzzyDBProperties.FUZZYDB_DB_DRIVER) == null
                        || fuzzyDBPlugin
                                .getPluginConfigurations(FuzzyDBProperties.FUZZYDB_CONNECTION_URL) == null
                        || fuzzyDBPlugin.getPluginConfigurations(FuzzyDBProperties.FUZZYDB_DB_USER_NAME) == null
                        || fuzzyDBPlugin.getPluginConfigurations(FuzzyDBProperties.FUZZYDB_DB_PASSWORD) == null
                        || fuzzyDBPlugin
                                .getPluginConfigurations(FuzzyDBProperties.FUZZYDB_THRESHOLD_VALUE) == null) {
                    respStr = "Incomplete properties of the Fuzzy DB plugin for the specified batch class id.";
                }

            }

            List<com.ephesoft.dcma.da.domain.FieldType> allFdTypes = fieldTypeService
                    .getFdTypeByDocTypeNameForBatchClass(documentType, batchClassIdentifier);

            if (allFdTypes == null) {
                respStr = "Please enter valid document type";
            }

            if (!results.isEmpty()) {
                respStr = results;
            } else {
                try {
                    HocrPages hocrPages = new HocrPages();
                    List<HocrPage> hocrPageList = hocrPages.getHocrPage();
                    HocrPage hocrPage = new HocrPage();
                    String pageID = "PG0";
                    hocrPage.setPageID(pageID);
                    hocrPageList.add(hocrPage);
                    bsService.hocrGenerationAPI(workingDir, pageID, workingDir + File.separator + hocrFileName,
                            hocrPage);
                    documents = fuzzyDBSearchService.extractDataBaseFields(batchClassIdentifier, documentType,
                            hocrPages);
                } catch (final DCMAException e) {
                    respStr = "Exception while extracting field using fuzzy db" + e;
                }
            }

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

        }
    }
}

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

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

            InputStream instream = null;
            OutputStream outStream = null;

            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;

            final BatchInstanceThread batchInstanceThread = new BatchInstanceThread(
                    new File(workingDir).getName() + Math.random());

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

            if (!(fileMap.size() >= 2 && fileMap.size() <= 3)) {
                respStr = "Invalid number of files. We are supposed only 3 files.";
            }
            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;
                    while ((len = instream.read(buf)) > 0) {
                        outStream.write(buf, 0, len);
                    }
                    if (instream != null) {
                        instream.close();
                    }

                    if (outStream != null) {
                        outStream.close();
                    }
                }

                final File xmlFile = new File(workingDir + File.separator + xmlFileName);
                final FileInputStream inputStream = new FileInputStream(xmlFile);
                Source source = XMLUtil.createSourceFromStream(inputStream);
                final WebServiceParams webServiceParams = (WebServiceParams) batchSchemaDao.getJAXB2Template()
                        .getJaxb2Marshaller().unmarshal(source);

                List<Param> paramList = webServiceParams.getParams().getParam();
                if (paramList == null || paramList.isEmpty()) {
                    FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                    respStr = "Improper input to server. Parameter XML is incorrect. Returning without processing the results.";
                } else {
                    String ocrEngine = WebServiceUtil.EMPTY_STRING;
                    String colorSwitch = WebServiceUtil.EMPTY_STRING;
                    String projectFile = WebServiceUtil.EMPTY_STRING;
                    String tesseractVersion = WebServiceUtil.EMPTY_STRING;
                    String cmdLanguage = WebServiceUtil.EMPTY_STRING;
                    for (final Param param : paramList) {
                        if (param.getName().equalsIgnoreCase("ocrEngine")) {
                            ocrEngine = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase("colorSwitch")) {
                            colorSwitch = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase("projectFile")) {
                            projectFile = param.getValue();
                            logger.info("Project file for recostar is :" + projectFile);
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase("tesseractVersion")) {
                            tesseractVersion = param.getValue();
                            logger.info("Tesseract version is: " + tesseractVersion);
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase("cmdLanguage")) {
                            // supported values are "eng" and "tha" for now provided tesseract engine is learnt.
                            cmdLanguage = param.getValue();
                            logger.info("cmd langugage is :" + cmdLanguage);
                            continue;
                        }
                    }

                    String results = WebServiceUtil.validateCreateOCRAPI(workingDir, ocrEngine, colorSwitch,
                            projectFile, tesseractVersion, cmdLanguage);
                    if (!results.isEmpty()) {
                        respStr = results;
                    } else {
                        String[] fileNames = null;
                        final File file = new File(workingDir);
                        if (colorSwitch.equalsIgnoreCase(WebServiceUtil.ON_STRING)) {
                            logger.info("Picking up the png file for processing.");
                            fileNames = file
                                    .list(new CustomFileFilter(false, FileType.PNG.getExtensionWithDot()));
                        } else {
                            logger.info("Picking up the tif file for processing.");
                            fileNames = file.list(new CustomFileFilter(false,
                                    FileType.TIF.getExtensionWithDot(), FileType.TIFF.getExtensionWithDot()));
                        }
                        logger.info("Number of file is:" + fileNames.length);
                        logger.info("OcrEngine used for generating ocr is :" + ocrEngine);
                        if (ocrEngine.equalsIgnoreCase("recostar")) {
                            if (fileNames != null && fileNames.length > 0) {
                                for (final String fileName : fileNames) {
                                    try {
                                        logger.info("File processing for recostar is :" + fileName);
                                        recostarService.createOCR(projectFile, workingDir, colorSwitch,
                                                fileName, batchInstanceThread, outputDir);
                                    } catch (final DCMAException e) {
                                        respStr = "Error occuring while creating OCR file using recostar. Please try again."
                                                + e;
                                        break;
                                    }
                                }
                            } else {
                                respStr = "Improper input to server. No tiff/png files provided.";
                            }
                        } else if (ocrEngine.equalsIgnoreCase("tesseract")) {
                            if (fileNames != null && fileNames.length > 0) {
                                for (final String fileName : fileNames) {
                                    try {
                                        logger.info("File processing for ocr with tesseract is :" + fileName);
                                        tesseractService.createOCR(workingDir, colorSwitch, fileName,
                                                batchInstanceThread, outputDir, cmdLanguage, tesseractVersion);
                                    } catch (final DCMAException e) {
                                        respStr = "Error occuring while creating OCR file using tesseract. Please try again."
                                                + e;
                                        break;
                                    }
                                }
                            } else {
                                respStr = "Improper input to server. No tiff/png files provided.";

                            }
                        } else {
                            respStr = "Please select valid tool for generating OCR file.";
                        }
                        if (respStr.isEmpty()) {
                            try {
                                batchInstanceThread.execute();
                                if (ocrEngine.equalsIgnoreCase("recostar")) {
                                    for (final String fileName : fileNames) {
                                        final String recostarXMLFileName = fileName.substring(0,
                                                fileName.lastIndexOf(WebServiceUtil.DOT))
                                                + FileType.XML.getExtensionWithDot();
                                        try {
                                            FileUtils.copyFile(
                                                    new File(workingDir + File.separator + recostarXMLFileName),
                                                    new File(outputDir + File.separator + recostarXMLFileName));
                                        } catch (final Exception e) {
                                            respStr = "Error while generating copying result file." + e;
                                            break;
                                        }
                                    }
                                }
                            } catch (final DCMAApplicationException e) {
                                respStr = "Exception while generating ocr using threadpool" + e;
                            }

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

        }
    }
}

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

@RequestMapping(value = "/extractFieldFromHocr", method = RequestMethod.POST)
@ResponseBody//ww  w  .  jav a2s  . c o  m
public void extractFieldFromHocr(final HttpServletRequest req, final HttpServletResponse resp) {
    logger.info("Start processing web service for extractFieldFromHocr.");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;

    if (req instanceof DefaultMultipartHttpServletRequest) {
        try {
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);

            InputStream instream = null;
            OutputStream outStream = null;

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

            if (fieldValue == null || fieldValue.isEmpty()) {
                respStr = "Field Value not specified.";
            }
            if (respStr.isEmpty()) {
                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
                        if (fileName.toLowerCase().indexOf(FileType.HTML.getExtension()) > -1) {
                            // only HTML file is expected
                            hocrFileName = fileName;
                            final MultipartFile f = multipartReq.getFile(fileName);
                            instream = f.getInputStream();
                            final File file = new File(workingDir + File.separator + fileName);
                            outStream = new FileOutputStream(file);
                            final byte buf[] = new byte[1024];
                            int len;
                            while ((len = instream.read(buf)) > 0) {
                                outStream.write(buf, 0, len);
                            }
                            if (instream != null) {
                                instream.close();
                            }

                            if (outStream != null) {
                                outStream.close();
                            }
                            break;
                        } else {
                            respStr = "Improper input to server. Expected only one html file. Returning without processing the results.";
                        }
                    }
                    if (respStr.isEmpty()) {
                        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 = "PG0";
                        hocrPage.setPageID(pageID);
                        hocrPageList.add(hocrPage);
                        bsService.hocrGenerationAPI(workingDir, "PG0", fileName, hocrPage);

                        List<KVExtraction> kvExtractionList = kvFieldService.createKeyValueFieldAPI(fieldValue,
                                hocrPage);

                        final KVExtractionFieldPatterns patterns = new KVExtractionFieldPatterns();

                        final List<KVExtractionFieldPattern> pattern = patterns.getKVExtractionFieldPattern();
                        for (final KVExtraction eachKVExtraction : kvExtractionList) {
                            final KVExtractionFieldPattern kvField = new KVExtractionFieldPattern();
                            kvField.setDistance(eachKVExtraction.getDistance());
                            kvField.setFetchValue(eachKVExtraction.getFetchValue().name());
                            kvField.setKeyPattern(eachKVExtraction.getKeyPattern());
                            kvField.setLength(eachKVExtraction.getLength());
                            kvField.setLocation(eachKVExtraction.getLocationType().name());
                            kvField.setMultiplier(eachKVExtraction.getMultiplier());
                            kvField.setNoOfWords(eachKVExtraction.getNoOfWords() == null ? 0
                                    : eachKVExtraction.getNoOfWords());
                            kvField.setValuePattern(eachKVExtraction.getValuePattern());
                            kvField.setWidth(eachKVExtraction.getWidth());
                            kvField.setXOffset(eachKVExtraction.getXoffset());
                            kvField.setYOffset(eachKVExtraction.getYoffset());
                            pattern.add(kvField);
                        }
                        StreamResult result;
                        try {
                            result = new StreamResult(resp.getOutputStream());
                            resp.setStatus(HttpServletResponse.SC_OK);
                            batchSchemaDao.getJAXB2Template().getJaxb2Marshaller().marshal(patterns, result);
                        } catch (final IOException e) {
                            try {
                                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                        "Internal Server error.Please check logs for further details."
                                                + e.getMessage());
                            } catch (final IOException ioe) {

                            }
                        }
                    }
                } else {
                    respStr = "Improper input to server. Expected only one html file. Returning without processing the results.";
                }
            }
        } catch (final DCMAException dcmae) {
            respStr = "Error in processing request. Detailed exception is " + dcmae;
        } catch (final Exception e) {
            respStr = "Internal Server error.Please check logs for further details." + e;
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        }
    } else {
        respStr = "Improper input to server. Expected multipart request. Returing without processing the results.";
    }

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

        }
    }
}