Example usage for org.springframework.web.multipart MultipartFile getInputStream

List of usage examples for org.springframework.web.multipart MultipartFile getInputStream

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile getInputStream.

Prototype

@Override
InputStream getInputStream() throws IOException;

Source Link

Document

Return an InputStream to read the contents of the file from.

Usage

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

/**
 * Function of the Helper Class which helps the web services to handle the Request of importing the Batch Class. It process the
 * request but raises an Exception when could not process the Request
 * //from w  ww.j  av  a 2s  .  com
 * @param httpRequest {@link HttpServletRequest} The request made by the client encapsulated as an object
 * @return success or error Message When an exception is not raised after processing the request
 * @throws ValidationException : When could not validate the input or input condition required for the request
 * @throws InternalServerException : When input is valid but server could not process the request
 * @throws Exception : In case of any un-expected Failure
 */
public String importBatchClass(final HttpServletRequest httpRequest)
        throws ValidationException, InternalServerException, Exception {
    String workingDir = WebServiceUtil.EMPTY_STRING;
    boolean isImported = false;
    LOGGER.info("Reached Here");
    if (httpRequest instanceof DefaultMultipartHttpServletRequest) {
        InputStream instream = null;
        OutputStream outStream = null;
        final String webServiceFolderPath = batchSchemaService.getWebServicesFolderPath();
        LOGGER.info("web Service Folder Path" + webServiceFolderPath);
        final DefaultMultipartHttpServletRequest mPartReq = (DefaultMultipartHttpServletRequest) httpRequest;
        final MultiValueMap<String, MultipartFile> fileMap = mPartReq.getMultiFileMap();
        if (fileMap.size() == WebServiceConstants.IMPORT_BATCH_CLASS_FILES) {
            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 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;
                        } else {
                            throw new ValidationException(WebServiceConstants.INVALID_FILES_SEND,
                                    createUnprocessableEntityRestError(WebServiceConstants.INVALID_FILES_SEND,
                                            WebServiceConstants.INVALID_PARAMETERS_CODE));
                        }
                    } finally {
                        IOUtils.closeQuietly(instream);
                        IOUtils.closeQuietly(outStream);
                    }
                }
                importBatchClassInternal(workingDir, option, zipFilePath);
                isImported = true;
            } catch (final InternalServerException ise) {
                throw ise;
            } catch (final ValidationException validationException) {
                throw validationException;
            } catch (final Exception exception) {
                exception.printStackTrace();
                throw new InternalServerException(
                        WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE.concat(exception.getMessage()),
                        createUnprocessableEntityRestError(
                                WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE
                                        .concat(exception.getMessage()),
                                WebServiceConstants.INTERNAL_SERVER_ERROR_CODE));
            } finally {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        } else {
            final String errorMessage = "Improper input to server. Expected two files: zip and xml file. Returning without processing the results.";
            LOGGER.error("Error response at server:" + errorMessage);
            final RestError restError = createUnprocessableEntityRestError(
                    WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE,
                    WebServiceConstants.IMPROPER_INPUT_TO_SERVER_CODE);
            LOGGER.error(errorMessage + WebServiceConstants.HTTP_STATUS + HttpStatus.INTERNAL_SERVER_ERROR);
            throw new ValidationException(
                    WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE + getAdditionalInfo(errorMessage),
                    restError);
        }
    } else {
        final String errorMessage = "Improper input to server. Expected two files: zip and xml file. Returning without processing the results.";
        LOGGER.error("Error response at server:" + errorMessage);
        final RestError restError = createUnprocessableEntityRestError(
                WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE,
                WebServiceConstants.IMPROPER_INPUT_TO_SERVER_CODE);
        LOGGER.error(errorMessage + WebServiceConstants.HTTP_STATUS + HttpStatus.INTERNAL_SERVER_ERROR);
        throw new ValidationException(
                WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE + getAdditionalInfo(errorMessage),
                restError);
    }
    if (!workingDir.isEmpty()) {
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    return isImported ? WebServiceConstants.BATCH_IMPORTED_SUCCESS_MESSAGE
            : WebServiceConstants.BATCH_IMPORTED_FAILURE_MESSAGE;
}

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

/**
 * This Web Service implements the functionality of uploading the Batch and creating the new BatchInstances with the name provided
 * by the user making sure that the there is no Other Batch Instance with the same name under that Batch class and as well as the
 * user has the access to that Batch Class
 * // ww  w  .  j  a  va 2s .c om
 * @param req {@link HttpServletRequest} The request Object encapsulated for the clients Request
 * @param batchClassIdentifier {@link String} Batch Class Identifier which uniquely Identifies the Object
 * @param batchInstanceName {@link String} Batch Instance Name that is the unique name which identifies the batch Instance
 * @param roles {@link Set} Set of the roles assigned to the user
 * @return {@link String} the Result to be displaying When the Request is executed successfully withoput generating an Exception
 * @throws ValidationException When the Input Parameters cannot be validated
 * @throws UnAuthorisedAccessException When User tries to make an access to a batch which is not under his role
 * @throws NoUserRoleException : When the user is not assigned to any role
 * @throws UnSupportedFileTypeException : When the uploaded file is not from any of the supprted file type by plugin pdf/tif/tiff
 * @throws BatchNameAlreadyExistException : The Batch With same Name aslready exist
 * @throws InternalServerException : When Some IOException Occurs at Server
 * @throws Exception When unable to process the Multi-Part Request
 */
public String uploadBatch(final HttpServletRequest req, final String batchClassIdentifier,
        final String batchInstanceName, final Set<String> roles)
        throws ValidationException, UnAuthorisedAccessException, NoUserRoleException,
        UnSupportedFileTypeException, BatchNameAlreadyExistException, InternalServerException, Exception {
    String workingDir = WebServiceUtil.EMPTY_STRING;
    boolean isSuccess = false;
    try {
        InputStream inStream = null;
        OutputStream outStream = null;
        if (StringUtils.isBlank(batchClassIdentifier)) {
            throw new ValidationException(
                    WebServiceConstants.INVALID_BATCH_CLASS_ID_MESSAGE + batchClassIdentifier,
                    createUnprocessableEntityRestError(WebServiceConstants.INVALID_BATCH_CLASS_ID_MESSAGE,
                            WebServiceConstants.INVALID_BATCH_CLASS_ID_CODE));
        } else if (StringUtils.isBlank(batchInstanceName)) {
            throw new ValidationException(
                    WebServiceConstants.INVALID_BATCH_INSTANCE_NAME_MESSAGE + batchClassIdentifier,
                    createUnprocessableEntityRestError(WebServiceConstants.INVALID_BATCH_INSTANCE_NAME_MESSAGE,
                            WebServiceConstants.INVALID_BATCH_INSTANCE_NAME_CODE));
        } else if (req instanceof DefaultMultipartHttpServletRequest) {
            final String webServiceFolderPath = batchSchemaService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;
            final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();
            String uncFolderPath = WebServiceUtil.EMPTY_STRING;
            final List<File> fileList = new ArrayList<File>();
            if (CollectionUtils.isNotEmpty(roles)) {
                final BatchClass batchClass = batchClassService.getBatchClassByUserRoles(roles,
                        batchClassIdentifier);
                if (batchClass == null) {
                    LOGGER.error(
                            "The user does not have the authentication to run the batch in the requested batch class with id: "
                                    + batchClassIdentifier);
                    throw new UnAuthorisedAccessException();
                } else {
                    uncFolderPath = batchClass.getUncFolder();
                }
            } else {
                LOGGER.error(WebServiceConstants.NO_USER_ROLE_EXCEPTION_MESSAGE);
                throw new NoUserRoleException();
            }
            if (fileMap.size() == 0) {
                throw new ValidationException(WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE,
                        createUnprocessableEntityRestError(WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE,
                                WebServiceConstants.IMPROPER_INPUT_TO_SERVER_CODE));
            }
            for (final String srcFileName : fileMap.keySet()) {
                if (FileType.isValidFileName(srcFileName)) {
                    final File file = new File(workingDir + File.separator + srcFileName);
                    fileList.add(file);
                    final MultipartFile multiPartFile = multiPartRequest.getFile(srcFileName);
                    inStream = multiPartFile.getInputStream();
                    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);
                    }
                    IOUtils.closeQuietly(inStream);
                    IOUtils.closeQuietly(outStream);
                } else {
                    LOGGER.error(WebServiceConstants.UNSUPPORTED_FILE_TYPE_EXCEPTION_MESSAGE);
                    throw new UnSupportedFileTypeException();
                }
            }
            final String filePath = workingDir + File.separator + batchInstanceName;
            final File file = new File(filePath);
            if (file.mkdir()) {
                for (final File srcFileName : fileList) {
                    final File destFile = new File(filePath + File.separator + srcFileName.getName());
                    FileUtils.copyFile(srcFileName, destFile);
                }
                final File destFile = new File(uncFolderPath + File.separator + batchInstanceName);
                if (!destFile.exists()) {
                    FileUtils.copyDirectoryWithContents(file, destFile);
                } else {
                    LOGGER.error(WebServiceConstants.BATCH_NAME_ALREADY_EXIST_EXCEPTION_MESSAGE);
                    throw new BatchNameAlreadyExistException();
                }
                isSuccess = true;
            } else {
                LOGGER.error(WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE);
                throw new InternalServerException(WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE,
                        createUnprocessableEntityRestError(WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE,
                                WebServiceConstants.IMPROPER_INPUT_TO_SERVER_CODE));
            }
        } else {
            throw new ValidationException(WebServiceConstants.INVALID_INPUT_FOR_UPLOAD_BATCH,
                    createUnprocessableEntityRestError(WebServiceConstants.INVALID_INPUT_FOR_UPLOAD_BATCH,
                            WebServiceConstants.INVALID_PARAMETERS_CODE));
        }
    } finally {
        if (!workingDir.isEmpty()) {
            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
        }
    }
    return isSuccess ? WebServiceConstants.BATCH_UPLOADED_SUCCESS_MESSAGE
            : WebServiceConstants.BATCH_UPLOADED_FAILURE_MESSAGE;
}

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

/**
 * To split Multi page File./*from   w w w  .j ava2  s  . c o  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

private void processRegularRegexExtraction(final HttpServletRequest req, final HttpServletResponse resp) {
    LOGGER.info("Start processing web service for extracting fields using regex...");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    InputStream instream = null;//from  w w w. jav  a  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 (respStr.isEmpty()) {
                String xmlFileName = WebServiceUtil.EMPTY_STRING;
                if (fileMap.size() == 2) {
                    Set<String> fileNameSet = fileMap.keySet();
                    for (final String fileName : fileNameSet) {
                        try {
                            if (fileName.endsWith(FileType.XML.getExtensionWithDot())) {
                                xmlFileName = fileName;
                            }
                            if (!xmlFileName.isEmpty()) {
                                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);
                                }
                                break;
                            }
                        } finally {
                            IOUtils.closeQuietly(instream);
                            IOUtils.closeQuietly(outStream);
                        }
                    }
                    WebServiceParams webServiceParams = null;
                    final File xmlFile = new File(workingDir + File.separator + xmlFileName);
                    if (xmlFileName == null) {
                        respStr = "No xml file passed...";
                    } else if (xmlFile.exists()) {
                        FileInputStream inputStream = null;
                        try {
                            inputStream = new FileInputStream(xmlFile);
                            Source source = XMLUtil.createSourceFromStream(inputStream);
                            webServiceParams = (WebServiceParams) batchSchemaDao.getJAXB2Template()
                                    .getJaxb2Marshaller().unmarshal(source);
                        } finally {
                            IOUtils.closeQuietly(inputStream);
                        }

                        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 documentType = WebServiceUtil.EMPTY_STRING;
                            String hocrFileName = WebServiceUtil.EMPTY_STRING;
                            for (final Param param : paramList) {
                                if (param.getName().equalsIgnoreCase(WebServiceUtil.DOCUMENT_TYPE)) {
                                    documentType = param.getValue();
                                    LOGGER.info("Value for documentType parameter is " + documentType);
                                    continue;
                                }
                                if (param.getName().equalsIgnoreCase(WebServiceUtil.BATCH_CLASS_IDENTIFIER)) {
                                    batchClassIdentifier = param.getValue();
                                    LOGGER.info("Value for batchClassIdentifier parameter is "
                                            + batchClassIdentifier);
                                    continue;
                                }
                                if (param.getName().equalsIgnoreCase(WebServiceUtil.HOCR_FILE)) {
                                    hocrFileName = param.getValue();
                                    LOGGER.info("Value for hocrFile parameter is " + hocrFileName);
                                    continue;
                                }
                            }
                            respStr = WebServiceUtil.validateExtractRegexFieldsAPI(workingDir,
                                    batchClassIdentifier, documentType, hocrFileName);
                            if (respStr.isEmpty()) {
                                respStr = validateInputAndPerformExtraction(req, resp, respStr, workingDir,
                                        multiPartRequest, fileNameSet, batchClassIdentifier, documentType,
                                        hocrFileName);
                            }
                        }
                    }
                } else {
                    respStr = "Invalid number of files. We are supposed only 2 files each of type: XML and html file.";
                }
            }
        } 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;
        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

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;//w  ww .j av  a 2  s  .c  o  m
    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 extract Field from Hocr.// ww  w . j  a  v  a 2 s.  com
 * @param req {@link HttpServletRequest}
 * @param resp {@link HttpServletResponse}
 */
@RequestMapping(value = "/extractFieldFromHocr", method = RequestMethod.POST)
@ResponseBody
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;
    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 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.";
                LOGGER.error(SERVER_ERROR_MSG + respStr);
            }
            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
                        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[WebserviceConstants.BUF];
                                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()) {
                        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);

                        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());
                            if (eachKVExtraction.getLocationType() != null) {
                                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 + e.getMessage());
                            } catch (final IOException ioe) {
                                LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe);
                            }
                        }
                    }
                } else {
                    respStr = IMPROPER_INPUT_ONLY_ONE_HTML_FILE_EXPECTED;
                    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 create Multi Page File.//from   w  ww. ja  va2s.  com
 * @param req {@link HttpServletRequest}
 * @param resp {@link HttpServletResponse}
 */
@RequestMapping(value = "/createMultiPageFile", method = RequestMethod.POST)
@ResponseBody
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;
    InputStream instream = null;
    OutputStream outStream = null;
    if (req instanceof DefaultMultipartHttpServletRequest) {
        try {
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir);

            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()) {
                try {
                    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 = instream.read(buf);
                        while (len > 0) {
                            outStream.write(buf, 0, len);
                            len = instream.read(buf);
                        }

                    } else {
                        respStr = "Expected only tif, tiff files.";
                        LOGGER.error(SERVER_ERROR_MSG + respStr);
                    }
                } finally {
                    IOUtils.closeQuietly(instream);
                    IOUtils.closeQuietly(outStream);
                }
            }
            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_XML_PARAMETER;
                    LOGGER.error(SERVER_ERROR_MSG + respStr);
                } 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(WebServiceUtil.IMAGE_PROCESSING_API)) {
                            imageProcessingAPI = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase(WebServiceUtil.PDF_OPTIMIZATION_PARAMS)) {
                            pdfOptimizationParams = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase(WebServiceUtil.MULTIPAGE_TIF_SWITCH)) {
                            multipageTifSwitch = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase(WebServiceUtil.PDF_OPTIMIZATION_SWITCH)) {
                            pdfOptimizationSwitch = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase(WebServiceUtil.GHOSTSCRIPT_PDF_PARAMETERS)) {
                            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(WebServiceUtil.APPLICATION_X_ZIP);
                        resp.setHeader(WebServiceUtil.CONTENT_DISPOSITION, WebServiceUtil.ATTACHMENT_FILENAME
                                + zipFileName + FileType.ZIP.getExtensionWithDot() + NEXT_LINE_STRING);
                        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 {
                            IOUtils.closeQuietly(zout);
                            IOUtils.closeQuietly(out);
                            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                        }
                    }
                }
            }
        } 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;
        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 convert Tiff to Pdf.//from  w w w  . j  av a 2 s.c  o  m
 * @param req {@link HttpServletRequest}
 * @param resp {@link HttpServletResponse}
 */
@RequestMapping(value = "/convertTiffToPdf", method = RequestMethod.POST)
@ResponseBody
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) {
        InputStream instream = null;
        OutputStream outStream = null;
        try {
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir);

            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;

            final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();
            if (!fileMap.keySet().isEmpty()) {
                for (final String fileName : fileMap.keySet()) {
                    try {
                        if (!fileName.toLowerCase(Locale.getDefault())
                                .endsWith(FileType.TIF.getExtensionWithDot())
                                && !fileName.toLowerCase(Locale.getDefault())
                                        .endsWith(FileType.TIFF.getExtensionWithDot())) {
                            respStr = "Invalid file. Please pass the valid Tif/Tiff file";
                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                            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 = instream.read(buf);
                        while (len > 0) {
                            outStream.write(buf, 0, len);
                            len = instream.read(buf);
                        }
                    } finally {
                        IOUtils.closeQuietly(instream);
                        IOUtils.closeQuietly(outStream);
                    }
                }
            } else {
                respStr = "Please passed the input files for processing";
                LOGGER.error(SERVER_ERROR_MSG + respStr);
            }

            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(WebServiceUtil.INPUT_PARAMS)) {
                        inputParams = multiPartRequest.getParameter(paramName);
                        LOGGER.info("Value for batchClassIdentifier parameter is " + inputParams);
                        continue;
                    }
                    if (paramName.equalsIgnoreCase(WebServiceUtil.OUTPUT_PARAMS)) {
                        outputParams = multiPartRequest.getParameter(paramName);
                        LOGGER.info("Value for hocrFile parameter is " + outputParams);
                        continue;
                    }
                    if (paramName.equalsIgnoreCase(WebServiceUtil.PDF_GENERATOR_ENGINE)) {
                        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(WebServiceUtil.APPLICATION_X_ZIP);
                    resp.setHeader(WebServiceUtil.CONTENT_DISPOSITION, WebServiceUtil.ATTACHMENT_FILENAME
                            + zipFileName + FileType.ZIP.getExtensionWithDot() + NEXT_LINE_STRING);
                    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 {
                        IOUtils.closeQuietly(zout);
                        IOUtils.closeQuietly(out);
                        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                    }
                }
            }
        } 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;
    }
    if (!respStr.isEmpty()) {
        try {
            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            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

@RequestMapping(value = "/uploadBatch/{batchClassIdentifier}/{batchInstanceName}", method = RequestMethod.POST)
@ResponseBody//from  w w w  . ja  v  a2  s  .  com
public void uploadBatch(@PathVariable(BATCH_CLASS_IDENTIFIER) final String batchClassIdentifier,
        @PathVariable("batchInstanceName") final String batchInstanceName, final HttpServletRequest req,
        final HttpServletResponse resp) {
    LOGGER.info("Start processing web service for uploadBatch.");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    InputStream instream = null;
    OutputStream outStream = null;
    respStr = WebServiceUtil.validateUploadBatchParameters(batchClassIdentifier, batchInstanceName);
    if (respStr.isEmpty()) {
        try {
            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();
                    String uncFolderPath = WebServiceUtil.EMPTY_STRING;
                    List<File> fileList = new ArrayList<File>();
                    try {
                        Set<String> roles = getUserRoles(req);
                        if (roles != null) {
                            BatchClass batchClass = bcService.getBatchClassByUserRoles(roles,
                                    batchClassIdentifier);
                            if (batchClass == null) {
                                respStr = "The user does not have the authentication to run the batch in the requested batch class with id: "
                                        + batchClassIdentifier;
                                LOGGER.error(SERVER_ERROR_MSG + respStr);
                            } else {
                                uncFolderPath = batchClass.getUncFolder();
                            }
                        } else {
                            respStr = "There are no user roles for authenticated user.";
                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                        }
                    } finally {
                        IOUtils.closeQuietly(instream);
                        IOUtils.closeQuietly(outStream);
                    }
                    if (respStr.isEmpty()) {
                        for (String srcFileName : fileMap.keySet()) {
                            try {
                                if (srcFileName.endsWith(FileType.TIF.getExtensionWithDot())
                                        || srcFileName.endsWith(FileType.TIFF.getExtensionWithDot())
                                        || srcFileName.endsWith(FileType.PDF.getExtensionWithDot())) {
                                    final File file = new File(workingDir + File.separator + srcFileName);
                                    fileList.add(file);
                                    final MultipartFile multiPartFile = multiPartRequest.getFile(srcFileName);
                                    instream = multiPartFile.getInputStream();
                                    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);
                                    }
                                } else {
                                    respStr = "Expected only tif, tiff and pdf files.";
                                    LOGGER.error(SERVER_ERROR_MSG + respStr);
                                }
                            } finally {
                                IOUtils.closeQuietly(instream);
                                IOUtils.closeQuietly(outStream);
                            }
                        }
                    }
                    if (respStr.isEmpty()) {
                        String filePath = workingDir + File.separator + batchInstanceName;
                        File file = new File(filePath);
                        if (file.mkdir()) {
                            for (File srcFileName : fileList) {
                                File destFile = new File(filePath + File.separator + srcFileName.getName());
                                try {
                                    FileUtils.copyFile(srcFileName, destFile);
                                } catch (IOException e) {
                                    respStr = "Unable to copy the files to working directory";
                                    LOGGER.error(SERVER_ERROR_MSG + respStr);
                                    break;
                                }
                            }

                            File destFile = new File(uncFolderPath + File.separator + batchInstanceName);
                            try {
                                if (!destFile.exists()) {
                                    FileUtils.copyDirectoryWithContents(file, destFile);
                                } else {
                                    respStr = "The batch name already exists. Please change the name of the batch.";
                                    LOGGER.error(SERVER_ERROR_MSG + respStr);
                                }
                            } catch (IOException e) {
                                respStr = "Unable to copy the files to the unc folder";
                                LOGGER.error(SERVER_ERROR_MSG + respStr);
                            }
                        }
                    }
                } finally {
                    IOUtils.closeQuietly(instream);
                    IOUtils.closeQuietly(outStream);
                }
            } else {
                respStr = IMPROPER_INPUT_TO_SERVER;
                LOGGER.error(SERVER_ERROR_MSG + 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(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 {
        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(
                    "Exception in sending the error code to client. Logged the exception for debugging:" + 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  a2 s.  c  o  m*/
 * @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;
}