List of usage examples for org.springframework.util MultiValueMap keySet
Set<K> keySet();
From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java
@RequestMapping(value = "/createOCR", method = RequestMethod.POST) @ResponseBody//ww w . ja v a 2 s .c om public void createOCR(final HttpServletRequest req, final HttpServletResponse resp) { logger.info("Start processing web service for create OCRing"); String respStr = WebServiceUtil.EMPTY_STRING; String workingDir = WebServiceUtil.EMPTY_STRING; if (req instanceof DefaultMultipartHttpServletRequest) { try { final String webServiceFolderPath = bsService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir); InputStream instream = null; OutputStream outStream = null; final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req; final BatchInstanceThread batchInstanceThread = new BatchInstanceThread( new File(workingDir).getName() + Math.random()); final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap(); if (!(fileMap.size() >= 2 && fileMap.size() <= 3)) { respStr = "Invalid number of files. We are supposed only 3 files."; } if (respStr.isEmpty()) { String xmlFileName = WebServiceUtil.EMPTY_STRING; for (final String fileName : fileMap.keySet()) { if (fileName.endsWith(FileType.XML.getExtensionWithDot())) { xmlFileName = fileName; } final MultipartFile multiPartFile = multiPartRequest.getFile(fileName); instream = multiPartFile.getInputStream(); final File file = new File(workingDir + File.separator + fileName); outStream = new FileOutputStream(file); final byte[] buf = new byte[WebServiceUtil.bufferSize]; int len; while ((len = instream.read(buf)) > 0) { outStream.write(buf, 0, len); } if (instream != null) { instream.close(); } if (outStream != null) { outStream.close(); } } final File xmlFile = new File(workingDir + File.separator + xmlFileName); final FileInputStream inputStream = new FileInputStream(xmlFile); Source source = XMLUtil.createSourceFromStream(inputStream); final WebServiceParams webServiceParams = (WebServiceParams) batchSchemaDao.getJAXB2Template() .getJaxb2Marshaller().unmarshal(source); List<Param> paramList = webServiceParams.getParams().getParam(); if (paramList == null || paramList.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); respStr = "Improper input to server. Parameter XML is incorrect. Returning without processing the results."; } else { String ocrEngine = WebServiceUtil.EMPTY_STRING; String colorSwitch = WebServiceUtil.EMPTY_STRING; String projectFile = WebServiceUtil.EMPTY_STRING; String tesseractVersion = WebServiceUtil.EMPTY_STRING; String cmdLanguage = WebServiceUtil.EMPTY_STRING; for (final Param param : paramList) { if (param.getName().equalsIgnoreCase("ocrEngine")) { ocrEngine = param.getValue(); continue; } if (param.getName().equalsIgnoreCase("colorSwitch")) { colorSwitch = param.getValue(); continue; } if (param.getName().equalsIgnoreCase("projectFile")) { projectFile = param.getValue(); logger.info("Project file for recostar is :" + projectFile); continue; } if (param.getName().equalsIgnoreCase("tesseractVersion")) { tesseractVersion = param.getValue(); logger.info("Tesseract version is: " + tesseractVersion); continue; } if (param.getName().equalsIgnoreCase("cmdLanguage")) { // supported values are "eng" and "tha" for now provided tesseract engine is learnt. cmdLanguage = param.getValue(); logger.info("cmd langugage is :" + cmdLanguage); continue; } } String results = WebServiceUtil.validateCreateOCRAPI(workingDir, ocrEngine, colorSwitch, projectFile, tesseractVersion, cmdLanguage); if (!results.isEmpty()) { respStr = results; } else { String[] fileNames = null; final File file = new File(workingDir); if (colorSwitch.equalsIgnoreCase(WebServiceUtil.ON_STRING)) { logger.info("Picking up the png file for processing."); fileNames = file .list(new CustomFileFilter(false, FileType.PNG.getExtensionWithDot())); } else { logger.info("Picking up the tif file for processing."); fileNames = file.list(new CustomFileFilter(false, FileType.TIF.getExtensionWithDot(), FileType.TIFF.getExtensionWithDot())); } logger.info("Number of file is:" + fileNames.length); logger.info("OcrEngine used for generating ocr is :" + ocrEngine); if (ocrEngine.equalsIgnoreCase("recostar")) { if (fileNames != null && fileNames.length > 0) { for (final String fileName : fileNames) { try { logger.info("File processing for recostar is :" + fileName); recostarService.createOCR(projectFile, workingDir, colorSwitch, fileName, batchInstanceThread, outputDir); } catch (final DCMAException e) { respStr = "Error occuring while creating OCR file using recostar. Please try again." + e; break; } } } else { respStr = "Improper input to server. No tiff/png files provided."; } } else if (ocrEngine.equalsIgnoreCase("tesseract")) { if (fileNames != null && fileNames.length > 0) { for (final String fileName : fileNames) { try { logger.info("File processing for ocr with tesseract is :" + fileName); tesseractService.createOCR(workingDir, colorSwitch, fileName, batchInstanceThread, outputDir, cmdLanguage, tesseractVersion); } catch (final DCMAException e) { respStr = "Error occuring while creating OCR file using tesseract. Please try again." + e; break; } } } else { respStr = "Improper input to server. No tiff/png files provided."; } } else { respStr = "Please select valid tool for generating OCR file."; } if (respStr.isEmpty()) { try { batchInstanceThread.execute(); if (ocrEngine.equalsIgnoreCase("recostar")) { for (final String fileName : fileNames) { final String recostarXMLFileName = fileName.substring(0, fileName.lastIndexOf(WebServiceUtil.DOT)) + FileType.XML.getExtensionWithDot(); try { FileUtils.copyFile( new File(workingDir + File.separator + recostarXMLFileName), new File(outputDir + File.separator + recostarXMLFileName)); } catch (final Exception e) { respStr = "Error while generating copying result file." + e; break; } } } } catch (final DCMAApplicationException e) { respStr = "Exception while generating ocr using threadpool" + e; } ServletOutputStream out = null; ZipOutputStream zout = null; final String zipFileName = WebServiceUtil.serverOutputFolderName; resp.setContentType("application/x-zip\r\n"); resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + FileType.ZIP.getExtensionWithDot() + "\"\r\n"); try { out = resp.getOutputStream(); zout = new ZipOutputStream(out); FileUtils.zipDirectory(outputDir, zout, zipFileName); resp.setStatus(HttpServletResponse.SC_OK); } catch (final IOException e) { respStr = "Error in creating output zip file.Please try again." + e; } finally { if (zout != null) { zout.close(); } if (out != null) { out.flush(); } FileUtils.deleteDirectoryAndContentsRecursive( new File(workingDir).getParentFile()); } } } } } } catch (final XmlMappingException xmle) { respStr = "Error in mapping input XML in the desired format. Please send it in the specified format. Detailed exception is " + xmle; } catch (final DCMAException dcmae) { respStr = "Error in processing request. Detailed exception is " + dcmae; } catch (final Exception e) { respStr = "Internal Server error.Please check logs for further details." + e; if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } else { respStr = "Improper input to server. Expected multipart request. Returning without processing the results."; } if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } if (!respStr.isEmpty()) { try { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr); } catch (final IOException ioe) { } } }
From source file:com.ephesoft.dcma.webservice.util.WebServiceHelper.java
/** * This method is used to get the input xml file. * /*w w w .j a v a 2 s. c o m*/ * @param workingDir {@link String} the working directory created for web service execution. * @param multiPartRequest {@link DefaultMultipartHttpServletRequest} request to get the multipart from request. * @param fileMap {@link MultiValueMap} this map contains the input files. * @return string * @throws IOException * @throws FileNotFoundException */ public static String getXMLFile(final String workingDir, final DefaultMultipartHttpServletRequest multiPartRequest, final MultiValueMap<String, MultipartFile> fileMap) throws IOException { InputStream instream = null; OutputStream outStream = null; String xmlFileName = WebServiceConstants.EMPTY_STRING; LOGGER.info("Checking for input file."); for (final String fileName : fileMap.keySet()) { try { if (fileName.endsWith(FileType.XML.getExtensionWithDot())) { xmlFileName = fileName; } final MultipartFile multiPartFile = multiPartRequest.getFile(fileName); instream = multiPartFile.getInputStream(); final File file = new File(workingDir + File.separator + fileName); outStream = new FileOutputStream(file); final byte[] buf = new byte[WebServiceUtil.bufferSize]; int len; while ((len = instream.read(buf)) > 0) { outStream.write(buf, 0, len); } } finally { IOUtils.closeQuietly(instream); IOUtils.closeQuietly(outStream); } } return xmlFileName; }
From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java
/** * To run Reporting./*from w w w.j a va 2 s . c o m*/ * @param req {@link HttpServletRequest} * @param resp {@link HttpServletResponse} */ @RequestMapping(value = "/runReporting", method = RequestMethod.POST) @ResponseBody public void runReporting(final HttpServletRequest req, final HttpServletResponse resp) { LOGGER.info("Start processing the run reporting web service"); String respStr = WebServiceUtil.EMPTY_STRING; try { if (req instanceof DefaultMultipartHttpServletRequest) { InputStream instream = null; final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req; final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap(); for (final String fileName : fileMap.keySet()) { final MultipartFile multiPartFile = multiPartRequest.getFile(fileName); instream = multiPartFile.getInputStream(); final Source source = XMLUtil.createSourceFromStream(instream); final ReportingOptions option = (ReportingOptions) batchSchemaDao.getJAXB2Template() .getJaxb2Marshaller().unmarshal(source); final String installerPath = option.getInstallerPath(); if (installerPath == null || installerPath.isEmpty() || !installerPath.toLowerCase(Locale.getDefault()).contains(WebServiceUtil.BUILD_XML)) { respStr = "Improper input to server. Installer path not specified or it does not contain the build.xml path."; } else { LOGGER.info("synchronizing the database"); reportingService.syncDatabase(installerPath); break; } } } else { respStr = IMPROPER_INPUT_TO_SERVER; LOGGER.error(SERVER_ERROR_MSG + respStr); } } catch (final XmlMappingException xmle) { respStr = ERROR_IN_MAPPING_INPUT + xmle; LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final Exception e) { respStr = INTERNAL_SERVER_ERROR + e; LOGGER.error(SERVER_ERROR_MSG + respStr); } if (!respStr.isEmpty()) { try { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr); LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final IOException ioe) { LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe); } } }
From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java
/** * To convert Tiff to Pdf.// ww w.ja va 2 s.c o m * @param req {@link HttpServletRequest} * @param resp {@link HttpServletResponse} */ @RequestMapping(value = "/convertTiffToPdf", method = RequestMethod.POST) @ResponseBody public void convertTiffToPdf(final HttpServletRequest req, final HttpServletResponse resp) { LOGGER.info("Start processing web service for extract fuzzy DB for given HOCR file"); String respStr = ""; String workingDir = ""; if (req instanceof DefaultMultipartHttpServletRequest) { InputStream instream = null; OutputStream outStream = null; try { final String webServiceFolderPath = bsService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir); final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req; final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap(); if (!fileMap.keySet().isEmpty()) { for (final String fileName : fileMap.keySet()) { try { if (!fileName.toLowerCase(Locale.getDefault()) .endsWith(FileType.TIF.getExtensionWithDot()) && !fileName.toLowerCase(Locale.getDefault()) .endsWith(FileType.TIFF.getExtensionWithDot())) { respStr = "Invalid file. Please pass the valid Tif/Tiff file"; LOGGER.error(SERVER_ERROR_MSG + respStr); break; } final MultipartFile multiPartFile = multiPartRequest.getFile(fileName); instream = multiPartFile.getInputStream(); final File file = new File(workingDir + File.separator + fileName); outStream = new FileOutputStream(file); final byte[] buf = new byte[WebServiceUtil.bufferSize]; int len = instream.read(buf); while (len > 0) { outStream.write(buf, 0, len); len = instream.read(buf); } } finally { IOUtils.closeQuietly(instream); IOUtils.closeQuietly(outStream); } } } else { respStr = "Please passed the input files for processing"; LOGGER.error(SERVER_ERROR_MSG + respStr); } if (respStr.isEmpty()) { String inputParams = WebServiceUtil.EMPTY_STRING; String outputParams = WebServiceUtil.EMPTY_STRING; String pdfGeneratorEngine = WebServiceUtil.EMPTY_STRING; for (final Enumeration<String> params = multiPartRequest.getParameterNames(); params .hasMoreElements();) { final String paramName = params.nextElement(); if (paramName.equalsIgnoreCase(WebServiceUtil.INPUT_PARAMS)) { inputParams = multiPartRequest.getParameter(paramName); LOGGER.info("Value for batchClassIdentifier parameter is " + inputParams); continue; } if (paramName.equalsIgnoreCase(WebServiceUtil.OUTPUT_PARAMS)) { outputParams = multiPartRequest.getParameter(paramName); LOGGER.info("Value for hocrFile parameter is " + outputParams); continue; } if (paramName.equalsIgnoreCase(WebServiceUtil.PDF_GENERATOR_ENGINE)) { pdfGeneratorEngine = multiPartRequest.getParameter(paramName); LOGGER.info("Value for hocrFile parameter is " + pdfGeneratorEngine); continue; } } respStr = WebServiceUtil.validateConvertTiffToPdfAPI(pdfGeneratorEngine, inputParams, outputParams); if (respStr.isEmpty()) { Set<String> outputFileList = new HashSet<String>(); File file = new File(workingDir); String[] fileList = file.list(new CustomFileFilter(false, FileType.TIF.getExtensionWithDot(), FileType.TIFF.getExtensionWithDot())); BatchInstanceThread batchInstanceThread = new BatchInstanceThread(workingDir); for (String inputFile : fileList) { String[] fileArray = new String[2]; String outputFile = inputFile.substring(0, inputFile.lastIndexOf(WebServiceUtil.DOT)) + FileType.PDF.getExtensionWithDot(); fileArray[0] = workingDir + File.separator + inputFile; fileArray[1] = workingDir + File.separator + outputFile; outputFileList.add(outputFile); imService.createTifToPDF(pdfGeneratorEngine, fileArray, batchInstanceThread, inputParams, outputParams); } batchInstanceThread.execute(); for (String outputFile : outputFileList) { FileUtils.copyFile(new File(workingDir + File.separator + outputFile), new File(outputDir + File.separator + outputFile)); } ServletOutputStream out = null; ZipOutputStream zout = null; final String zipFileName = WebServiceUtil.SERVEROUTPUTFOLDERNAME; resp.setContentType(WebServiceUtil.APPLICATION_X_ZIP); resp.setHeader(WebServiceUtil.CONTENT_DISPOSITION, WebServiceUtil.ATTACHMENT_FILENAME + zipFileName + FileType.ZIP.getExtensionWithDot() + NEXT_LINE_STRING); try { out = resp.getOutputStream(); zout = new ZipOutputStream(out); FileUtils.zipDirectory(outputDir, zout, zipFileName); resp.setStatus(HttpServletResponse.SC_OK); } catch (final IOException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error in creating output zip file.Please try again." + e.getMessage()); } finally { IOUtils.closeQuietly(zout); IOUtils.closeQuietly(out); FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } } catch (final XmlMappingException xmle) { respStr = ERROR_IN_MAPPING_INPUT + xmle; LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final DCMAException dcmae) { respStr = ERROR_PROCESSING_REQUEST + dcmae; LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final Exception e) { respStr = INTERNAL_SERVER_ERROR + e; LOGGER.error(SERVER_ERROR_MSG + respStr); if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } else { respStr = IMPROPER_INPUT_TO_SERVER; } if (!respStr.isEmpty()) { try { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr); LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final IOException ioe) { LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe); } } }
From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java
/** * Method to perform split multipage file API after the validations. * // ww w .j av a 2 s .c o m * @param resp {@link HttpServletResponse} * @param workingDir {@link String} * @param outputDir {@link String} * @param threadList {@link BatchInstanceThread} * @param inputParams {@link String} * @param outputParams {@link String} * @param isGSTool boolean * @param fileMap MultiValueMap<String, MultipartFile> * @throws DCMAException if error occurs * @throws DCMAApplicationException if error occurs * @throws IOException if error occurs */ private String performSplitAPIInternal(final HttpServletResponse resp, String workingDir, final String outputDir, final BatchInstanceThread threadList, String inputParams, String outputParams, boolean isGSTool, final MultiValueMap<String, MultipartFile> fileMap) throws DCMAException, DCMAApplicationException, IOException { String respStr = WebServiceUtil.EMPTY_STRING; for (final String fileName : fileMap.keySet()) { final File file = new File(workingDir + File.separator + fileName); if (isGSTool) { LOGGER.info("Start spliting multipage file using ghost script for file :" + fileName); imService.convertPdfToSinglePageTiffsUsingGSAPI(inputParams, file, outputParams, new File(outputDir + File.separator + fileName), threadList); } else { LOGGER.info("Start spliting multipage file using image magick for file :" + fileName); imService.convertPdfOrMultiPageTiffToTiffUsingIM(inputParams, file, outputParams, new File(outputDir + File.separator + fileName), threadList); } } try { LOGGER.info("Executing batch instance thread using thread pool"); threadList.execute(); } catch (final DCMAApplicationException dcmae) { threadList.remove(); FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); throw dcmae; } ServletOutputStream out = null; ZipOutputStream zout = null; final String zipFileName = WebServiceUtil.SERVEROUTPUTFOLDERNAME; resp.setContentType(WebServiceUtil.APPLICATION_X_ZIP); resp.setHeader(WebServiceUtil.CONTENT_DISPOSITION, WebServiceUtil.ATTACHMENT_FILENAME + zipFileName + FileType.ZIP.getExtensionWithDot() + NEXT_LINE_STRING); try { out = resp.getOutputStream(); zout = new ZipOutputStream(out); FileUtils.zipDirectory(outputDir, zout, zipFileName); LOGGER.info("zipFileName:" + zipFileName); LOGGER.info("outputDir:" + outputDir); resp.setStatus(HttpServletResponse.SC_OK); } catch (final IOException e) { respStr = "Unable to process web service request.Please check your ghostscipt or imagemagick configuration."; LOGGER.error(SERVER_ERROR_MSG + respStr); } finally { IOUtils.closeQuietly(zout); IOUtils.closeQuietly(out); FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } return respStr; }
From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java
/** * To create Searchable PDF.//from www . j a v a 2s. co m * @param request {@link HttpServletRequest} * @param response {@link HttpServletResponse} */ @RequestMapping(value = "/createSearchablePDF", method = RequestMethod.POST) @ResponseBody public void createSearchablePDF(final HttpServletRequest request, final HttpServletResponse response) { LOGGER.info("Start processing web service for create searchable pdf"); String respStr = WebServiceUtil.EMPTY_STRING; String workingDir = WebServiceUtil.EMPTY_STRING; InputStream instream = null; OutputStream outStream = null; if (request instanceof DefaultMultipartHttpServletRequest) { try { final String webServiceFolderPath = bsService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); LOGGER.info("workingDir:" + workingDir); final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir); LOGGER.info("outputDir:" + outputDir); final DefaultMultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest) request; final BatchInstanceThread batchInstanceThread = new BatchInstanceThread( new File(workingDir).getName() + Math.random()); final String isColorImage = request.getParameter("isColorImage"); final String isSearchableImage = request.getParameter("isSearchableImage"); final String outputPDFFileName = request.getParameter("outputPDFFileName"); final String projectFile = request.getParameter(WebServiceUtil.PROJECT_FILE); String results = WebServiceUtil.validateSearchableAPI(outputPDFFileName, projectFile, FileType.PDF.getExtensionWithDot(), isSearchableImage, isColorImage); if (!results.isEmpty()) { respStr = results; } else { LOGGER.info("Value of isColorImage" + isColorImage); LOGGER.info("Value of isSearchableImage" + isSearchableImage); LOGGER.info("Value of outputPDFFileName" + outputPDFFileName); LOGGER.info("Value of projectFile" + projectFile); final MultiValueMap<String, MultipartFile> fileMap = multipartRequest.getMultiFileMap(); for (final String fileName : fileMap.keySet()) { try { if (fileName.toLowerCase(Locale.getDefault()).indexOf(WebServiceUtil.RSP_EXTENSION) > -1 || fileName.toLowerCase(Locale.getDefault()) .indexOf(FileType.TIF.getExtension()) > -1 || fileName.toLowerCase(Locale.getDefault()) .indexOf(FileType.TIFF.getExtension()) > -1) { // only tiffs and RSP file is expected final MultipartFile multiPartFile = multipartRequest.getFile(fileName); try { instream = multiPartFile.getInputStream(); final File file = new File(workingDir + File.separator + fileName); outStream = new FileOutputStream(file); final byte[] buf = new byte[WebServiceUtil.bufferSize]; int len = instream.read(buf); while (len > 0) { outStream.write(buf, 0, len); len = instream.read(buf); } if (fileName.endsWith(FileType.TIF.getExtensionWithDot()) || fileName.endsWith(FileType.TIFF.getExtensionWithDot())) { int pageCount = TIFFUtil .getTIFFPageCount(workingDir + File.separator + fileName); if (pageCount > 1) { respStr = ONLY_ONE_SINGLE_PAGE_TIFF_EXPECTED; break; } } } finally { if (instream != null) { instream.close(); } if (outStream != null) { outStream.close(); } } } else { respStr = "Only tiff, tif and rsp files expected."; LOGGER.error(SERVER_ERROR_MSG + respStr); break; } } finally { IOUtils.closeQuietly(instream); IOUtils.closeQuietly(outStream); } } if (respStr.isEmpty()) { String[] imageFiles = null; final File file = new File(workingDir); imageFiles = file.list(new CustomFileFilter(false, FileType.TIFF.getExtensionWithDot(), FileType.TIF.getExtensionWithDot())); if (imageFiles == null || imageFiles.length == 0) { respStr = "No tif/tiff file found for processing."; } // getting rsp project file name String rspProjectFile = workingDir + File.separator + projectFile; LOGGER.info("rspProjectFile:" + rspProjectFile); File rspFile = new File(rspProjectFile); if (rspProjectFile == null || !rspFile.exists()) { respStr = "Invalid project file. Please verify the project file."; LOGGER.error(SERVER_ERROR_MSG + respStr); } if (respStr.isEmpty()) { final String[] pages = new String[imageFiles.length + 1]; int index = 0; for (final String imageFileName : imageFiles) { pages[index] = workingDir + File.separator + imageFileName; index++; if (WebServiceUtil.TRUE.equalsIgnoreCase(isColorImage)) { try { LOGGER.info("Generating png image files"); imService.generatePNGForImage( new File(workingDir + File.separator + imageFileName)); // getting png file name from image file name final String pngFileName = imageFileName.substring(0, imageFileName.lastIndexOf(WebServiceUtil.DOT)) + FileType.PNG.getExtensionWithDot(); // creating OCR recostarService.createOCR(projectFile, workingDir, WebServiceUtil.ON_STRING, pngFileName, batchInstanceThread, workingDir); } catch (final DCMAException e) { // deleting directory FileUtils.deleteDirectoryAndContentsRecursive( new File(workingDir).getParentFile()); respStr = "Error in generating plugin output for color switch \"ON\" for image:" + imageFileName + ". " + e; LOGGER.error(SERVER_ERROR_MSG + respStr); } } else { try { // creating OCR recostarService.createOCR(projectFile, workingDir, WebServiceUtil.OFF_STRING, imageFileName, batchInstanceThread, workingDir); } catch (final DCMAException e) { FileUtils.deleteDirectoryAndContentsRecursive( new File(workingDir).getParentFile()); respStr = "Error in generating plugin output for color switch \"OFF\" for image:" + imageFileName + ". " + e; LOGGER.error(SERVER_ERROR_MSG + respStr); } } } if (respStr.isEmpty()) { try { LOGGER.info("Generating HOCR file for input images."); // executing the batch instance thread batchInstanceThread.execute(); batchInstanceThread.remove(); final String outputPDFFile = workingDir + File.separator + outputPDFFileName; pages[index] = outputPDFFile; // creating searchable PDF imService.createSearchablePDF(isColorImage, isSearchableImage, workingDir, pages, batchInstanceThread, WebServiceUtil.DOCUMENTID); batchInstanceThread.execute(); LOGGER.info("Copying output searchable file"); FileUtils.copyFile(new File(outputPDFFile), new File(outputDir + File.separator + outputPDFFileName)); } catch (final DCMAApplicationException e) { batchInstanceThread.remove(); // deleting the directory contents FileUtils.deleteDirectoryAndContentsRecursive( new File(workingDir).getParentFile()); respStr = "Error in generating searchable pdf." + e; LOGGER.error(SERVER_ERROR_MSG + respStr); } if (respStr.isEmpty()) { ServletOutputStream out = null; ZipOutputStream zout = null; final String zipFileName = WebServiceUtil.SERVEROUTPUTFOLDERNAME; // setting the content type response.setContentType(WebServiceUtil.ATTACHMENT_FILENAME); // setting the content header response.setHeader(WebServiceUtil.CONTENT_DISPOSITION, WebServiceUtil.ATTACHMENT_FILENAME + zipFileName + FileType.ZIP.getExtensionWithDot() + NEXT_LINE_STRING); try { // zip the directory contents and set the response status out = response.getOutputStream(); zout = new ZipOutputStream(out); FileUtils.zipDirectory(outputDir, zout, zipFileName); response.setStatus(HttpServletResponse.SC_OK); } catch (final IOException e) { respStr = "Unable to process web service request.Please try again." + e; LOGGER.error(SERVER_ERROR_MSG + respStr); } finally { // clean up code IOUtils.closeQuietly(zout); IOUtils.closeQuietly(out); FileUtils.deleteDirectoryAndContentsRecursive( new File(workingDir).getParentFile()); } } } } } } } catch (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 { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr); } catch (final IOException ioe) { LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe); } } }
From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java
/** * To extract Field from Hocr.//from w w w . java 2s . c o m * @param req {@link HttpServletRequest} * @param resp {@link HttpServletResponse} */ @RequestMapping(value = "/extractFieldFromHocr", method = RequestMethod.POST) @ResponseBody public void extractFieldFromHocr(final HttpServletRequest req, final HttpServletResponse resp) { LOGGER.info("Start processing web service for extractFieldFromHocr."); String respStr = WebServiceUtil.EMPTY_STRING; String workingDir = WebServiceUtil.EMPTY_STRING; InputStream instream = null; OutputStream outStream = null; if (req instanceof DefaultMultipartHttpServletRequest) { try { final String webServiceFolderPath = bsService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); final DefaultMultipartHttpServletRequest multipartReq = (DefaultMultipartHttpServletRequest) req; String fieldValue = WebServiceUtil.EMPTY_STRING; for (final Enumeration<String> params = multipartReq.getParameterNames(); params .hasMoreElements();) { final String paramName = params.nextElement(); if (paramName.equalsIgnoreCase("fieldValue")) { fieldValue = multipartReq.getParameter(paramName); break; } } if (fieldValue == null || fieldValue.isEmpty()) { respStr = "Field Value not specified."; LOGGER.error(SERVER_ERROR_MSG + respStr); } if (respStr.isEmpty()) { final MultiValueMap<String, MultipartFile> fileMap = multipartReq.getMultiFileMap(); if (fileMap.size() == 1) { String hocrFileName = ""; for (final String fileName : fileMap.keySet()) { // only single html file is expected as input try { if (fileName.toLowerCase(Locale.getDefault()) .indexOf(FileType.HTML.getExtension()) > -1) { // only HTML file is expected hocrFileName = fileName; final MultipartFile multiPartFile = multipartReq.getFile(fileName); instream = multiPartFile.getInputStream(); final File file = new File(workingDir + File.separator + fileName); outStream = new FileOutputStream(file); final byte buf[] = new byte[WebserviceConstants.BUF]; int len = instream.read(buf); while (len > 0) { outStream.write(buf, 0, len); len = instream.read(buf); } break; } else { respStr = IMPROPER_INPUT_ONLY_ONE_HTML_FILE_EXPECTED; LOGGER.error(SERVER_ERROR_MSG + respStr); } } finally { IOUtils.closeQuietly(instream); IOUtils.closeQuietly(outStream); } } if (respStr.isEmpty()) { String fileName = workingDir + File.separator + hocrFileName; // generate hocr file from html file. HocrPages hocrPages = new HocrPages(); List<HocrPage> hocrPageList = hocrPages.getHocrPage(); HocrPage hocrPage = new HocrPage(); String pageID = WebServiceUtil.PG0; hocrPage.setPageID(pageID); hocrPageList.add(hocrPage); bsService.hocrGenerationAPI(workingDir, WebServiceUtil.PG0, fileName, hocrPage); List<KVExtraction> kvExtractionList = kvFieldService.createKeyValueFieldAPI(fieldValue, hocrPage); final KVExtractionFieldPatterns patterns = new KVExtractionFieldPatterns(); final List<KVExtractionFieldPattern> pattern = patterns.getKVExtractionFieldPattern(); for (final KVExtraction eachKVExtraction : kvExtractionList) { final KVExtractionFieldPattern kvField = new KVExtractionFieldPattern(); kvField.setDistance(eachKVExtraction.getDistance()); kvField.setFetchValue(eachKVExtraction.getFetchValue().name()); kvField.setKeyPattern(eachKVExtraction.getKeyPattern()); kvField.setLength(eachKVExtraction.getLength()); if (eachKVExtraction.getLocationType() != null) { kvField.setLocation(eachKVExtraction.getLocationType().name()); } kvField.setMultiplier(eachKVExtraction.getMultiplier()); kvField.setNoOfWords(eachKVExtraction.getNoOfWords() == null ? 0 : eachKVExtraction.getNoOfWords()); kvField.setValuePattern(eachKVExtraction.getValuePattern()); kvField.setWidth(eachKVExtraction.getWidth()); kvField.setXOffset(eachKVExtraction.getXoffset()); kvField.setYOffset(eachKVExtraction.getYoffset()); pattern.add(kvField); } StreamResult result; try { result = new StreamResult(resp.getOutputStream()); resp.setStatus(HttpServletResponse.SC_OK); batchSchemaDao.getJAXB2Template().getJaxb2Marshaller().marshal(patterns, result); } catch (final IOException e) { try { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR + e.getMessage()); } catch (final IOException ioe) { LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe); } } } } else { respStr = IMPROPER_INPUT_ONLY_ONE_HTML_FILE_EXPECTED; LOGGER.error(SERVER_ERROR_MSG + respStr); } } } catch (final DCMAException dcmae) { respStr = ERROR_PROCESSING_REQUEST + dcmae; LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final Exception e) { respStr = INTERNAL_SERVER_ERROR + e; LOGGER.error(SERVER_ERROR_MSG + respStr); if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } else { respStr = "Improper input to server. Expected multipart request. Returing without processing the results."; LOGGER.error(SERVER_ERROR_MSG + respStr); } if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } if (!respStr.isEmpty()) { try { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr); LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final IOException ioe) { LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe); } } }
From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java
/** * To create Multi Page File./*from ww w. j a va 2s .c om*/ * @param req {@link HttpServletRequest} * @param resp {@link HttpServletResponse} */ @RequestMapping(value = "/createMultiPageFile", method = RequestMethod.POST) @ResponseBody public void createMultiPageFile(final HttpServletRequest req, final HttpServletResponse resp) { LOGGER.info("Start processing web service for createMultiPageFile."); String respStr = WebServiceUtil.EMPTY_STRING; String workingDir = WebServiceUtil.EMPTY_STRING; InputStream instream = null; OutputStream outStream = null; if (req instanceof DefaultMultipartHttpServletRequest) { try { final String webServiceFolderPath = bsService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir); final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req; final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap(); String xmlFileName = WebServiceUtil.EMPTY_STRING; List<File> fileList = new ArrayList<File>(); for (final String fileName : fileMap.keySet()) { try { if (fileName.endsWith(FileType.XML.getExtensionWithDot()) || fileName.endsWith(FileType.TIF.getExtensionWithDot()) || fileName.endsWith(FileType.TIFF.getExtensionWithDot())) { final File file = new File(workingDir + File.separator + fileName); if (fileName.endsWith(FileType.XML.getExtensionWithDot())) { xmlFileName = fileName; } else { fileList.add(file); } final MultipartFile multiPartFile = multiPartRequest.getFile(fileName); instream = multiPartFile.getInputStream(); outStream = new FileOutputStream(file); final byte[] buf = new byte[WebServiceUtil.bufferSize]; int len = instream.read(buf); while (len > 0) { outStream.write(buf, 0, len); len = instream.read(buf); } } else { respStr = "Expected only tif, tiff files."; LOGGER.error(SERVER_ERROR_MSG + respStr); } } finally { IOUtils.closeQuietly(instream); IOUtils.closeQuietly(outStream); } } if (respStr.isEmpty()) { final File xmlFile = new File(workingDir + File.separator + xmlFileName); final FileInputStream inputStream = new FileInputStream(xmlFile); Source source = XMLUtil.createSourceFromStream(inputStream); final WebServiceParams webServiceParams = (WebServiceParams) batchSchemaDao.getJAXB2Template() .getJaxb2Marshaller().unmarshal(source); if (webServiceParams.getParams() == null || webServiceParams.getParams().getParam() == null || webServiceParams.getParams().getParam().isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); respStr = IMPROPER_XML_PARAMETER; LOGGER.error(SERVER_ERROR_MSG + respStr); } else { List<Param> paramList = webServiceParams.getParams().getParam(); String imageProcessingAPI = WebServiceUtil.EMPTY_STRING; String pdfOptimizationParams = WebServiceUtil.EMPTY_STRING; String multipageTifSwitch = WebServiceUtil.EMPTY_STRING; String pdfOptimizationSwitch = WebServiceUtil.EMPTY_STRING, ghostscriptPdfParameters = WebServiceUtil.EMPTY_STRING; for (final Param param : paramList) { if (param.getName().equalsIgnoreCase(WebServiceUtil.IMAGE_PROCESSING_API)) { imageProcessingAPI = param.getValue(); continue; } if (param.getName().equalsIgnoreCase(WebServiceUtil.PDF_OPTIMIZATION_PARAMS)) { pdfOptimizationParams = param.getValue(); continue; } if (param.getName().equalsIgnoreCase(WebServiceUtil.MULTIPAGE_TIF_SWITCH)) { multipageTifSwitch = param.getValue(); continue; } if (param.getName().equalsIgnoreCase(WebServiceUtil.PDF_OPTIMIZATION_SWITCH)) { pdfOptimizationSwitch = param.getValue(); continue; } if (param.getName().equalsIgnoreCase(WebServiceUtil.GHOSTSCRIPT_PDF_PARAMETERS)) { ghostscriptPdfParameters = param.getValue(); continue; } } String results = WebServiceUtil.validateCreateMultiPageFile(ghostscriptPdfParameters, imageProcessingAPI, pdfOptimizationSwitch, multipageTifSwitch, pdfOptimizationParams); if (!results.isEmpty()) { respStr = results; } else { imService.createMultiPageFilesAPI(ghostscriptPdfParameters, pdfOptimizationParams, multipageTifSwitch, imageProcessingAPI, pdfOptimizationSwitch, workingDir, outputDir, fileList, new File(workingDir).getName() + Math.random()); ServletOutputStream out = null; ZipOutputStream zout = null; final String zipFileName = WebServiceUtil.SERVEROUTPUTFOLDERNAME; resp.setContentType(WebServiceUtil.APPLICATION_X_ZIP); resp.setHeader(WebServiceUtil.CONTENT_DISPOSITION, WebServiceUtil.ATTACHMENT_FILENAME + zipFileName + FileType.ZIP.getExtensionWithDot() + NEXT_LINE_STRING); try { out = resp.getOutputStream(); zout = new ZipOutputStream(out); FileUtils.zipDirectory(outputDir, zout, zipFileName); resp.setStatus(HttpServletResponse.SC_OK); } catch (final IOException e) { respStr = "Unable to process web service request.Please try again." + e; } finally { IOUtils.closeQuietly(zout); IOUtils.closeQuietly(out); FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } } } catch (final XmlMappingException xmle) { respStr = ERROR_IN_MAPPING_INPUT + xmle; LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final DCMAException dcmae) { respStr = ERROR_PROCESSING_REQUEST + dcmae; LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final Exception e) { respStr = INTERNAL_SERVER_ERROR + e; LOGGER.error(SERVER_ERROR_MSG + respStr); if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } else { respStr = IMPROPER_INPUT_TO_SERVER; LOGGER.error(SERVER_ERROR_MSG + respStr); } if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } if (!respStr.isEmpty()) { try { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr); LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final IOException ioe) { LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe); } } }
From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java
private void processFuzzyDbExtraction(final HttpServletRequest req, final HttpServletResponse resp) { LOGGER.info("Start processing web service for extract fuzzy DB for given HOCR file"); String respStr = ""; String workingDir = ""; Documents documents = null;/*from w w w .ja v a2 s .c o m*/ InputStream instream = null; OutputStream outStream = null; if (req instanceof DefaultMultipartHttpServletRequest) { try { final String webServiceFolderPath = bsService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req; final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap(); String htmlFile = WebServiceUtil.EMPTY_STRING; if (fileMap.size() == 1) { for (final String fileName : fileMap.keySet()) { try { if (fileName.endsWith(FileType.HTML.getExtensionWithDot())) { htmlFile = fileName; } else { respStr = "Invalid file. Please passed the valid html file"; LOGGER.error(SERVER_ERROR_MSG + respStr); break; } final MultipartFile multiPartFile = multiPartRequest.getFile(fileName); instream = multiPartFile.getInputStream(); final File file = new File(workingDir + File.separator + fileName); outStream = new FileOutputStream(file); final byte[] buf = new byte[WebServiceUtil.bufferSize]; int len = instream.read(buf); while (len > 0) { outStream.write(buf, 0, len); len = instream.read(buf); } } finally { IOUtils.closeQuietly(instream); IOUtils.closeQuietly(outStream); } } } else { respStr = "Invalid number of files. We are supposed only one file"; LOGGER.error(SERVER_ERROR_MSG + respStr); } String batchClassIdentifier = WebServiceUtil.EMPTY_STRING; String documentType = WebServiceUtil.EMPTY_STRING; String hocrFileName = WebServiceUtil.EMPTY_STRING; for (final Enumeration<String> params = multiPartRequest.getParameterNames(); params .hasMoreElements();) { final String paramName = params.nextElement(); if (paramName.equalsIgnoreCase("documentType")) { documentType = multiPartRequest.getParameter(paramName); LOGGER.info("Value for documentType parameter is : " + documentType); continue; } if (paramName.equalsIgnoreCase("batchClassIdentifier")) { batchClassIdentifier = multiPartRequest.getParameter(paramName); LOGGER.info("Value for batchClassIdentifier parameter is : " + batchClassIdentifier); continue; } if (paramName.equalsIgnoreCase("hocrFile")) { hocrFileName = multiPartRequest.getParameter(paramName); LOGGER.info("Value for hocrFile parameter is : " + hocrFileName); continue; } } if (!hocrFileName.equalsIgnoreCase(htmlFile)) { respStr = "Please pass the valid hocr File."; LOGGER.error(SERVER_ERROR_MSG + respStr); } if (respStr.isEmpty()) { respStr = WebServiceUtil.validateExtractFuzzyDBAPI(workingDir, hocrFileName, batchClassIdentifier, documentType); if (respStr.isEmpty()) { BatchClass batchClass = bcService.getBatchClassByIdentifier(batchClassIdentifier); if (batchClass == null) { respStr = "Please enter valid batch class identifier"; } else { Set<String> loggedInUserRole = getUserRoles(req); if (!isBatchClassViewableToUser(batchClassIdentifier, loggedInUserRole, isSuperAdmin(req))) { respStr = USER_NOT_AUTHORIZED_TO_VIEW_THE_BATCH_CLASS + batchClassIdentifier; LOGGER.error(SERVER_ERROR_MSG + respStr); } else { BatchPlugin fuzzyDBPlugin = batchClassPPService .getPluginProperties(batchClassIdentifier, "FUZZYDB"); if (fuzzyDBPlugin == null || fuzzyDBPlugin.getPropertiesSize() == 0) { respStr = "Fuzzy DB plugin is not configured for batch class : " + batchClassIdentifier + " . Please select proper batch class"; LOGGER.error(SERVER_ERROR_MSG + respStr); } else if (fuzzyDBPlugin .getPluginConfigurations(FuzzyDBProperties.FUZZYDB_STOP_WORDS) == null || fuzzyDBPlugin.getPluginConfigurations( FuzzyDBProperties.FUZZYDB_MIN_TERM_FREQ) == null || fuzzyDBPlugin.getPluginConfigurations( FuzzyDBProperties.FUZZYDB_MIN_WORD_LENGTH) == null || fuzzyDBPlugin.getPluginConfigurations( FuzzyDBProperties.FUZZYDB_MAX_QUERY_TERMS) == null || fuzzyDBPlugin.getPluginConfigurations( FuzzyDBProperties.FUZZYDB_NO_OF_PAGES) == null || fuzzyDBPlugin.getPluginConfigurations( FuzzyDBProperties.FUZZYDB_DB_DRIVER) == null || fuzzyDBPlugin.getPluginConfigurations( FuzzyDBProperties.FUZZYDB_CONNECTION_URL) == null || fuzzyDBPlugin.getPluginConfigurations( FuzzyDBProperties.FUZZYDB_DB_USER_NAME) == null || fuzzyDBPlugin.getPluginConfigurations( FuzzyDBProperties.FUZZYDB_DB_PASSWORD) == null || fuzzyDBPlugin.getPluginConfigurations( FuzzyDBProperties.FUZZYDB_THRESHOLD_VALUE) == null) { respStr = "Incomplete properties of the Fuzzy DB plugin for the specified batch class id: " + batchClassIdentifier; LOGGER.error(SERVER_ERROR_MSG + respStr); } } } if (respStr.isEmpty()) { List<com.ephesoft.dcma.da.domain.FieldType> allFdTypes = fieldTypeService .getFdTypeByDocTypeNameForBatchClass(documentType, batchClassIdentifier); if (allFdTypes == null || allFdTypes.size() == 0) { respStr = "Document Level Fields doesn't exist for document type: " + documentType; LOGGER.error(SERVER_ERROR_MSG + respStr); } } if (respStr.isEmpty()) { try { 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, pageID, workingDir + File.separator + hocrFileName, hocrPage); documents = fuzzyDBSearchService.extractDataBaseFields(batchClassIdentifier, documentType, hocrPages); if (documents != null) { StreamResult result = new StreamResult(resp.getOutputStream()); batchSchemaDao.getJAXB2Template().getJaxb2Marshaller().marshal(documents, result); } } catch (final DCMAException e) { respStr = "Exception while extracting field using fuzzy db" + e; LOGGER.error(SERVER_ERROR_MSG + respStr); } } } } } catch (final XmlMappingException xmle) { respStr = ERROR_IN_MAPPING_INPUT + xmle; LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final Exception e) { respStr = INTERNAL_SERVER_ERROR + e; LOGGER.error(SERVER_ERROR_MSG + respStr); if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } else { respStr = IMPROPER_INPUT_TO_SERVER; LOGGER.error(SERVER_ERROR_MSG + respStr); } if (!respStr.isEmpty()) { try { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr); LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final IOException ioe) { LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe); } } }
From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java
private void processRegularRegexExtraction(final HttpServletRequest req, final HttpServletResponse resp) { LOGGER.info("Start processing web service for extracting fields using regex..."); String respStr = WebServiceUtil.EMPTY_STRING; String workingDir = WebServiceUtil.EMPTY_STRING; InputStream instream = null;/*from ww w. j a va 2s. co m*/ OutputStream outStream = null; if (req instanceof DefaultMultipartHttpServletRequest) { try { final String webServiceFolderPath = bsService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req; final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap(); if (respStr.isEmpty()) { String xmlFileName = WebServiceUtil.EMPTY_STRING; if (fileMap.size() == 2) { Set<String> fileNameSet = fileMap.keySet(); for (final String fileName : fileNameSet) { try { if (fileName.endsWith(FileType.XML.getExtensionWithDot())) { xmlFileName = fileName; } if (!xmlFileName.isEmpty()) { final MultipartFile multiPartFile = multiPartRequest.getFile(fileName); instream = multiPartFile.getInputStream(); final File file = new File(workingDir + File.separator + fileName); outStream = new FileOutputStream(file); final byte[] buf = new byte[WebServiceUtil.bufferSize]; int len = instream.read(buf); while (len > 0) { outStream.write(buf, 0, len); len = instream.read(buf); } break; } } finally { IOUtils.closeQuietly(instream); IOUtils.closeQuietly(outStream); } } WebServiceParams webServiceParams = null; final File xmlFile = new File(workingDir + File.separator + xmlFileName); if (xmlFileName == null) { respStr = "No xml file passed..."; } else if (xmlFile.exists()) { FileInputStream inputStream = null; try { inputStream = new FileInputStream(xmlFile); Source source = XMLUtil.createSourceFromStream(inputStream); webServiceParams = (WebServiceParams) batchSchemaDao.getJAXB2Template() .getJaxb2Marshaller().unmarshal(source); } finally { IOUtils.closeQuietly(inputStream); } List<Param> paramList = webServiceParams.getParams().getParam(); if (paramList == null || paramList.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); respStr = IMPROPER_XML_PARAMETER; } else { String batchClassIdentifier = WebServiceUtil.EMPTY_STRING; String documentType = WebServiceUtil.EMPTY_STRING; String hocrFileName = WebServiceUtil.EMPTY_STRING; for (final Param param : paramList) { if (param.getName().equalsIgnoreCase(WebServiceUtil.DOCUMENT_TYPE)) { documentType = param.getValue(); LOGGER.info("Value for documentType parameter is " + documentType); continue; } if (param.getName().equalsIgnoreCase(WebServiceUtil.BATCH_CLASS_IDENTIFIER)) { batchClassIdentifier = param.getValue(); LOGGER.info("Value for batchClassIdentifier parameter is " + batchClassIdentifier); continue; } if (param.getName().equalsIgnoreCase(WebServiceUtil.HOCR_FILE)) { hocrFileName = param.getValue(); LOGGER.info("Value for hocrFile parameter is " + hocrFileName); continue; } } respStr = WebServiceUtil.validateExtractRegexFieldsAPI(workingDir, batchClassIdentifier, documentType, hocrFileName); if (respStr.isEmpty()) { respStr = validateInputAndPerformExtraction(req, resp, respStr, workingDir, multiPartRequest, fileNameSet, batchClassIdentifier, documentType, hocrFileName); } } } } else { respStr = "Invalid number of files. We are supposed only 2 files each of type: XML and html file."; } } } catch (final XmlMappingException xmle) { respStr = ERROR_IN_MAPPING_INPUT + xmle; LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final DCMAException dcmae) { respStr = ERROR_PROCESSING_REQUEST + dcmae; LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final Exception e) { respStr = INTERNAL_SERVER_ERROR + e; LOGGER.error(SERVER_ERROR_MSG + respStr); if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } else { respStr = IMPROPER_INPUT_TO_SERVER; LOGGER.error(SERVER_ERROR_MSG + respStr); } if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } if (!respStr.isEmpty()) { try { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr); LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final IOException ioe) { LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe); } } }