Example usage for org.springframework.util MultiValueMap keySet

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

Introduction

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

Prototype

Set<K> keySet();

Source Link

Document

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

Usage

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

/**
 * 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
 * // w w  w  . ja v a 2s.c o  m
 * @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.EphesoftWebServiceAPI.java

private void processFixedFormExtraction(final HttpServletRequest req, final HttpServletResponse resp) {
    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;
    InputStream instream = null;//from  w  w  w.  j  a  v 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();
            String xmlFileName = WebServiceUtil.EMPTY_STRING;

            if (fileMap.size() != WebserviceConstants.THREE) {
                respStr = "Invalid number of files. We are supposed only 3 files each of type: XML, RSP and tif/tiff/png.";
                LOGGER.error(SERVER_ERROR_MSG + respStr);
            }

            if (respStr.isEmpty()) {
                for (final String fileName : fileMap.keySet()) {
                    try {
                        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 (fileName.toLowerCase(Locale.getDefault())
                                .endsWith(FileType.TIF.getExtensionWithDot())
                                || fileName.toLowerCase(Locale.getDefault())
                                        .endsWith(FileType.TIFF.getExtensionWithDot())) {
                            int pageCount = TIFFUtil.getTIFFPageCount(workingDir + File.separator + fileName);
                            if (pageCount > 1) {
                                respStr = ONLY_ONE_SINGLE_PAGE_TIFF_EXPECTED;
                                break;
                            }
                        }
                    } finally {
                        IOUtils.closeQuietly(instream);
                        IOUtils.closeQuietly(outStream);
                    }
                }

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

                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.";
                                LOGGER.error(SERVER_ERROR_MSG + respStr);
                            }

                            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(WebServiceUtil.COLOR_SWITCH)) {
                                            colorSwitch = param.getValue();
                                            LOGGER.info("Color Switch for recostar is :" + colorSwitch);
                                            continue;
                                        }
                                        if (param.getName().equalsIgnoreCase(WebServiceUtil.PROJECT_FILE)) {
                                            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)) {
                                        String[] tifFileNames = file.list(
                                                new CustomFileFilter(false, FileType.TIF.getExtensionWithDot(),
                                                        FileType.TIFF.getExtensionWithDot()));
                                        // generate png file for each tiff/tif file
                                        for (String tifFile : tifFileNames) {
                                            imService.generatePNGForImage(
                                                    new File(workingDir + File.separator + tifFile));
                                        }
                                        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";
                                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                                        } else {
                                            respStr = "Image file of tif type is not found for processing";
                                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                                        }
                                    }

                                    if (respStr.isEmpty() && documents != null) {
                                        StreamResult result = new StreamResult(resp.getOutputStream());
                                        batchSchemaDao.getJAXB2Template().getJaxb2Marshaller()
                                                .marshal(documents, result);
                                    }
                                }
                            }
                        }
                    } catch (final DCMAException e) {
                        respStr = "Error occuring while creating OCR file using recostar. Please try later. "
                                + e;
                        LOGGER.error(SERVER_ERROR_MSG + respStr);
                    } catch (final Exception e) {
                        respStr = "Improper input to server. Returning without processing the results." + e;
                        LOGGER.error(SERVER_ERROR_MSG + respStr);
                    }
                }
            }
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        } catch (Exception e) {
            respStr = INTERNAL_SERVER_ERROR + e;
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        }

    }
    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 OCR.//from w w w  .jav a2  s. c  om
 * @param req {@link HttpServletRequest}
 * @param resp {@link HttpServletResponse}
 */
@RequestMapping(value = "/createOCR", method = RequestMethod.POST)
@ResponseBody
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;
    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 BatchInstanceThread batchInstanceThread = new BatchInstanceThread(
                    new File(workingDir).getName() + Math.random());

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

            if (!(fileMap.size() >= 2 && fileMap.size() <= WebserviceConstants.THREE)) {
                respStr = "Invalid number of files. We are supposed only 3 files each of type:XML, Project RSP file(if recostar tool) and tif/tiff/png file.";
            }
            if (respStr.isEmpty()) {
                String xmlFileName = WebServiceUtil.EMPTY_STRING;
                for (final String fileName : fileMap.keySet()) {
                    try {
                        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 (fileName.endsWith(FileType.TIF.getExtensionWithDot())
                                || fileName.endsWith(FileType.TIFF.getExtensionWithDot())) {
                            int pageCount = TIFFUtil.getTIFFPageCount(workingDir + File.separator + fileName);
                            if (pageCount > 1) {
                                respStr = ONLY_ONE_SINGLE_PAGE_TIFF_EXPECTED;
                                break;
                            }
                        }
                    } finally {
                        IOUtils.closeQuietly(instream);
                        IOUtils.closeQuietly(outStream);
                    }

                }
                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);
                }

                List<Param> paramList = webServiceParams.getParams().getParam();
                if (paramList == null || paramList.isEmpty()) {
                    FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                    respStr = IMPROPER_XML_PARAMETER;
                } 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(WebServiceUtil.OCR_ENGINE)) {
                            ocrEngine = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase(WebServiceUtil.COLOR_SWITCH)) {
                            colorSwitch = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase(WebServiceUtil.PROJECT_FILE)) {
                            projectFile = param.getValue();
                            LOGGER.info("Project file for recostar is :" + projectFile);
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase(WebServiceUtil.TESSERACT_VERSION)) {
                            tesseractVersion = param.getValue();
                            LOGGER.info("Tesseract version is: " + tesseractVersion);
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase(WebServiceUtil.CMD_LANGUAGE)) {
                            // 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)) {
                            String[] tifFileNames = file.list(new CustomFileFilter(false,
                                    FileType.TIF.getExtensionWithDot(), FileType.TIFF.getExtensionWithDot()));
                            // generate png file for each tiff/tif file
                            for (String tifFile : tifFileNames) {
                                imService.generatePNGForImage(new File(workingDir + File.separator + tifFile));
                            }
                            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(WebServiceUtil.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;
                                        LOGGER.error(SERVER_ERROR_MSG + respStr);
                                        break;
                                    }
                                }
                            } else {
                                if (colorSwitch.equalsIgnoreCase(WebServiceUtil.OFF_STRING)) {
                                    respStr = "Improper input to server. No tiff files provided.";
                                } else {
                                    respStr = "Improper input to server. No tiff/png files provided.";
                                }
                            }
                        } else if (ocrEngine.equalsIgnoreCase(WebServiceUtil.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;
                                        LOGGER.error(SERVER_ERROR_MSG + respStr);
                                        break;
                                    }
                                }
                            } else {
                                respStr = "Improper input to server. No tiff/png files provided.";
                                LOGGER.error(SERVER_ERROR_MSG + respStr);

                            }
                        } else {
                            respStr = "Please select valid tool for generating OCR file.";
                        }
                        if (respStr.isEmpty()) {
                            try {
                                batchInstanceThread.execute();
                                if (ocrEngine.equalsIgnoreCase(WebServiceUtil.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;
                                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                                            break;
                                        }
                                    }
                                }
                            } catch (final DCMAApplicationException e) {
                                respStr = "Exception while generating ocr using threadpool" + e;
                            }
                            if (respStr.isEmpty()) {
                                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 = "Error in creating output zip file.Please try again." + e;
                                    LOGGER.error(SERVER_ERROR_MSG + respStr);
                                } 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.util.WebServiceHelper.java

public void processCreateHOCRXML(final HttpServletRequest req, final HttpServletResponse resp)
        throws InternalServerException, ValidationException {
    LOGGER.info("Start processing web service for create HOCR-XML for Batch Class");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    File zipInFolder = null;/*  www .j  av a  2 s .c  o  m*/
    File zipOutFolder = null;
    int responseCode = 0;
    WebServiceParams webServiceParams = null;
    if (req instanceof DefaultMultipartHttpServletRequest) {
        try {
            final String webServiceFolderPath = batchSchemaService.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.size() != 2) {
                LOGGER.error("Invalid Number of files sent to the server");
                respStr = WebServiceConstants.INVALID_ARGUMENTS_FOR_CREATE_HOCR;
                responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
            } else {
                String xmlFileName = WebServiceUtil.EMPTY_STRING;
                String zipOutputLocation = WebServiceUtil.EMPTY_STRING;
                String zipFileNameWithOutExt = WebServiceUtil.EMPTY_STRING;
                for (final String fileName : fileMap.keySet()) {
                    InputStream instream = null;
                    OutputStream outStream = null;
                    ZipInputStream zipstream = null;
                    try {

                        if (!(fileName.endsWith(FileType.ZIP.getExtensionWithDot())
                                || fileName.endsWith(FileType.XML.getExtensionWithDot())
                                || fileName.endsWith(FileType.TIF.getExtensionWithDot())
                                || fileName.endsWith(FileType.TIFF.getExtensionWithDot()))) {
                            respStr = WebServiceConstants.INVALID_ARGUMENTS_FOR_CREATE_OCR_BATCH_CLASS;
                            responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
                        }
                        final MultipartFile multiPartFile = multiPartRequest.getFile(fileName);
                        instream = multiPartFile.getInputStream();

                        if (fileName.endsWith(FileType.XML.getExtensionWithDot())) {
                            xmlFileName = fileName;
                            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 (fileName.endsWith(FileType.ZIP.getExtensionWithDot())) {
                            zipFileNameWithOutExt = FilenameUtils.removeExtension(fileName);
                            zipInFolder = new File(workingDir + File.separator + zipFileNameWithOutExt);
                            if (zipInFolder != null) {
                                zipInFolder.mkdirs();
                            }
                            zipstream = new ZipInputStream(instream);
                            ZipEntry ze = zipstream.getNextEntry();
                            if (ze == null) {
                                respStr = WebServiceConstants.NO_FILES_IN_ZIP_DIR;
                                responseCode = WebServiceConstants.NO_FILES_IN_ZIP_DIR_CODE;
                                LOGGER.error(respStr + " No files in the zip directory ");
                            }
                            while (ze != null) {
                                String upzipFileName = ze.getName();
                                LOGGER.info("Unzipping " + upzipFileName);

                                if (!(upzipFileName.endsWith(FileType.TIF.getExtensionWithDot())
                                        || upzipFileName.endsWith(FileType.TIFF.getExtensionWithDot())
                                        || upzipFileName.endsWith(FileType.PDF.getExtensionWithDot()))) {
                                    respStr = WebServiceConstants.UNSUPPORTED_FILE_TYPE_EXCEPTION_MESSAGE;
                                    responseCode = WebServiceConstants.UNSUPPORTED_FILE_TYPE_EXCEPTION_CODE;
                                    LOGGER.error("File name should be a valid tif, tiff or pdf file name only");
                                }
                                final File filePath = new File(zipInFolder + File.separator + upzipFileName);
                                outStream = new FileOutputStream(filePath);
                                final byte[] buf = new byte[WebServiceUtil.bufferSize];
                                int len;
                                while ((len = zipstream.read(buf)) > 0) {
                                    outStream.write(buf, 0, len);
                                }
                                final int pageCount = TIFFUtil
                                        .getTIFFPageCount(zipInFolder + File.separator + upzipFileName);
                                if (pageCount > 1
                                        || upzipFileName.endsWith(FileType.PDF.getExtensionWithDot())) {
                                    final BatchInstanceThread threadList = new BatchInstanceThread(
                                            new File(zipInFolder.toString()).getName() + Math.random());
                                    LOGGER.info(
                                            "Start spliting multipage tiff/pdf file into tiffs using image magick");
                                    imService.convertPdfOrMultiPageTiffToTiffUsingIM("", filePath, "",
                                            new File(EphesoftStringUtil.concatenate(zipInFolder.toString(),
                                                    File.separator, upzipFileName)),
                                            threadList);
                                    threadList.execute();
                                }
                                ze = zipstream.getNextEntry();
                            }
                        }
                        if (fileName.endsWith(FileType.TIFF.getExtensionWithDot())
                                || fileName.endsWith(FileType.TIF.getExtensionWithDot())) {
                            zipFileNameWithOutExt = WebServiceUtil.EMPTY_STRING;
                            final File file = new File(workingDir + File.separator + fileName);
                            zipInFolder = new File(workingDir);
                            outStream = new FileOutputStream(file);
                            final byte[] buf = new byte[WebServiceUtil.bufferSize];
                            int len;
                            while ((len = instream.read(buf)) > 0) {
                                outStream.write(buf, 0, len);
                            }
                            final int pageCount = TIFFUtil
                                    .getTIFFPageCount(workingDir + File.separator + fileName);
                            if (pageCount > 1) {
                                final BatchInstanceThread threadList = new BatchInstanceThread(
                                        zipInFolder.getName() + Math.random());
                                LOGGER.info(
                                        "Start spliting multipage tiff/pdf file into tiffs using image magick");
                                imService.convertPdfOrMultiPageTiffToTiffUsingIM(WebServiceUtil.EMPTY_STRING,
                                        file, WebServiceUtil.EMPTY_STRING, new File(EphesoftStringUtil
                                                .concatenate(workingDir.toString(), File.separator, fileName)),
                                        threadList);
                                threadList.execute();
                            }
                        }
                    } finally {
                        IOUtils.closeQuietly(instream);
                        IOUtils.closeQuietly(outStream);
                        IOUtils.closeQuietly(zipstream);
                    }
                }
                final File xmlFile = new File(workingDir + File.separator + xmlFileName);
                if (StringUtils.isNotEmpty(xmlFileName) && xmlFile.exists()) {
                    final FileInputStream inputStream = new FileInputStream(xmlFile);
                    final Source source = XMLUtil.createSourceFromStream(inputStream);
                    final Object unmarshelledObject = batchSchemaDao.getJAXB2Template().getJaxb2Marshaller()
                            .unmarshal(source);
                    if (!(unmarshelledObject instanceof WebServiceParams)) {
                        respStr = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_MESSAGE;
                        responseCode = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_CODE;
                    } else {
                        webServiceParams = (WebServiceParams) unmarshelledObject;
                        if (null != webServiceParams.getParams()) {
                            final List<Param> paramList = webServiceParams.getParams().getParam();
                            if (paramList == null || paramList.isEmpty()) {
                                final HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
                                respStr = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_MESSAGE;
                                responseCode = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_CODE;
                                LOGGER.error(respStr + "\n No Parameters in the request" + status);
                            } else {
                                String batchClassId = WebServiceUtil.EMPTY_STRING;
                                for (final Param param : paramList) {
                                    if (WebServiceConstants.BATCH_CLASS_IDENTIFIER
                                            .equalsIgnoreCase(param.getName())) {
                                        batchClassId = param.getValue();
                                        continue;
                                    }
                                    if (WebServiceUtil.ZIP_OUTPUT_LOCATION.equalsIgnoreCase(param.getName())) {
                                        zipOutputLocation = param.getValue();
                                        if (StringUtils.isBlank(zipOutputLocation)
                                                || !(new File(zipOutputLocation).isDirectory())) {
                                            respStr = WebServiceConstants.ZIP_OUTPUT_LOCATION_INVALID_MESSAGE;
                                            responseCode = WebServiceConstants.ZIP_OUTPUT_LOCATION_INVALID_CODE;
                                            LOGGER.error(
                                                    "Zip output location is blank or invalid in xml input file");
                                        }
                                        continue;
                                    }
                                    if (WebServiceUtil.ZIP_NAME.equalsIgnoreCase(param.getName())) {
                                        if (!((zipFileNameWithOutExt + FileType.ZIP.getExtensionWithDot())
                                                .equals(param.getValue()))) {
                                            respStr = WebServiceConstants.INPUT_ZIP_NOT_FOUND_MESSAGE;
                                            responseCode = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_CODE;
                                            LOGGER.error(
                                                    "Zip file name doesn't match zip file name in xml input file");
                                        } else
                                            continue;
                                    }
                                }
                                if (respStr == null || respStr.isEmpty()) {
                                    if (batchClassId != null && !batchClassId.isEmpty()) {
                                        final BatchClass batchClass = batchClassService
                                                .getBatchClassByIdentifier(batchClassId);
                                        if (batchClass != null) {

                                            final String ocrEngine = getDefaultHOCRPlugin(batchClassId);
                                            String colorSwitch = WebServiceUtil.EMPTY_STRING;
                                            String cmdLanguage = WebServiceUtil.EMPTY_STRING;
                                            LOGGER.info(EphesoftStringUtil.concatenate("Ocr engine used is : ",
                                                    ocrEngine));

                                            if (WebServiceConstants.TESSERACT_HOCR_PLUGIN
                                                    .equalsIgnoreCase(ocrEngine)) {
                                                final File dir = new File(zipInFolder + "");
                                                File[] directoryListing = dir.listFiles();
                                                if (directoryListing != null) {
                                                    zipOutFolder = new File(
                                                            outputDir + File.separator + zipFileNameWithOutExt);
                                                    if (zipOutFolder != null) {
                                                        zipOutFolder.mkdirs();
                                                    }
                                                    for (File inputFile : directoryListing) {
                                                        String inputFileName = inputFile.getName();
                                                        if (inputFileName != null && !inputFileName.isEmpty()) {
                                                            if (inputFileName.endsWith(
                                                                    FileType.TIFF.getExtensionWithDot())
                                                                    || inputFileName.endsWith(FileType.TIF
                                                                            .getExtensionWithDot())) {
                                                                final int pageCountTiff = TIFFUtil
                                                                        .getTIFFPageCount(inputFile.toString());
                                                                if (pageCountTiff > 1) {
                                                                    continue;
                                                                }

                                                                if (WebServiceConstants.TESSERACT_HOCR_PLUGIN
                                                                        .equalsIgnoreCase(ocrEngine)) {
                                                                    final BatchPlugin pluginProperties = classPluginPropertiesService
                                                                            .getPluginProperties(batchClassId,
                                                                                    WebServiceConstants.TESSERACT_HOCR_PLUGIN);
                                                                    if (pluginProperties != null) {
                                                                        if (pluginProperties
                                                                                .getPluginConfigurations(
                                                                                        TesseractProperties.TESSERACT_COLOR_SWITCH) != null) {
                                                                            colorSwitch = classPluginPropertiesService
                                                                                    .getPropertyValue(
                                                                                            batchClassId,
                                                                                            WebServiceConstants.TESSERACT_HOCR_PLUGIN,
                                                                                            TesseractProperties.TESSERACT_COLOR_SWITCH);
                                                                            if (pluginProperties
                                                                                    .getPluginConfigurations(
                                                                                            TesseractProperties.TESSERACT_LANGUAGE) != null) {
                                                                                cmdLanguage = classPluginPropertiesService
                                                                                        .getPropertyValue(
                                                                                                batchClassId,
                                                                                                WebServiceConstants.TESSERACT_HOCR_PLUGIN,
                                                                                                TesseractProperties.TESSERACT_LANGUAGE);
                                                                                tesseractService.createOCR(
                                                                                        zipInFolder.toString(),
                                                                                        colorSwitch,
                                                                                        inputFileName,
                                                                                        zipOutFolder.toString(),
                                                                                        cmdLanguage,
                                                                                        WebServiceConstants.TESSERACT_CURRENT_VERSION);
                                                                            } else {
                                                                                respStr = WebServiceConstants.NO_TESSERACT_LANGUAGE_SUPPORT;
                                                                                responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE;
                                                                                LOGGER.error(
                                                                                        "No Language Support");
                                                                            }

                                                                        } else {
                                                                            respStr = WebServiceConstants.NO_TESSERACT_COLOR_SWITCH;
                                                                            responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE;
                                                                            LOGGER.error(
                                                                                    "Colour Switch Not Found");
                                                                        }
                                                                    } else {
                                                                        respStr = WebServiceConstants.NO_PROPERTY_FOR_TESSERACT_HOCR;
                                                                        responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE;
                                                                    }
                                                                }

                                                            }
                                                        } else {
                                                            respStr = WebServiceConstants.INVALID_FILE_NAME;
                                                            responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
                                                            LOGGER.error(
                                                                    "File Name should not be NULL or empty ");
                                                        }
                                                    } // End of for loop

                                                }

                                                else {
                                                    respStr = WebServiceConstants.NO_FILES_IN_ZIP_DIR;
                                                    responseCode = WebServiceConstants.NO_FILES_IN_ZIP_DIR_CODE;
                                                    LOGGER.error(respStr + " No files in the zip directory ");
                                                }

                                            }
                                            if (respStr.isEmpty()) {
                                                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()
                                                                + "\"\r\n");
                                                resp.setStatus(HttpServletResponse.SC_OK);
                                                try {
                                                    out = resp.getOutputStream();
                                                    zout = new ZipOutputStream(out);
                                                    FileUtils.zipDirectory(zipOutFolder.toString(), zout,
                                                            zipFileName);
                                                } catch (final FileNotFoundException fileNotFoundException) {
                                                    String messageString = fileNotFoundException.getMessage();
                                                    messageString = messageString.substring(
                                                            messageString.lastIndexOf(File.separator));
                                                    respStr = WebServiceConstants.FILE_NOT_FOUND
                                                            + messageString;
                                                    responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE;
                                                    LOGGER.error("Could Not Copy the File "
                                                            + fileNotFoundException.getMessage());
                                                } catch (final IOException ioExcpetion) {
                                                    respStr = WebServiceConstants.ERROR_WHILE_CREATING_ZIPPED_FILE
                                                            + ioExcpetion;
                                                    responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE;
                                                    LOGGER.error(respStr);
                                                } finally {
                                                    IOUtils.closeQuietly(zout);
                                                    IOUtils.closeQuietly(out);
                                                }
                                            }
                                            if (respStr.isEmpty()) {
                                                FileOutputStream fos = null;
                                                ZipOutputStream zos = null;
                                                final File out = new File(zipOutputLocation + File.separator
                                                        + zipFileNameWithOutExt
                                                        + FileType.ZIP.getExtensionWithDot());
                                                try {
                                                    fos = new FileOutputStream(out);
                                                    zos = new ZipOutputStream(fos);
                                                    FileUtils.zipDirectory(zipOutFolder.toString(), zos,
                                                            zipFileNameWithOutExt);

                                                } catch (final FileNotFoundException fileNotFoundException) {
                                                    String messageString = fileNotFoundException.getMessage();
                                                    messageString = messageString.substring(
                                                            messageString.lastIndexOf(File.separator));
                                                    respStr = WebServiceConstants.FILE_NOT_FOUND
                                                            + messageString;
                                                    responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE;
                                                    LOGGER.error("Could Not Copy the File "
                                                            + fileNotFoundException.getMessage());
                                                } catch (final IOException ioExcpetion) {
                                                    respStr = WebServiceConstants.ERROR_WHILE_CREATING_ZIPPED_FILE
                                                            + ioExcpetion;
                                                    responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE;
                                                    LOGGER.error(respStr);
                                                } finally {
                                                    IOUtils.closeQuietly(zos);
                                                    IOUtils.closeQuietly(fos);
                                                }
                                            }

                                        } else {
                                            respStr = WebServiceConstants.INVALID_BATCH_CLASS_ID_MESSAGE;
                                            responseCode = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_CODE;
                                            LOGGER.error(respStr + " Batch Class ID doesnot exist ");
                                        }
                                    } else {
                                        respStr = WebServiceConstants.INVALID_BATCH_CLASS_ID_MESSAGE;
                                        responseCode = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_CODE;
                                        LOGGER.error(respStr + " No input of Batch Class ID ");
                                    }
                                }
                            }
                        }
                    }
                } else {
                    respStr = WebServiceConstants.INPUT_FILES_NOT_FOUND_MESSAGE;
                    responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
                }
            }
        } catch (final FileNotFoundException fileNotFoundException) {
            String message = fileNotFoundException.getMessage();
            message = message.substring(message.lastIndexOf(File.separator));
            respStr = WebServiceConstants.FILE_NOT_FOUND + message;
        } catch (final ValidationException validationException) {
            throw validationException;
        } catch (final InternalServerException internalServerError) {
            throw internalServerError;
        } catch (final Exception exception) {
            respStr = WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE + exception;
            responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE;
            exception.printStackTrace();
        } finally {
            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir));
        }
    } else {
        respStr = WebServiceConstants.INVALID_MULTIPART_REQUEST;
        responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE;
    }
    validateResponse(responseCode, respStr);
}

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
 * /*from ww w .  j av  a 2 s .c o m*/
 * @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

@RequestMapping(value = "/uploadBatch/{batchClassIdentifier}/{batchInstanceName}", method = RequestMethod.POST)
@ResponseBody//from   www  . j av a 2  s. co  m
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.EphesoftWebServiceAPI.java

/**
 * To extract From Image.//w  ww .ja v  a2 s .  c o  m
 * @param req {@link HttpServletRequest}
 * @param resp {@link HttpServletResponse}
 */
@RequestMapping(value = "/extractFromImage", method = RequestMethod.POST)
@ResponseBody
public void extractFromImage(final HttpServletRequest req, final HttpServletResponse resp) {
    LOGGER.info("Start processing web service for performExtractionForImage..");
    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 BatchInstanceThread batchInstanceThread = new BatchInstanceThread();

            final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();
            final DefaultMultipartHttpServletRequest multipartReq = (DefaultMultipartHttpServletRequest) req;
            String batchClassId = WebServiceUtil.EMPTY_STRING;
            String ocrEngine = WebServiceUtil.EMPTY_STRING;
            String colorSwitch = WebServiceUtil.EMPTY_STRING;
            String projectFile = WebServiceUtil.EMPTY_STRING;
            String cmdLanguage = WebServiceUtil.EMPTY_STRING;
            String documentType = WebServiceUtil.EMPTY_STRING;
            String tifFileName = WebServiceUtil.EMPTY_STRING;
            for (final Enumeration<String> params = multipartReq.getParameterNames(); params
                    .hasMoreElements();) {
                final String paramName = params.nextElement();
                if (paramName.equalsIgnoreCase(WebServiceUtil.BATCH_CLASS_IDENTIFIER)) {
                    batchClassId = multipartReq.getParameter(paramName);
                    continue;
                }
                if (paramName.equalsIgnoreCase(WebServiceUtil.OCR_ENGINE)) {
                    ocrEngine = multipartReq.getParameter(paramName);
                    continue;
                }
                if (paramName.equalsIgnoreCase(WebServiceUtil.COLOR_SWITCH)) {
                    colorSwitch = multipartReq.getParameter(paramName);
                    continue;
                }
                if (paramName.equalsIgnoreCase(WebServiceUtil.PROJECT_FILE)) {
                    projectFile = multipartReq.getParameter(paramName);
                    continue;
                }
                if (paramName.equalsIgnoreCase(WebServiceUtil.CMD_LANGUAGE)) {
                    cmdLanguage = multipartReq.getParameter(paramName);
                    continue;
                }
                if (paramName.equalsIgnoreCase(WebServiceUtil.DOCUMENT_TYPE)) {
                    documentType = multipartReq.getParameter(paramName);
                    continue;
                }

            }
            LOGGER.info("Parameters for the web service are: ");
            LOGGER.debug(WebServiceUtil.BATCH_CLASS_IDENTIFIER + " :" + batchClassId);
            LOGGER.debug(WebServiceUtil.OCR_ENGINE + " :" + ocrEngine);
            LOGGER.debug(WebServiceUtil.COLOR_SWITCH + " :" + colorSwitch);
            LOGGER.debug(WebServiceUtil.PROJECT_FILE + " :" + projectFile);
            // logger.debug("" + tesseractVersion);
            LOGGER.debug(WebServiceUtil.CMD_LANGUAGE + " :" + cmdLanguage);
            LOGGER.debug(WebServiceUtil.DOCUMENT_TYPE + " :" + documentType);

            final int attachedFileSize = fileMap.size();
            if (attachedFileSize != 1) {
                respStr = "Invalid number of files. Expected number of file(s): 1 of type: tif/tiff/png file. Recieved: "
                        + attachedFileSize + " file(s)";
            }
            if (respStr.isEmpty()) {
                for (final String fileName : fileMap.keySet()) {
                    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 > 0) {
                            outStream.write(buf, 0, len);
                            len = instream.read(buf);
                        }
                        if (fileName.endsWith(FileType.TIF.getExtensionWithDot())
                                || fileName.endsWith(FileType.TIFF.getExtensionWithDot())) {
                            tifFileName = fileName;
                            LOGGER.debug("Image Name :" + tifFileName);

                        }
                    } finally {
                        IOUtils.closeQuietly(instream);
                        IOUtils.closeQuietly(outStream);
                    }

                }

                final StringBuilder projectFileBuffer = new StringBuilder();
                projectFileBuffer.append(bsService.getBaseFolderLocation());
                projectFileBuffer.append(File.separator);
                projectFileBuffer.append(batchClassId);
                projectFileBuffer.append(File.separator);
                projectFileBuffer.append(RECOSTAR_EXTRACTION);
                projectFileBuffer.append(File.separator);
                projectFileBuffer.append(projectFile);
                final String projectFilePath = projectFileBuffer.toString();
                final String results = WebServiceUtil.validateExtractFromImageAPI(workingDir, ocrEngine,
                        colorSwitch, projectFilePath, cmdLanguage, tifFileName);
                if (!results.isEmpty()) {
                    respStr = results;
                } else {
                    String[] fileNames = null;
                    final File file = new File(workingDir);
                    fileNames = splitImagesAndCreatePNG(workingDir, colorSwitch, file);
                    LOGGER.info("Number of file is:" + fileNames.length);
                    LOGGER.info("OcrEngine used for generating ocr is :" + ocrEngine);
                    if (ocrEngine.equalsIgnoreCase(WebServiceUtil.RECOSTAR)) {
                        respStr = createHOCRViaRecostar(workingDir, outputDir, batchInstanceThread, colorSwitch,
                                projectFilePath, fileNames);
                    } else if (ocrEngine.contains(WebServiceUtil.TESSERACT)) {
                        respStr = createHOCRViaTesseract(workingDir, outputDir, batchInstanceThread,
                                colorSwitch, ocrEngine, cmdLanguage, fileNames);
                    } else {
                        respStr = "Please select valid tool for generating OCR file.";
                    }
                    if (respStr.isEmpty()) {
                        respStr = executeBatchInstanceThread(workingDir, outputDir, batchInstanceThread,
                                ocrEngine, fileNames);
                    }

                }
            }
            if (respStr.isEmpty()) {
                final String hocrFilePath = outputDir + File.separator
                        + tifFileName.substring(0, tifFileName.lastIndexOf(CONSTANT_DOT) + 1)
                        + FileType.HTML.getExtension();
                LOGGER.debug("Generated HOCR file located at " + hocrFilePath);
                final Set<String> loggedInUserRole = getUserRoles(req);
                if (!isBatchClassViewableToUser(batchClassId, loggedInUserRole, isSuperAdmin(req))) {
                    respStr = "User is not authorized to view the batch class for given identifier:"
                            + batchClassId;
                    LOGGER.error("Error response at server:" + respStr);
                }

                LOGGER.info("Performing Extraction using KV mechanism.");
                respStr = extractKVFromHOCR(resp, respStr, outputDir, batchClassId, hocrFilePath, documentType);
            }

        } catch (final DCMAException dcmae) {
            respStr = "Error in processing request. Detailed exception is " + dcmae;
            LOGGER.error("Error response at server:" + respStr);
        } catch (final Exception e) {
            respStr = INTERNAL_SERVER_ERROR + e;
            LOGGER.error("Error response at server:" + respStr);
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        }
    } else {
        respStr = IMPROPER_INPUT_TO_SERVER;
        LOGGER.error("Error response at server:" + respStr);
    }
    if (!workingDir.isEmpty()) {
        LOGGER.info("Clearing the temporary files.");
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
            LOGGER.error("Error response at server:" + respStr);
        } catch (final IOException ioe) {
            LOGGER.info(
                    "Exception in sending the error code to client. Logged the exception for debugging:" + ioe,
                    ioe);
        }
    }
}

From source file:com.kabone.research.common.utils.FileUtil.java

/**
 * ?//  ww  w  .j av a  2 s .  c  o  m
 * @param map
 * @param realPath
 * @param dirPath
 * @param thumbnail
 * @return
 * @throws IllegalStateException
 * @throws IOException
 */
public static List<Map<String, Object>> getFileInfo(MultiValueMap<String, MultipartFile> map, String realPath,
        String dirPath, boolean thumbnail) throws IllegalStateException, IOException {

    Date time = Calendar.getInstance().getTime();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssS");
    String formatDate = formatter.format(time);

    List<Map<String, Object>> fileList = new ArrayList<Map<String, Object>>();

    Iterator<String> iterator = map.keySet().iterator();

    //  savePath ? /yyyy/mm/ ??   
    String savePath = dirPath + File.separator + StringUtils.substring(formatDate, 0, 4) + File.separator
            + StringUtils.substring(formatDate, 4, 6) + File.separator;

    String realFilePath = realPath + savePath;
    String logicalPath = savePath;

    if (File.separator.equalsIgnoreCase("\\")) {
        logicalPath = savePath.replaceAll("\\\\", "/");
    }

    while (iterator.hasNext()) {

        Map<String, Object> fileMap = new HashMap<String, Object>();

        String key = iterator.next();
        LinkedList<MultipartFile> df = (LinkedList<MultipartFile>) map.get(key);

        CommonsMultipartFile fileInfo = (CommonsMultipartFile) df.getFirst();
        if (fileInfo.getSize() > 0) {
            fileMap.put("key", key);

            int idx = fileInfo.getOriginalFilename().lastIndexOf(".");

            String extName = "";
            if (idx != -1) {
                extName = fileInfo.getOriginalFilename().substring(idx,
                        fileInfo.getOriginalFilename().length());
            }

            File fDir = new File(realFilePath);
            if (!fDir.exists()) {
                fDir.mkdirs();
            }

            File file1 = new File(realFilePath + formatDate + fileInfo.getName() + extName);
            fileInfo.transferTo(file1);

            logger.info("fileInfo.realFilePath() : " + realFilePath);
            logger.info("fileInfo.logicalPath() : " + logicalPath);
            logger.info("fileInfo.getOriginalFilename() : " + fileInfo.getOriginalFilename());
            logger.info("fileInfo.getName() : " + fileInfo.getName());
            logger.info("fileInfo.path() : " + logicalPath + formatDate + fileInfo.getName() + extName);

            fileMap.put("path", logicalPath + formatDate + fileInfo.getName() + extName);
            fileMap.put("name", fileInfo.getOriginalFilename());
            fileMap.put("size", "" + fileInfo.getSize());

            //??
            if (thumbnail) {
                int imageWidth = 0;
                int imageHeight = 0;
                //? ? ?? ?
                if ("mainImg".equals(fileInfo.getName())) {
                    logger.info("? ? ?? ?");
                    imageWidth = 645;
                    imageHeight = 485;
                } else if ("cardImg".equals(fileInfo.getName())) {
                    logger.info(" ? ?? ?");
                    imageWidth = 240;
                    imageHeight = 180;
                }

                if (imageWidth != 0 && imageHeight != 0) {
                    File originFileName = new File(realFilePath + formatDate + fileInfo.getName() + extName);
                    File thumbFileName = new File(
                            realFilePath + "thumbnail_" + formatDate + fileInfo.getName() + extName);

                    thumbnail(imageWidth, imageHeight, originFileName, thumbFileName);

                    fileMap.put("thumb",
                            logicalPath + "thumbnail_" + formatDate + fileInfo.getName() + extName);
                }
            }
            fileList.add(fileMap);
        }

    }

    return fileList;
}

From source file:com.kabone.research.common.utils.FileUtil.java

public static List<Map<String, Object>> getFileInfo2(String BUCKET_NAME, String S3_ENDPOINT, String ACCESS_KEY,
        String SECRET_KEY, MultiValueMap<String, MultipartFile> map, String realPath, String dirPath,
        boolean thumbnail) throws Exception {
    //public static List<Map<String,Object>> getFileInfo2(MultiValueMap<String, MultipartFile> map, String realPath, String dirPath, boolean thumbnail) throws Exception {

    Date time = Calendar.getInstance().getTime();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssS");
    String formatDate = formatter.format(time);

    List<Map<String, Object>> fileList = new ArrayList<Map<String, Object>>();
    Iterator<String> iterator = map.keySet().iterator();

    String savePath = dirPath + "/";

    String realFilePath = realPath + savePath;
    /*/*from  ww  w . j  av  a 2  s  .co  m*/
    String logicalPath = savePath;
            
    if(File.separator.equalsIgnoreCase("\\")) {
    logicalPath = savePath.replaceAll("\\\\", "/");
    }
    */
    File fDir = new File(realFilePath);
    if (!fDir.exists()) {
        fDir.mkdirs();
    }

    AWSUtil.s3MakeFolder(S3_ENDPOINT, BUCKET_NAME, ACCESS_KEY, SECRET_KEY, dirPath);

    while (iterator.hasNext()) {

        Map<String, Object> fileMap = new HashMap<String, Object>();

        String key = iterator.next();
        LinkedList<MultipartFile> df = (LinkedList<MultipartFile>) map.get(key);

        CommonsMultipartFile fileInfo = (CommonsMultipartFile) df.getFirst();
        if (fileInfo.getSize() > 0) {
            fileMap.put("key", key);

            int idx = fileInfo.getOriginalFilename().lastIndexOf(".");

            String extName = "";
            if (idx != -1) {
                extName = fileInfo.getOriginalFilename().substring(idx,
                        fileInfo.getOriginalFilename().length());
            }
            String fileName = formatDate + fileInfo.getName() + extName;
            File file1 = new File(realFilePath + fileName);
            fileInfo.transferTo(file1);

            logger.info("fileInfo.getOriginalFilename() : " + fileInfo.getOriginalFilename());

            String filePath = AWSUtil.s3FileUpload(S3_ENDPOINT, BUCKET_NAME, ACCESS_KEY, SECRET_KEY,
                    savePath + fileName, realFilePath + fileName);

            logger.info("filePath : " + filePath);

            fileMap.put("path", filePath);
            fileMap.put("name", fileInfo.getOriginalFilename());
            fileMap.put("size", "" + fileInfo.getSize());

            //??
            if (thumbnail) {
                int imageWidth = 0;
                int imageHeight = 0;
                //? ? ?? ?
                if ("mainImg".equals(fileInfo.getName())) {
                    //??
                    imageWidth = 645;
                    imageHeight = 485;
                } else if ("cardImg".equals(fileInfo.getName())) {
                    //?
                    imageWidth = 224;
                    imageHeight = 180;
                } else if ("storyImg".equals(fileInfo.getName())) {
                    //
                    imageWidth = 148;
                    imageHeight = 98;
                } else if ("ftypeMainImg".equals(fileInfo.getName())) {
                    // ??
                    imageWidth = 980;
                    imageHeight = 400;
                } else if ("choiceImg".equals(fileInfo.getName())) {
                    // Editor's Choice ?
                    imageWidth = 160;
                    imageHeight = 70;
                }

                if (imageWidth != 0 && imageHeight != 0) {
                    File originFileName = new File(realFilePath + fileName);
                    File thumbFileName = new File(realFilePath + "thumbnail_" + fileName);

                    boolean result = thumbnail(imageWidth, imageHeight, originFileName, thumbFileName);
                    String filePath2 = "";
                    if (result) {
                        filePath2 = AWSUtil.s3FileUpload(S3_ENDPOINT, BUCKET_NAME, ACCESS_KEY, SECRET_KEY,
                                savePath + "thumbnail_" + fileName, realFilePath + "thumbnail_" + fileName);
                    }

                    if (thumbFileName.exists()) {
                        thumbFileName.delete();
                    }

                    fileMap.put("thumbPath", filePath2);
                }
            }

            if (file1.exists()) {
                file1.delete();
            }

            fileList.add(fileMap);
        }

    }

    return fileList;
}

From source file:eionet.webq.web.controller.cdr.IntegrationWithCDRController.java

/**
 * Deliver with WebForms.// w w w.  j  a va2  s  . co  m
 *
 * @param request parameters of this action
 * @param model   model
 * @return view name
 * @throws eionet.webq.service.FileNotAvailableException if one redirect to xform remote file not found.
 */
@RequestMapping("/WebQMenu")
public String webQMenu(HttpServletRequest request, Model model) throws FileNotAvailableException {
    CdrRequest parameters = convertAndPutResultIntoSession(request);

    LOGGER.info("Received WebQMenu request with parameters:" + parameters.toString());

    // For local tests
    //MultiValueMap<String, XmlFile> xmlFiles = new LinkedMultiValueMap<>();
    MultiValueMap<String, XmlFile> xmlFiles = envelopeService.getXmlFiles(parameters);
    Collection<String> requiredSchemas = StringUtils.isNotEmpty(parameters.getSchema())
            ? Arrays.asList(parameters.getSchema())
            : xmlFiles.keySet();
    Collection<ProjectFile> webForms = webFormService.findWebFormsForSchemas(requiredSchemas);
    if (webForms.isEmpty()) {
        throw new IllegalArgumentException("no web forms available.");
    }
    if (hasOnlyOneFileAndWebFormForSameSchema(xmlFiles, webForms, parameters)) {
        return redirectToEditWebForm(parameters, xmlFiles, webForms);
    }
    if (oneWebFormAndNoFilesButNewFileCreationIsAllowed(xmlFiles, webForms, parameters)) {
        return startNewForm(parameters, webForms.iterator().next());
    }
    return deliverMenu(webForms, xmlFiles, parameters, model);
}