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

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

Introduction

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

Prototype

@Override
InputStream getInputStream() throws IOException;

Source Link

Document

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

Usage

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

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

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

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

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

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

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

                    String rspProjectFile = workingDir + File.separator + projectFile;

                    File rspFile = new File(rspProjectFile);

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

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

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

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

        }
    }
}

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

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

        InputStream instream = null;
        OutputStream outStream = null;

        final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;

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

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

        if (respStr.isEmpty()) {
            for (final String fileName : fileMap.keySet()) {
                if (fileName.endsWith(FileType.XML.getExtensionWithDot())) {
                    xmlFileName = fileName;
                }

                final MultipartFile multiPartFile = multiPartRequest.getFile(fileName);
                instream = multiPartFile.getInputStream();
                final File file = new File(workingDir + File.separator + fileName);
                outStream = new FileOutputStream(file);
                final byte[] buf = new byte[WebServiceUtil.bufferSize];
                int len;
                while ((len = instream.read(buf)) > 0) {
                    outStream.write(buf, 0, len);
                }
                if (instream != null) {
                    instream.close();
                }

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

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

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

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

                        List<Param> paramList = null;

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

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

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

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

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

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

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

        }
    }
}

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

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

            InputStream instream = null;
            OutputStream outStream = null;

            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;

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

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

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

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

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

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

            }

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

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

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

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

        }
    }
}

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

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

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

            InputStream instream = null;
            OutputStream outStream = null;

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

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

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

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

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

                            final MultipartFile f = multipartReq.getFile(fileName);
                            instream = f.getInputStream();
                            final File file = new File(workingDir + File.separator + fileName);
                            outStream = new FileOutputStream(file);
                            final byte buf[] = new byte[1024];
                            int len;
                            while ((len = instream.read(buf)) > 0) {
                                outStream.write(buf, 0, len);
                            }
                            if (instream != null) {
                                instream.close();
                            }

                            if (outStream != null) {
                                outStream.close();
                            }
                            if (TIFFUtil.getTIFFPageCount(file.getAbsolutePath()) > 1) {
                                respStr = "Improper input to server. Expected only one single page tiff file. Returning without processing the results.";
                            }
                            break;
                        } else {
                            respStr = "Improper input to server. Expected only one tiff file. Returning without processing the results.";
                        }
                    }
                    if (respStr.isEmpty()) {

                        String compareThumbnailH = batchClassPPService.getPropertyValue(batchClassId,
                                ImageMagicKConstants.CREATE_THUMBNAILS_PLUGIN,
                                ImageMagicProperties.CREATE_THUMBNAILS_COMP_THUMB_HEIGHT);
                        String compareThumbnailW = batchClassPPService.getPropertyValue(batchClassId,
                                ImageMagicKConstants.CREATE_THUMBNAILS_PLUGIN,
                                ImageMagicProperties.CREATE_THUMBNAILS_COMP_THUMB_WIDTH);

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

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

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

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

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

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

        }
    }
}

From source file:com.siblinks.ws.service.impl.UploadEssayServiceImpl.java

/**
 * {@inheritDoc}/*from   w  ww  .  j av  a 2 s. c o m*/
 */
@Override
@RequestMapping(value = "/updateEssayStudent", method = RequestMethod.POST)
public ResponseEntity<Response> updateEssayStudent(@RequestParam("essayId") final String essayId,
        @RequestParam("desc") final String desc, @RequestParam("userId") final String userId,
        @RequestParam(required = false) final String fileName, @RequestParam("title") final String title,
        @RequestParam("schoolId") final String schoolId, @RequestParam("majorId") final String majorId,
        @RequestParam(required = false) final MultipartFile file) {
    SimpleResponse simpleResponse = null;
    String statusMessage = "";
    try {

        if (!AuthenticationFilter.isAuthed(context)) {
            simpleResponse = new SimpleResponse(SibConstants.FAILURE, "Authentication required.");
            return new ResponseEntity<Response>(simpleResponse, HttpStatus.FORBIDDEN);
        }

        if (StringUtil.isNull(desc)) {
            statusMessage = "Essay description can't blank!";
        } else {
            if (desc.length() > 1000) {
                statusMessage = "Essay description can't over 1000 characters!";
            }
        }

        if (StringUtil.isNull(title)) {
            statusMessage = "Essay title can't blank!";
        } else {
            if (title.length() > 250) {
                statusMessage = "Essay title can't over 250 characters!";
            }
        }
        if (StringUtil.isNull(essayId)) {
            statusMessage = "EssayId null!";
        }
        boolean msgs = false;
        if (StringUtil.isNull(statusMessage)) {
            List<Map<String, String>> allWordFilter = cachedDao.getAllWordFilter();
            String strContent = CommonUtil.filterWord(desc, allWordFilter);
            String strTitle = CommonUtil.filterWord(title, allWordFilter);
            String strFileName = CommonUtil.filterWord(fileName, allWordFilter);

            if (validateEssay(file).equals("File is empty")) {
                Object[] queryParams = { strContent, strTitle, schoolId, majorId, essayId };
                msgs = dao.insertUpdateObject(SibConstants.SqlMapper.SQL_STUDENT_UPDATE_ESSAY_NOFILE,
                        queryParams);
            } else {
                Object[] queryParams = { file.getInputStream(), strContent, file.getContentType(), strFileName,
                        strTitle, file.getSize(), schoolId, majorId, essayId };
                msgs = dao.insertUpdateObject(SibConstants.SqlMapper.SQL_STUDENT_UPDATE_ESSAY, queryParams);
            }
            if (msgs) {
                statusMessage = "You updated successfull essay.";
            } else {
                statusMessage = "This essay is already not exist.";
            }

        }
        simpleResponse = new SimpleResponse("" + msgs, "essay", "upload", statusMessage);

    } catch (Exception e) {
        e.printStackTrace();
        simpleResponse = new SimpleResponse(SibConstants.FAILURE, "essay", "upload", e.getMessage());
    }

    return new ResponseEntity<Response>(simpleResponse, HttpStatus.OK);
}

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

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

            InputStream instream = null;
            OutputStream outStream = null;

            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;

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

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

            if (!(fileMap.size() >= 2 && fileMap.size() <= 3)) {
                respStr = "Invalid number of files. We are supposed only 3 files.";
            }
            if (respStr.isEmpty()) {
                String xmlFileName = WebServiceUtil.EMPTY_STRING;
                for (final String fileName : fileMap.keySet()) {
                    if (fileName.endsWith(FileType.XML.getExtensionWithDot())) {
                        xmlFileName = fileName;
                    }
                    final MultipartFile multiPartFile = multiPartRequest.getFile(fileName);
                    instream = multiPartFile.getInputStream();
                    final File file = new File(workingDir + File.separator + fileName);
                    outStream = new FileOutputStream(file);
                    final byte[] buf = new byte[WebServiceUtil.bufferSize];
                    int len;
                    while ((len = instream.read(buf)) > 0) {
                        outStream.write(buf, 0, len);
                    }
                    if (instream != null) {
                        instream.close();
                    }

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

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

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

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

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

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

        }
    }
}

From source file:cn.edu.henu.rjxy.lms.controller.TeaController.java

@RequestMapping("teacher/homework_submit")
public @ResponseBody String homework_submit(HttpServletRequest request,
        @RequestParam("file") MultipartFile file) throws FileNotFoundException, IOException {
    int length = 0;
    String textWork = request.getParameter("arr1");//?
    String time = request.getParameter("time");//??
    String miaoshu = request.getParameter("miaoshu");
    String coursename = request.getParameter("courseName");
    String term = request.getParameter("term");
    String tec_name = TeacherDao.getTeacherBySn(getCurrentUsername()).getTeacherName();
    String sn = getCurrentUsername();
    String collage = TeacherDao.getTeacherBySn(getCurrentUsername()).getTeacherCollege();
    //                                      ?   ??          ??
    String ff = getFileFolder(request) + "homework/" + term + "/" + collage + "/" + sn + "/" + tec_name + "/"
            + coursename + "/";
    file(ff);//??
    length = haveFile(ff);/*from  w  w  w .j  a v a2 s.co  m*/
    ff = ff + (length + 1) + "/";
    file(ff);
    //?html
    OutputStreamWriter pw = null;//?
    pw = new OutputStreamWriter(new FileOutputStream(new File(ff + File.separator + "textWork.html")), "GBK");
    pw.write(textWork);
    pw.close();
    //??
    PrintStream ps = null;
    ps = new PrintStream(new FileOutputStream(new File(ff + File.separator + "Workall.txt")));
    ps.printf(miaoshu);//??:
    ps.println();
    ;
    ps.println(time);//??:
    ps.close();
    //
    if (!file.isEmpty()) {
        try {
            InputStream in;
            try (FileOutputStream os = new FileOutputStream(ff + "/" + file.getOriginalFilename())) {
                in = file.getInputStream();
                int b = 0;
                while ((b = in.read()) != -1) {
                    os.write(b);
                }
                os.flush();
            }
            in.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block  
            e.printStackTrace();
        }
    }
    return "1";
}

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

@RequestMapping(value = "/classifyHocr", method = RequestMethod.POST)
@ResponseBody/*from w  w  w  .ja  v a2  s .  co m*/
public void classifyHocr(final HttpServletRequest req, final HttpServletResponse resp) {
    logger.info("Start processing web service for classifyHocr.");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;

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

            InputStream instream = null;
            OutputStream outStream = null;

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

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

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

                if (fileMap.size() == 1) {
                    String hocrFileName = "";
                    for (final String fileName : fileMap.keySet()) {
                        // only single html file is expected as input
                        if (fileName.toLowerCase().indexOf(FileType.HTML.getExtension()) > -1) {
                            // only HTML file is expected
                            hocrFileName = fileName;
                            final MultipartFile f = multipartReq.getFile(fileName);
                            instream = f.getInputStream();
                            final File file = new File(workingDir + File.separator + fileName);
                            outStream = new FileOutputStream(file);
                            final byte buf[] = new byte[1024];
                            int len;
                            while ((len = instream.read(buf)) > 0) {
                                outStream.write(buf, 0, len);
                            }
                            if (instream != null) {
                                instream.close();
                            }

                            if (outStream != null) {
                                outStream.close();
                            }
                            break;
                        } else {
                            respStr = "Improper input to server. Expected only one html file. Returning without processing the results.";
                        }
                    }
                    if (respStr.isEmpty()) {
                        ObjectFactory objectFactory = new ObjectFactory();

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

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

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

                        try {
                            // invoke the document assembler plugin
                            xmlDocuments = docAssembler.createDocumentAPI(
                                    DocumentClassificationFactory.SEARCHCLASSIFICATION, batchClassId,
                                    listOfPages);
                            Documents docs = new Documents();
                            docs.getDocument().addAll(xmlDocuments);
                            StreamResult result;
                            try {
                                result = new StreamResult(resp.getOutputStream());
                                resp.setStatus(HttpServletResponse.SC_OK);
                                batchSchemaDao.getJAXB2Template().getJaxb2Marshaller().marshal(docs, result);
                            } catch (final IOException e) {
                                respStr = "Internal Server error.Please check logs for further details." + e;
                            }
                        } catch (final DCMAApplicationException e) {
                            respStr = "Error while executing plugin. Detailed exception is " + e;
                        }
                    }
                } else {
                    respStr = "Improper input to server. Expected only one html file. Returning without processing the results.";
                }
            }
        } catch (final XmlMappingException xmle) {
            respStr = "Error in mapping input XML in the desired format. Please send it in the specified format. Detailed exception is "
                    + xmle;
        } catch (final DCMAException dcmae) {
            respStr = "Error in processing request. Detailed exception is " + dcmae;
        } catch (final Exception e) {
            respStr = "Internal Server error.Please check logs for further details." + e;
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        }
    } else {
        respStr = "Improper input to server. Expected multipart request. Returing without processing the results.";
    }

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

        }
    }
}

From source file:com.prcsteel.platform.account.service.impl.AccountServiceImpl.java

@Override
@Transactional//  w w  w . j a  v a 2s  .com
public HashMap<String, Object> insert(AccountDto record, List<MultipartFile> attachments,
        AccountContact contact) throws BusinessException {
    HashMap<String, Object> result = new HashMap<String, Object>();
    Account account = record.getAccount();
    String accountCode = account.getAccountCode();
    if (accountCode != null && !"".equals(accountCode.replaceAll(" ", ""))) {
        // ??
        AccountBank accountBank = accountBankDao.selectByAccountCode(StringToReplace.toReplaceAll(accountCode));
        if (accountBank != null) {
            throw new BusinessException(Constant.EXCEPTIONCODE_BUSINESS,
                    "??" + accountCode.substring(accountCode.length() - 4)
                            + "???"
                            + accountDao.selectByPrimaryKey(accountBank.getAccountId()).getName()
                            + "??" + userDao.queryByLoginId("chenhu").getTel()
                            + "?");
        }
    }
    User user = record.getManager();
    account.setManagerId(user.getId());
    account.setCreatedBy(user.getLoginId());
    account.setLastUpdatedBy(user.getLoginId());
    account.setRegTime(new Date());
    account.setCode(getCode());
    if (StringUtils.isEmpty(account.getBusinessType())) {
        account.setBusinessType(null);
    }
    accountDao.insertSelective(account);
    Long accountId = account.getId();
    // ??????? modify by kongbinheng 20150803
    if (accountCode != null && !"".equals(accountCode.replaceAll(" ", ""))) {
        AccountBank accountBank = accountBankDao.selectByAccountCode(StringToReplace.toReplaceAll(accountCode));
        if (accountBank == null) {
            accountBank = new AccountBank();
            accountBank.setAccountId(accountId); // ?ID
            accountBank.setBankCode(StringToReplace.toReplaceAll(account.getBankCode())); // ?
            accountBank.setBankName(StringToReplace.toReplaceAll(account.getBankNameMain())); // 
            accountBank.setBankNameBranch(StringToReplace.toReplaceAll(account.getBankNameBranch())); // 
            accountBank.setBankProvinceId(account.getBankProvinceId());
            accountBank.setBankCityId(account.getBankCityId());
            if (account.getBankProvinceId() != null)
                accountBank.setBankProvinceName(
                        provinceDao.selectByPrimaryKey(account.getBankProvinceId()).getName());
            if (account.getBankCityId() != null)
                accountBank.setBankCityName(cityDao.selectByPrimaryKey(account.getBankCityId()).getName());
            accountBank.setBankAccountCode(StringToReplace.toReplaceAll(accountCode)); // ?
            accountBank.setCreated(new Date());
            accountBank.setCreatedBy(user.getLoginId());
            accountBank.setLastUpdated(new Date());
            accountBank.setLastUpdatedBy(user.getLoginId());
            accountBank.setModificationNumber(0);
            accountBankDao.insertSelective(accountBank);
        } else {
            if (accountId.equals(accountBank.getAccountId())) {
                accountBank.setBankCode(StringToReplace.toReplaceAll(account.getBankCode())); // ?
                accountBank.setBankName(StringToReplace.toReplaceAll(account.getBankNameMain())); // 
                accountBank.setBankNameBranch(StringToReplace.toReplaceAll(account.getBankNameBranch())); // 
                accountBankDao.updateByPrimaryKeySelective(accountBank);
            } else {

            }
        }
    }

    // String basePath = rootPath + ATTACHMENTSAVEPATH + account.getCode()
    // + File.separator;
    boolean hasTaxReg = false;
    boolean hasInvoiceData = false;
    boolean hasPaymentData = false;//
    boolean hasOpenAccountLicense = false;//??
    if (attachments != null) {
        for (MultipartFile file : attachments) {
            if ("pic_tax_reg".equals(file.getName())) {
                hasTaxReg = true;
            } else if ("pic_invoice_data".equals(file.getName())) {
                hasInvoiceData = true;
            } else if ("pic_payment_data".equals(file.getName())) {
                hasPaymentData = true;
            } else if ("pic_open_account_license".equals(file.getName())) {
                hasOpenAccountLicense = true;
            }
            AccountAttachment accountAttachment = new AccountAttachment();
            accountAttachment.setCreatedBy(user.getLoginId());
            accountAttachment.setLastUpdatedBy(user.getLoginId());
            accountAttachment.setAccountId(accountId);
            AttachmentType type = AttachmentType.valueOf(file.getName());
            accountAttachment.setType(type.getCode());
            // String savePath = basePath + type.getCode() + "."
            // + FileUtil.getFileSuffix(file.getOriginalFilename());
            // FileUtil.saveFile(file, savePath);
            String saveKey = "";
            try {
                saveKey = fileService.saveFile(file.getInputStream(),
                        ATTACHMENTSAVEPATH + account.getCode() + File.separator + type.getCode() + "."
                                + FileUtil.getFileSuffix(file.getOriginalFilename()));
            } catch (IOException e) {
                BusinessException be = new BusinessException(Constant.EXCEPTIONCODE_SYSTEM,
                        "?" + AttachmentType.valueOf(file.getName()) + "");
                throw be;
            }
            accountAttachment.setUrl(saveKey);
            aamDao.insertSelective(accountAttachment);

        }
    }
    if (hasTaxReg || hasInvoiceData) {
        accountDao.updateInvoiceDataStatusByPrimaryKey(account.getId(), InvoiceDataStatus.Requested.getCode(),
                null, user.getLoginId());// 
    } else {
        accountDao.updateInvoiceDataStatusByPrimaryKey(account.getId(),
                InvoiceDataStatus.Insufficient.getCode(), null, user.getLoginId());// ?
    }
    // ??
    if (hasPaymentData || hasOpenAccountLicense) {
        accountDao.updateBankDataStatusByPrimaryKey(account.getId(), AccountBankDataStatus.Requested.getCode(),
                null, null, user.getLoginId());
    } else {
        accountDao.updateBankDataStatusByPrimaryKey(account.getId(),
                AccountBankDataStatus.Insufficient.getCode(), null, null, user.getLoginId());
    }

    accountDao.updateByPrimaryKeySelective(account);

    insertAccountContact(contact, accountId, user);

    result.put("success", true);
    result.put("data", accountId);

    return result;
}

From source file:com.ut.healthelink.service.impl.transactionInManagerImpl.java

@Override
public String copyUplaodedPath(configurationTransport transportDetails, MultipartFile fileUpload) {

    //save the file as is to input folder
    MultipartFile file = fileUpload;
    String fileName = file.getOriginalFilename();

    InputStream inputStream;/* w  ww .  j  a va2s . c  om*/
    OutputStream outputStream;

    try {
        inputStream = file.getInputStream();
        File newFile = null;

        //Set the directory to save the brochures to
        fileSystem dir = new fileSystem();

        String filelocation = transportDetails.getfileLocation();
        filelocation = filelocation.replace("/bowlink/", "");
        dir.setDirByName(filelocation);

        newFile = new File(dir.getDir() + fileName);

        if (newFile.exists()) {
            int i = 1;
            while (newFile.exists()) {
                int iDot = fileName.lastIndexOf(".");
                newFile = new File(dir.getDir() + fileName.substring(0, iDot) + "_(" + ++i + ")"
                        + fileName.substring(iDot));
            }
            fileName = newFile.getName();
            newFile.createNewFile();
        } else {
            newFile.createNewFile();
        }

        //Save the attachment
        outputStream = new FileOutputStream(newFile);
        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }
        outputStream.close();

        return fileName;
    } catch (IOException e) {
        System.err.println("copyUplaodedPath " + e.getCause());
        e.printStackTrace();
        return null;
    }
}