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

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

Introduction

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

Prototype

@Override
    public MultipartFile getFile(String name) 

Source Link

Usage

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

@RequestMapping(value = "/classifyImage", method = RequestMethod.POST)
@ResponseBody//from   w w  w  .ja v a2s  .  c om
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.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

/**
 * To extract From Image./*from  w  ww  .j  av  a 2 s  . com*/
 * @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.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

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

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

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

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

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

                }
                for (final String fileName : fileMap.keySet()) {
                    if (fileName.toLowerCase(Locale.getDefault())
                            .indexOf(FileType.PDF.getExtension()) > -WebserviceConstants.ONE
                            || fileName.toLowerCase(Locale.getDefault())
                                    .indexOf(FileType.TIF.getExtension()) > -WebserviceConstants.ONE
                            || fileName.toLowerCase(Locale.getDefault())
                                    .indexOf(FileType.TIFF.getExtension()) > -WebserviceConstants.ONE) {
                        // only tiffs and RSP file is expected
                        if (isGSTool && (fileName.toLowerCase(Locale.getDefault())
                                .indexOf(FileType.TIF.getExtension()) > -WebserviceConstants.ONE
                                || fileName.toLowerCase(Locale.getDefault())
                                        .indexOf(FileType.TIFF.getExtension()) > -WebserviceConstants.ONE)) {
                            respStr = "Only PDF files expected with GhostScript tool.";
                            LOGGER.error(SERVER_ERROR_MSG + respStr);
                            break;
                        }
                        try {
                            final MultipartFile multiPartFile = multiPartRequest.getFile(fileName);
                            instream = multiPartFile.getInputStream();
                            final File file = new File(workingDir + File.separator + fileName);
                            outStream = new FileOutputStream(file);
                            final byte[] buf = new byte[WebServiceUtil.bufferSize];
                            int len = instream.read(buf);
                            while (len > WebserviceConstants.ZERO) {
                                outStream.write(buf, WebserviceConstants.ZERO, len);
                                len = instream.read(buf);
                            }
                        } finally {
                            IOUtils.closeQuietly(instream);
                            IOUtils.closeQuietly(outStream);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@RequestMapping(value = "/classifyHocr", method = RequestMethod.POST)
@ResponseBody/*from www  . j  a v  a2 s .com*/
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.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:org.openflamingo.web.fs.HdfsBrowserController.java

/**
 * ?? .// w  ww. j  a  va  2  s  .c  o m
 *
 * @return REST Response JAXB Object
 */
@RequestMapping(value = "upload", method = RequestMethod.POST, consumes = { "multipart/form-data" })
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ResponseEntity<String> upload(HttpServletRequest req) throws IOException {
    Response response = new Response();
    if (!(req instanceof DefaultMultipartHttpServletRequest)) {
        response.setSuccess(false);
        response.getError().setCause(message("S_FS_SERVICE", "CANNOT_UPLOAD_INVALID", null));
        response.getError().setMessage(message("S_FS_SERVICE", "CANNOT_UPLOAD", null));
        String json = new ObjectMapper().writeValueAsString(response);
        return new ResponseEntity(json, HttpStatus.BAD_REQUEST);
    }

    InputStream inputStream = null;
    try {
        DefaultMultipartHttpServletRequest request = (DefaultMultipartHttpServletRequest) req;
        String pathToUpload = request.getParameter("path");
        String engineId = req.getParameter("engineId");
        MultipartFile uploadedFile = request.getFile("file");
        String originalFilename = uploadedFile.getOriginalFilename();
        String fullyQualifiedPath = pathToUpload.equals("/") ? pathToUpload + originalFilename
                : pathToUpload + FILE_SEPARATOR + originalFilename;
        inputStream = uploadedFile.getInputStream();
        byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);

        Engine engine = engineService.getEngine(Long.parseLong(engineId));
        FileSystemService fileSystemService = (FileSystemService) lookupService.getService(RemoteService.HDFS,
                engine);

        Context context = getContext(engine);
        String forbiddenPaths = ConfigurationManager.getConfigurationManager()
                .get("hdfs.delete.forbidden.paths", DEFAULT_FORBIDDEN_PATH);
        context.putString("hdfs.delete.forbidden.paths", forbiddenPaths);

        FileSystemCommand command = new FileSystemCommand();
        command.putString("path", fullyQualifiedPath);
        command.putObject("content", bytes);

        boolean file = fileSystemService.save(context, command);
        response.setSuccess(file);
        response.getMap().put("directory", pathToUpload);

        String json = new ObjectMapper().writeValueAsString(response);
        return new ResponseEntity(json, HttpStatus.OK);
    } catch (Exception ex) {
        response.setSuccess(false);
        response.getError().setMessage(ex.getMessage());
        if (ex.getCause() != null)
            response.getError().setCause(ex.getCause().getMessage());
        response.getError().setException(ExceptionUtils.getFullStackTrace(ex));

        String json = new ObjectMapper().writeValueAsString(response);
        return new ResponseEntity(json, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.wise.portal.presentation.web.controllers.author.project.AuthorProjectController.java

@RequestMapping("/author/authorproject.html")
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    User user = ControllerUtil.getSignedInUser();

    String projectIdStr = request.getParameter(PROJECT_ID_PARAM_NAME);
    String forward = request.getParameter(FORWARD);

    Project project;/*w  w  w  . j a  va 2 s  .  c o  m*/
    if (projectIdStr != null && !projectIdStr.equals("") && !projectIdStr.equals("none")) {
        //project = projectService.getProjectWithoutMetadata(Long.parseLong(projectIdStr));
        project = projectService.getById(Long.parseLong(projectIdStr));
    } else {
        project = null;
    }

    /* catch forwarding requests, authenticate and forward request upon successful authentication */
    if (forward != null && !forward.equals("")) {
        //get the command
        String command = request.getParameter("command");

        if (forward.equals("filemanager") || forward.equals("assetmanager")) {

            if ((this.isProjectlessRequest(request, forward)
                    || this.projectService.canAuthorProject(project, user))
                    || ("copyProject".equals(command) && project.getFamilytag().equals(FamilyTag.TELS))
                    || ("retrieveFile".equals(command) && project.getFamilytag().equals(FamilyTag.TELS))) {

                if ("createProject".equals(command) && !this.hasAuthorPermissions(user)) {
                    return new ModelAndView(new RedirectView("accessdenied.html"));
                }

                if ("copyProject".equals(command)
                        && (project == null || (!project.getFamilytag().equals(FamilyTag.TELS)
                                && !this.projectService.canAuthorProject(project, user)))) {
                    return new ModelAndView(new RedirectView("accessdenied.html"));
                }

                CredentialManager.setRequestCredentials(request, user);

                if (forward.equals("filemanager")) {
                    if (command != null) {
                        String pathAllowedToAccess = CredentialManager.getAllowedPathAccess(request);

                        if (command.equals("createProject")) {
                            String projectName = request.getParameter("projectName");
                            String curriculumBaseDir = wiseProperties.getProperty("curriculum_base_dir");

                            String result = "";

                            if (SecurityUtils.isAllowedAccess(pathAllowedToAccess, curriculumBaseDir)) {
                                result = FileManager.createProject(curriculumBaseDir, projectName);
                            } else {
                                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                                result = "unauthorized";
                            }

                            response.getWriter().write(result);
                        } else if (command.equals("projectList")) {
                            String projectPaths = request.getParameter("projectPaths");
                            String projectExt = ".project.json";

                            String result = FileManager.getProjectList(projectPaths, projectExt);

                            response.getWriter().write(result);
                        } else if (command.equals("retrieveFile")) {
                            //get the file name
                            String fileName = request.getParameter("fileName");

                            //get the full file path
                            String filePath = FileManager.getFilePath(project, fileName);

                            String result = "";

                            if (SecurityUtils.isAllowedAccess(pathAllowedToAccess, filePath)) {
                                result = FileManager.retrieveFile(filePath);
                            } else {
                                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                                result = "unauthorized";
                            }

                            response.getWriter().write(result);
                        } else if (command.equals("updateFile")) {
                            /*
                             * get the project folder path
                             * e.g.
                             * /Users/geoffreykwan/dev/apache-tomcat-5.5.27/webapps/curriculum/667
                             */
                            String projectFolderPath = FileManager.getProjectFolderPath(project);

                            //get the file name
                            String fileName = request.getParameter("fileName");

                            //get the content to save to the file
                            String data = request.getParameter("data");

                            String result = "";

                            if (SecurityUtils.isAllowedAccess(pathAllowedToAccess, projectFolderPath)) {
                                result = FileManager.updateFile(projectFolderPath, fileName, data);
                            } else {
                                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                                result = "unauthorized";
                            }

                            response.getWriter().write(result);
                        } else if (command.equals("createNode")) {
                            /*
                             * get the project file path
                             * e.g.
                             * /Users/geoffreykwan/dev/apache-tomcat-5.5.27/webapps/curriculum/667/wise4.project.json
                             */
                            String projectPath = FileManager.getProjectFilePath(project);
                            String nodeClass = request.getParameter("nodeClass");
                            String title = request.getParameter("title");
                            String type = request.getParameter("type");

                            //get the string that contains an array of node template params
                            String nodeTemplateParams = request.getParameter("nodeTemplateParams");

                            String result = "";

                            if (SecurityUtils.isAllowedAccess(pathAllowedToAccess, projectPath)) {
                                result = FileManager.createNode(projectPath, nodeClass, title, type,
                                        nodeTemplateParams);
                            } else {
                                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                                result = "not authorized";
                            }

                            response.getWriter().write(result);
                        } else if (command.equals("createSequence")) {
                            /*
                             * get the project file name
                             * e.g.
                             * /wise4.project.json
                             */
                            String projectFileName = request.getParameter("projectFileName");
                            String name = request.getParameter("name");
                            String id = request.getParameter("id");

                            /*
                             * get the project folder path
                             * e.g.
                             * /Users/geoffreykwan/dev/apache-tomcat-5.5.27/webapps/curriculum/667
                             */
                            String projectFolderPath = FileManager.getProjectFolderPath(project);

                            String result = "";

                            if (SecurityUtils.isAllowedAccess(pathAllowedToAccess, projectFolderPath)) {
                                result = FileManager.createSequence(projectFileName, name, id,
                                        projectFolderPath);
                            } else {
                                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                                result = "not authorized";
                            }

                            response.getWriter().write(result);
                        } else if (command.equals("removeFile")) {
                            /*
                             * get the project folder path
                             * e.g.
                             * /Users/geoffreykwan/dev/apache-tomcat-5.5.27/webapps/curriculum/667
                             */
                            String projectFolderPath = FileManager.getProjectFolderPath(project);

                            /*
                             * get the file name
                             * node_1.or
                             */
                            String fileName = request.getParameter("fileName");

                            String result = "";

                            if (SecurityUtils.isAllowedAccess(pathAllowedToAccess, projectFolderPath)) {
                                result = FileManager.removeFile(projectFolderPath, fileName);
                            } else {
                                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                                result = "unauthorized";
                            }

                            response.getWriter().write(result);
                        } else if (command.equals("copyNode")) {
                            //get the parameters for the node
                            String data = request.getParameter("data");
                            String type = request.getParameter("type");
                            String title = request.getParameter("title");
                            String nodeClass = request.getParameter("nodeClass");
                            String contentFile = request.getParameter("contentFile");

                            /*
                             * get the file name
                             * e.g.
                             * /node_1.or
                             */
                            String projectFileName = request.getParameter("projectFileName");

                            /*
                             * get the project folder path
                             * e.g.
                             * /Users/geoffreykwan/dev/apache-tomcat-5.5.27/webapps/curriculum/667
                             */
                            String projectFolderPath = FileManager.getProjectFolderPath(project);

                            String result = "";

                            if (SecurityUtils.isAllowedAccess(pathAllowedToAccess, projectFolderPath)) {
                                result = FileManager.copyNode(projectFolderPath, projectFileName, data, type,
                                        title, nodeClass, contentFile);
                            } else {
                                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                            }

                            response.getWriter().write(result);
                        } else if (command.equals("createSequenceFromJSON")) {
                            /*
                             * get the project file name
                             * e.g.
                             * /wise4.project.json
                             */
                            String projectFileName = request.getParameter("projectFileName");

                            //get the json for the new sequence we are going to add to the project
                            String data = request.getParameter("data");

                            /*
                             * get the project folder path
                             * e.g.
                             * /Users/geoffreykwan/dev/apache-tomcat-5.5.27/webapps/curriculum/667
                             */
                            String projectFolderPath = FileManager.getProjectFolderPath(project);

                            String result = "";

                            if (SecurityUtils.isAllowedAccess(pathAllowedToAccess, projectFolderPath)) {
                                result = FileManager.createSequenceFromJSON(projectFolderPath, projectFileName,
                                        data);
                            } else {
                                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                            }

                            response.getWriter().write(result);
                        } else if (command.equals("getScripts")) {
                            String data = request.getParameter("param1");

                            String result = FileManager.getScripts(servletContext, data);

                            response.getWriter().write(result);
                        } else if (command.equals("copyProject")) {
                            /*
                             * get the project folder path
                             * e.g.
                             * /Users/geoffreykwan/dev/apache-tomcat-5.5.27/webapps/curriculum/667
                             */
                            String projectFolderPath = FileManager.getProjectFolderPath(project);

                            /*
                             * get the curriculum base
                             * e.g.
                             * /Users/geoffreykwan/dev/apache-tomcat-5.5.27/webapps/curriculum
                             */
                            String curriculumBaseDir = wiseProperties.getProperty("curriculum_base_dir");

                            String result = "";

                            if (SecurityUtils.isAllowedAccess(pathAllowedToAccess, projectFolderPath)) {
                                result = FileManager.copyProject(curriculumBaseDir, projectFolderPath);
                            } else {
                                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                                result = "unauthorized";
                            }

                            response.getWriter().write(result);
                        } else if (command.equals("createFile")) {
                            /*
                             * get the file name
                             * e.g.
                             * /node_1.or
                             */
                            String fileName = request.getParameter("path");
                            String data = request.getParameter("data");

                            /*
                             * get the project folder path
                             * e.g.
                             * /Users/geoffreykwan/dev/apache-tomcat-5.5.27/webapps/curriculum/667
                             */
                            String projectFolderPath = FileManager.getProjectFolderPath(project);

                            String result = "";

                            if (SecurityUtils.isAllowedAccess(pathAllowedToAccess, projectFolderPath)) {
                                result = FileManager.createFile(projectFolderPath, fileName, data);
                            } else {
                                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                            }

                            response.getWriter().write(result);
                        } else if (command.equals("reviewUpdateProject")) {
                            //get the curriculum base directory e.g. /Users/geoffreykwan/dev/apache-tomcat-5.5.27/webapps/curriculum
                            String curriculumBaseDir = wiseProperties.getProperty("curriculum_base_dir");

                            //get the relative child project url e.g. /236/wise4.project.json
                            String projectUrl = (String) project.getCurnit()
                                    .accept(new CurnitGetCurnitUrlVisitor());

                            //get the parent project id
                            Long parentProjectId = project.getParentProjectId();

                            //get the parent project
                            Project parentProject = projectService.getById(parentProjectId);

                            //get the relative parent project url e.g. /235/wise4.project.json
                            String parentProjectUrl = (String) parentProject.getCurnit()
                                    .accept(new CurnitGetCurnitUrlVisitor());

                            String result = FileManager.reviewUpdateProject(curriculumBaseDir, parentProjectUrl,
                                    projectUrl);

                            response.getWriter().write(result);
                        } else if (command.equals("updateProject")) {
                            //get the curriculum base directory e.g. /Users/geoffreykwan/dev/apache-tomcat-5.5.27/webapps/curriculum
                            String curriculumBaseDir = wiseProperties.getProperty("curriculum_base_dir");

                            //get the relative child project url e.g. /236/wise4.project.json
                            String childProjectUrl = (String) project.getCurnit()
                                    .accept(new CurnitGetCurnitUrlVisitor());

                            //get the child project folder path
                            String childProjectFolderPath = FileManager.getProjectFolderPath(project);

                            //get the parent project id
                            Long parentProjectId = project.getParentProjectId();

                            //get the parent project
                            Project parentProject = projectService.getById(parentProjectId);

                            //get the relative parent project url e.g. /235/wise4.project.json
                            String parentProjectUrl = (String) parentProject.getCurnit()
                                    .accept(new CurnitGetCurnitUrlVisitor());

                            String result = "";

                            if (SecurityUtils.isAllowedAccess(pathAllowedToAccess, childProjectFolderPath)) {
                                result = FileManager.updateProject(curriculumBaseDir, parentProjectUrl,
                                        childProjectUrl);
                            } else {
                                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                                result = "unauthorized";
                            }

                            response.getWriter().write(result);
                        } else if (command.equals("importSteps")) {
                            //get the curriculum base directory e.g. /Users/geoffreykwan/dev/apache-tomcat-5.5.27/webapps/curriculum
                            String curriculumBaseDir = wiseProperties.getProperty("curriculum_base_dir");

                            //get the relative child project url e.g. /172/wise4.project.json
                            String fromProjectUrl = "";

                            //get the from project id string
                            String fromProjectIdStr = request.getParameter("fromProjectId");

                            if (fromProjectIdStr != null) {
                                try {
                                    //get the from project id
                                    long fromProjectId = Long.parseLong(fromProjectIdStr);

                                    //get the from project
                                    Project fromProject = projectService.getById(fromProjectId);

                                    //get the from project url e.g. /172/wise4.project.json
                                    fromProjectUrl = (String) fromProject.getCurnit()
                                            .accept(new CurnitGetCurnitUrlVisitor());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            //get the relative child project url e.g. /236/wise4.project.json
                            String toProjectUrl = (String) project.getCurnit()
                                    .accept(new CurnitGetCurnitUrlVisitor());

                            //get the child project folder path
                            String toProjectFolderPath = FileManager.getProjectFolderPath(project);

                            //get all the files we need to import
                            String nodeIds = (String) request.getParameter("nodeIds");

                            String result = "";

                            if (SecurityUtils.isAllowedAccess(pathAllowedToAccess, toProjectFolderPath)) {
                                result = FileManager.importSteps(curriculumBaseDir, fromProjectUrl,
                                        toProjectUrl, nodeIds);
                            } else {
                                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                                result = "unauthorized";
                            }

                            response.getWriter().write(result);
                        } else if (command.equals("getProjectUsageAndMax")) {
                            //get the path to the folder
                            String path = FileManager.getProjectFolderPath(project);

                            //get the max project size for this project if it was separately specified for this project
                            Long projectMaxTotalAssetsSizeLong = project.getMaxTotalAssetsSize();

                            String result = FileManager.getProjectUsageAndMax(path,
                                    projectMaxTotalAssetsSizeLong);

                            response.getWriter().write(result);
                        } else {
                            /* we don't understand this command */
                            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                        }
                    } else {
                        /* no command was provided */
                        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    }
                } else if (forward.equals("assetmanager")) {

                    if (command == null && ServletFileUpload.isMultipartContent(request)) {
                        //user is uploading a file

                        ServletFileUpload uploader = new ServletFileUpload(new DiskFileItemFactory());
                        List<?> fileList = null;
                        try {
                            //get a list of the files the user is uploading
                            fileList = uploader.parseRequest(request);
                        } catch (FileUploadException e) {
                            e.printStackTrace();
                        }

                        //get the project folder path
                        String projectFolderPath = FileManager.getProjectFolderPath(project);

                        //get the folder name that will contain the assets
                        String dirName = "assets";
                        String pathToCheckSize = projectFolderPath;

                        //get the max disk space size this project can use
                        Long projectMaxTotalAssetsSize = project.getMaxTotalAssetsSize();

                        if (projectMaxTotalAssetsSize == null) {
                            //get the default max project size
                            projectMaxTotalAssetsSize = new Long(
                                    wiseProperties.getProperty("project_max_total_assets_size", "15728640"));
                        }

                        String allowedProjectAssetContentTypesStr = wiseProperties
                                .getProperty("normalAuthorAllowedProjectAssetContentTypes");
                        if (user.isTrustedAuthor()) {
                            allowedProjectAssetContentTypesStr += "," + wiseProperties
                                    .getProperty("trustedAuthorAllowedProjectAssetContentTypes");
                        }

                        DefaultMultipartHttpServletRequest multiRequest = (DefaultMultipartHttpServletRequest) request;
                        List<String> fileNames = new ArrayList<String>();
                        Map<String, MultipartFile> fileMap = new TreeMap<String, MultipartFile>();

                        //get all the file names and files to be uploaded
                        Iterator<String> iter = multiRequest.getFileNames();
                        while (iter.hasNext()) {
                            String filename = (String) iter.next();
                            fileNames.add(filename);
                            MultipartFile oneFile = multiRequest.getFile(filename);
                            String contentType = oneFile.getContentType();
                            if (!allowedProjectAssetContentTypesStr.contains(contentType)) {
                                if (contentType.equals("application/octet-stream") && (filename.endsWith(".mml")
                                        || filename.endsWith(".cml") || filename.endsWith(".json"))) {
                                    // .mml and .cml files are acceptable. Their content-type is not well-known, so it will show up at application/octet-stream
                                } else {
                                    response.getWriter().write(
                                            "Uploading this file type is not allowed. Operation aborted.");
                                    return null;
                                }
                            }
                            fileMap.put(filename, oneFile);
                        }

                        //tell the asset manager to handle the file upload
                        String result = AssetManager.uploadAsset(fileList, fileNames, fileMap,
                                projectFolderPath, dirName, pathToCheckSize, projectMaxTotalAssetsSize);
                        response.getWriter().write(result);
                    } else if (command.equals("remove")) {
                        //get the project folder path
                        String path = FileManager.getProjectFolderPath(project);

                        //get the assets folder name
                        String dirName = "assets";

                        //get the file name that we are going to remove
                        String assetFileName = request.getParameter("asset");

                        //tell the asset manager to remove the file
                        String result = AssetManager.removeAsset(path, dirName, assetFileName);
                        response.getWriter().write(result);
                    } else if (command.equals("getSize")) {
                        //get the project folder path
                        String path = FileManager.getProjectFolderPath(project);

                        //get the assets folder name
                        String dirName = "assets";

                        //tell the asset manager to get the size of the assets folder
                        String result = AssetManager.getSize(path, dirName);
                        response.getWriter().write(result);
                    } else if (command.equals("assetList")) {
                        //get the project folder path
                        String path = FileManager.getProjectFolderPath(project);

                        //get the assets folder name
                        String dirName = "assets";

                        //get the file names for all the assets in the assets folder
                        String assetList = AssetManager.getAssetList(path, dirName);
                        response.getWriter().write(assetList);
                    } else if (command.equals("studentAssetCopyForReference")) {
                        //AssetManager.copyAssetForReference();
                    } else {
                        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                    }
                }

                if ("updateFile".equals(command)) {
                    //we have updated a file in a project so we will update the project edited timestamp

                    /*
                     * set the project into the request so the handleProjectEdited 
                     * function doesn't have to retrieve it again
                     */
                    request.setAttribute("project", project);

                    //update the project edited timestamp
                    handleProjectEdited(request, response);
                }

                return null;
            } else {
                return new ModelAndView(new RedirectView("accessdenied.html"));
            }
        } else if (command.equals("getTimestamp")) {
            //get the current timestamp on the server and write it to the response
            response.getWriter().write(String.valueOf(new Date().getTime()));
            return null;
        } else if (forward.equals("minifier")) {
            if (this.isProjectlessRequest(request, forward)
                    || this.projectService.canAuthorProject(project, user)) {
                CredentialManager.setRequestCredentials(request, user);
                servletContext.getRequestDispatcher("/util/" + forward + ".html").forward(request, response);
                return null;
            }
        }
    }

    String command = request.getParameter(COMMAND);
    if (command != null && command != "") {
        if (command.equals("launchAuthoring")) {
            return handleLaunchAuthoring(request, response);
        } else if (command.equals("createProject")) {
            return handleCreateProject(request, response);
        } else if (command.equals("projectList")) {
            return handleProjectList(request, response);
        } else if (command.equals("notifyProjectOpen")) {
            return handleNotifyProjectOpen(request, response);
        } else if (command.equals("notifyProjectClose")) {
            return handleNotifyProjectClose(request, response);
        } else if (command.equals("publishMetadata")) {
            return this.handlePublishMetadata(request, response);
        } else if (command.equals("getUsername")) {
            return this.handleGetUsername(request, response);
        } else if (command.equals("getCurriculumBaseUrl")) {
            return this.handleGetCurriculumBaseUrl(request, response);
        } else if (command.equals("getConfig")) {
            return this.handleGetConfig(request, response);
        } else if (command.equals("getEditors")) {
            if (this.projectService.canAuthorProject(project, user)) {
                return this.handleGetEditors(request, response);
            } else {
                return new ModelAndView(new RedirectView("accessdenied.html"));
            }
        } else if (command.equals("preview")) {
            PreviewProjectParameters previewParams = new PreviewProjectParameters();
            previewParams.setProject(project);
            previewParams.setHttpServletRequest(request);

            return (ModelAndView) this.projectService.previewProject(previewParams);
        } else if (command.equals("createTag") || command.equals("updateTag") || command.equals("removeTag")
                || command.equals("retrieveProjectTags")) {
            return this.taggerController.handleRequestInternal(request, response);
        } else if (command.equals("getMetadata")) {
            request.setAttribute("project", project);
            return handleGetMetadata(request, response);
        } else if (command.equals("postMetadata")) {
            request.setAttribute("project", project);
            return handlePostMetadata(request, response);
        } else if (command.equals("reviewUpdateProject")) {
            return handleReviewUpdateProject(request, response);
        } else if (command.equals("updateProject")) {
            return handleUpdateProject(request, response);
        } else if (command.equals("importSteps")) {
            return handleReviewOrUpdateProject(request, response);
        }
    }

    return handleLaunchAuthoring(request, response);
}