List of usage examples for org.springframework.web.multipart.support DefaultMultipartHttpServletRequest getMultiFileMap
@Override
public MultiValueMap<String, MultipartFile> getMultiFileMap()
From source file:com.ephesoft.dcma.webservice.util.WebServiceHelper.java
/** * This Method is Added to process the input provided for WebService to upload files for Learning * /*from ww w. ja v a 2s . c o m*/ * @param req the {@link HttpServletRequest} the request header for this web service hit * @throws InternalServerException the internal server exception * @throws ValidationException the validation exception */ public void getUploadFilesforLearning(final HttpServletRequest req) throws InternalServerException, ValidationException { LOGGER.info("Inside getUploadFilesforLearning method"); String respStr = WebServiceConstants.EMPTY_STRING; String workingDir = WebServiceConstants.EMPTY_STRING; String docTypeName = WebServiceConstants.EMPTY_STRING; String learningType = WebServiceConstants.EMPTY_STRING; List<String> fileNamesFirst = null; List<String> fileNamesMiddle = null; List<String> fileNamesLast = null; if (req instanceof DefaultMultipartHttpServletRequest) { try { final String webServiceFolderPath = batchSchemaService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req; final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap(); final int fileCountValue = checkFileCountForExtentionType("xml", fileMap); if (fileCountValue >= 2) { final HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY; respStr = "There are more than 1 xml file uploaded with the request. Only 1 xml is expected"; final RestError restError = new RestError(status, WebServiceConstants.INTERNAL_SERVER_ERROR_CODE, respStr, respStr + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error("Error response at server:" + respStr); final InternalServerException internalServerExcpetion = new InternalServerException( WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE, restError); LOGGER.error(respStr + WebServiceConstants.HTTP_STATUS + status); throw internalServerExcpetion; } String xmlFileName = WebServiceConstants.EMPTY_STRING; xmlFileName = getXMLFile(workingDir, multiPartRequest, fileMap); LOGGER.info("XML file name is" + xmlFileName); UploadLearningFiles uploadLearningFileXML = null; final File xmlFile = new File(workingDir + File.separator + xmlFileName); final FileInputStream inputStream = new FileInputStream(xmlFile); final Source source = XMLUtil.createSourceFromStream(inputStream); uploadLearningFileXML = (UploadLearningFiles) batchSchemaDao.getJAXB2Template().getJaxb2Marshaller() .unmarshal(source); final String inputXMLValidationRes = validateInputXMLForLearning(uploadLearningFileXML); if (inputXMLValidationRes.isEmpty()) { String searchPathName = WebServiceConstants.EMPTY_STRING; final List<DocType> docTypes = uploadLearningFileXML.getDocType(); if (isValidFileCountForLearning(docTypes, fileMap.size() - 1)) { for (final DocType docType : docTypes) { docTypeName = docType.getDocTypeName(); learningType = docType.getLearningType(); if (docType.getPageTypeFirst() != null && docType.getPageTypeFirst().getFilesToBeUploaded().getFileName() != null && !docType.getPageTypeFirst().getFilesToBeUploaded().getFileName().isEmpty()) { fileNamesFirst = docType.getPageTypeFirst().getFilesToBeUploaded().getFileName(); if (LUCENE_SEARCH_CLASSIFICATION_TYPE.equalsIgnoreCase(learningType)) { searchPathName = EphesoftStringUtil.concatenate( batchSchemaService.getSearchClassSamplePath( uploadLearningFileXML.getBatchClassId(), true), File.separator, docType.getDocTypeName(), File.separator, docTypeName, WebServiceConstants.FIRST_PAGE); uploadInputImagesToLearningFolder(searchPathName, workingDir, fileNamesFirst); LOGGER.info( "Sucessfully Uploaded Images for lucene-search-classification-sample"); } else if ("Image".equalsIgnoreCase(learningType)) { searchPathName = EphesoftStringUtil.concatenate( batchSchemaService.getImageMagickBaseFolderPath( uploadLearningFileXML.getBatchClassId(), true), File.separator, docType.getDocTypeName(), File.separator, docTypeName, WebServiceConstants.FIRST_PAGE); uploadInputImagesToLearningFolder(searchPathName, workingDir, fileNamesFirst); } else { searchPathName = EphesoftStringUtil.concatenate( batchSchemaService.getSearchClassSamplePath( uploadLearningFileXML.getBatchClassId(), true), File.separator, docType.getDocTypeName(), File.separator, docTypeName, WebServiceConstants.FIRST_PAGE); uploadInputImagesToLearningFolder(searchPathName, workingDir, fileNamesFirst); LOGGER.info( "Sucessfully Uploaded Images for lucene-search-classification-sample"); searchPathName = EphesoftStringUtil.concatenate( batchSchemaService.getImageMagickBaseFolderPath( uploadLearningFileXML.getBatchClassId(), true), File.separator, docType.getDocTypeName(), File.separator, docTypeName, WebServiceConstants.FIRST_PAGE); uploadInputImagesToLearningFolder(searchPathName, workingDir, fileNamesFirst); LOGGER.info("Sucessfully Uploaded Images for image-classification-sample"); } } if (docType.getPageTypeMiddle() != null && docType.getPageTypeMiddle().getFilesToBeUploaded().getFileName() != null && !docType.getPageTypeMiddle().getFilesToBeUploaded().getFileName() .isEmpty()) { fileNamesMiddle = docType.getPageTypeMiddle().getFilesToBeUploaded().getFileName(); if (LUCENE_SEARCH_CLASSIFICATION_TYPE.equalsIgnoreCase(learningType)) { searchPathName = EphesoftStringUtil.concatenate( batchSchemaService.getSearchClassSamplePath( uploadLearningFileXML.getBatchClassId(), true), File.separator, docType.getDocTypeName(), File.separator, docTypeName, WebServiceConstants.MIDDLE_PAGE); uploadInputImagesToLearningFolder(searchPathName, workingDir, fileNamesMiddle); LOGGER.info( "Sucessfully Uploaded Images for lucene-search-classification-sample"); } else if ("Image".equalsIgnoreCase(learningType)) { searchPathName = EphesoftStringUtil.concatenate( batchSchemaService.getImageMagickBaseFolderPath( uploadLearningFileXML.getBatchClassId(), true), File.separator, docType.getDocTypeName(), File.separator, docTypeName, WebServiceConstants.MIDDLE_PAGE); uploadInputImagesToLearningFolder(searchPathName, workingDir, fileNamesMiddle); LOGGER.info("Sucessfully Uploaded Images for image-classification-sample"); } else { searchPathName = EphesoftStringUtil.concatenate( batchSchemaService.getSearchClassSamplePath( uploadLearningFileXML.getBatchClassId(), true), File.separator, docType.getDocTypeName(), File.separator, docTypeName, WebServiceConstants.MIDDLE_PAGE); uploadInputImagesToLearningFolder(searchPathName, workingDir, fileNamesMiddle); LOGGER.info( "Sucessfully Uploaded Images for lucene-search-classification-sample"); searchPathName = EphesoftStringUtil.concatenate( batchSchemaService.getImageMagickBaseFolderPath( uploadLearningFileXML.getBatchClassId(), true), File.separator, docType.getDocTypeName(), File.separator, docTypeName, WebServiceConstants.MIDDLE_PAGE); uploadInputImagesToLearningFolder(searchPathName, workingDir, fileNamesMiddle); LOGGER.info("Sucessfully Uploaded Images for image-classification-sample"); } } if (docType.getPageTypeLast() != null && docType.getPageTypeLast().getFilesToBeUploaded().getFileName() != null && !docType.getPageTypeLast().getFilesToBeUploaded().getFileName().isEmpty()) { fileNamesLast = docType.getPageTypeLast().getFilesToBeUploaded().getFileName(); if (LUCENE_SEARCH_CLASSIFICATION_TYPE.equalsIgnoreCase(learningType)) { searchPathName = EphesoftStringUtil.concatenate( batchSchemaService.getSearchClassSamplePath( uploadLearningFileXML.getBatchClassId(), true), File.separator, docType.getDocTypeName(), File.separator, docTypeName, WebServiceConstants.LAST_PAGE); uploadInputImagesToLearningFolder(searchPathName, workingDir, fileNamesLast); LOGGER.info( "Sucessfully Uploaded Images for lucene-search-classification-sample"); } else if ("Image".equalsIgnoreCase(learningType)) { searchPathName = EphesoftStringUtil.concatenate( batchSchemaService.getImageMagickBaseFolderPath( uploadLearningFileXML.getBatchClassId(), true), File.separator, docType.getDocTypeName(), File.separator, docTypeName, WebServiceConstants.LAST_PAGE); uploadInputImagesToLearningFolder(searchPathName, workingDir, fileNamesLast); LOGGER.info("Sucessfully Uploaded Images for image-classification-sample"); } else { searchPathName = EphesoftStringUtil.concatenate( batchSchemaService.getSearchClassSamplePath( uploadLearningFileXML.getBatchClassId(), true), File.separator, docType.getDocTypeName(), File.separator, docTypeName, WebServiceConstants.LAST_PAGE); uploadInputImagesToLearningFolder(searchPathName, workingDir, fileNamesLast); LOGGER.info( "Sucessfully Uploaded Images for lucene-search-classification-sample"); searchPathName = EphesoftStringUtil.concatenate( batchSchemaService.getImageMagickBaseFolderPath( uploadLearningFileXML.getBatchClassId(), true), File.separator, docType.getDocTypeName(), File.separator, docTypeName, WebServiceConstants.LAST_PAGE); uploadInputImagesToLearningFolder(searchPathName, workingDir, fileNamesLast); LOGGER.info("Sucessfully Uploaded Images for image-classification-sample"); } } } } else { final RestError restError = createUnprocessableEntityRestError( WebServiceConstants.INVALID_NUMBER_OF_FILES_FOR_UPLOAD_LEARNING, WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_CODE); LOGGER.error("Mismatch in the XML input and files sent."); throw new ValidationException( WebServiceConstants.INVALID_NUMBER_OF_FILES_FOR_UPLOAD_LEARNING, restError); } } else { final RestError restError = new RestError(HttpStatus.UNPROCESSABLE_ENTITY, WebServiceConstants.PARAMETER_XML_INCORRECT_CODE, inputXMLValidationRes, inputXMLValidationRes + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error(WebServiceConstants.PARAMETER_XML_INCORRECT_MESSAGE + WebServiceConstants.HTTP_STATUS + HttpStatus.UNPROCESSABLE_ENTITY); throw new InternalServerException(inputXMLValidationRes, restError); } } catch (final FileNotFoundException fe) { respStr = WebServiceConstants.INPUT_XML_NOT_FOUND_MESSAGE; final RestError restError = new RestError(HttpStatus.UNPROCESSABLE_ENTITY, WebServiceConstants.INPUT_XML_NOT_FOUND_CODE, respStr, WebServiceConstants.INPUT_XML_NOT_FOUND_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error("Error response at server:" + respStr); final InternalServerException internalServerExcpetion = new InternalServerException( WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE, restError); LOGGER.error(respStr + WebServiceConstants.HTTP_STATUS); throw internalServerExcpetion; } catch (final org.xml.sax.SAXParseException ex) { respStr = "Error in Parsing Input XML.Please try again" + ex.getMessage(); final RestError restError = new RestError(HttpStatus.UNPROCESSABLE_ENTITY, WebServiceConstants.INPUT_XML_NOT_ABLE_TO_PARSE_CODE, respStr, WebServiceConstants.INPUT_XML_NOT_ABLE_TO_PARSE_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error("Error response at server:" + respStr); final InternalServerException internalServerExcpetion = new InternalServerException( WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE, restError); LOGGER.error(respStr + WebServiceConstants.HTTP_STATUS); throw internalServerExcpetion; // JIRA-Bug-11130 } catch (InternalServerException internalServerException) { throw internalServerException; } catch (ValidationException validationException) { throw validationException; } catch (final Exception exception) { final HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; respStr = WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE + exception; final RestError restError = new RestError(status, WebServiceConstants.INTERNAL_SERVER_ERROR_CODE, WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE, WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error("Error response at server:" + respStr); final InternalServerException internalServerExcpetion = new InternalServerException( WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE, restError); LOGGER.error(respStr + WebServiceConstants.HTTP_STATUS + status); throw internalServerExcpetion; } finally { try { if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } catch (final Exception ex) { final HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; respStr = WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE + ex.getMessage(); final RestError restError = new RestError(status, WebServiceConstants.INTERNAL_SERVER_ERROR_CODE, WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE, WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error("Error response at server:" + respStr); final InternalServerException internalServerExcpetion = new InternalServerException( WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE, restError); LOGGER.error(respStr + WebServiceConstants.HTTP_STATUS + status); throw internalServerExcpetion; } } } else { final HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; respStr = WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE; final RestError restError = new RestError(status, WebServiceConstants.IMPROPER_INPUT_TO_SERVER_CODE, WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE, WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error(respStr + WebServiceConstants.HTTP_STATUS + status); throw new InternalServerException(WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE, restError); } }
From source file:com.ephesoft.dcma.webservice.util.WebServiceHelper.java
/** * This method is Added to process input XML to implement auto Learning for KV feature * // w w w . j a v a 2 s . c om * @param req the {@link HttpServletRequest} the request header for this web service hit * @throws InternalServerException the internal server exception * @throws ValidationException the validation exception */ public ExtractKV processKVLearningDocType(final HttpServletRequest req) throws InternalServerException, ValidationException { final com.ephesoft.dcma.batch.schema.ExtractKV extractKV = new com.ephesoft.dcma.batch.schema.ExtractKV(); LOGGER.info("Inside autoLearningKV method for WebService"); String respStr = WebServiceConstants.EMPTY_STRING; String workingDir = WebServiceConstants.EMPTY_STRING; Coordinates keyRectangleCoordinates = null; Coordinates valueRectangleCoordinates = null; if (req instanceof DefaultMultipartHttpServletRequest) { try { final String webServiceFolderPath = batchSchemaService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req; final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap(); if (fileMap.size() != 2) { final HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; respStr = "Improper input to server. Expected two files: hocrFileZip and xml parameter file."; final RestError restError = new RestError(status, WebServiceConstants.IMPROPER_INPUT_TO_SERVER_CODE, respStr, WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error(respStr + WebServiceConstants.HTTP_STATUS + status); throw new InternalServerException(WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE, restError); } String xmlFileName = WebServiceConstants.EMPTY_STRING; xmlFileName = getXMLFile(workingDir, multiPartRequest, fileMap); LOGGER.info("XML file name is" + xmlFileName); KVExtractionDocType kvExtract = null; final File xmlFile = new File(workingDir + File.separator + xmlFileName); if (xmlFile.exists()) { final FileInputStream inputStream = new FileInputStream(xmlFile); final Source source = XMLUtil.createSourceFromStream(inputStream); kvExtract = (KVExtractionDocType) batchSchemaDao.getJAXB2Template().getJaxb2Marshaller() .unmarshal(source); if (kvExtract != null) { final String inputXMLValidationRes = validateInputXMLForAutoKVExtraction(kvExtract); if (inputXMLValidationRes.isEmpty()) { final String documentName = kvExtract.getDocumentType(); final BatchClass batchClass = batchClassService .getBatchClassByIdentifier(kvExtract.getBatchClass()); DocumentType documentType = new DocumentType(); final List<DocumentType> docTypes = batchClass.getDocumentTypes(); if (docTypes != null && !docTypes.isEmpty()) { for (final DocumentType docType : docTypes) { if (documentName.equalsIgnoreCase(docType.getName())) { documentType = batchClass .getDocumentTypeByIdentifier(docType.getIdentifier()); } } } else { respStr = "Document Type doesn't Exist.Please enter a valid document type of batch class" + batchClass; final RestError restError = new RestError(HttpStatus.UNPROCESSABLE_ENTITY, WebServiceConstants.INPUT_XML_NOT_ABLE_TO_PARSE_CODE, respStr, WebServiceConstants.INPUT_XML_NOT_ABLE_TO_PARSE_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error("Error response at server:" + respStr); throw new InternalServerException(respStr, restError); } final List<com.ephesoft.dcma.batch.schema.HOCRFile> hocrFileList = new ArrayList<com.ephesoft.dcma.batch.schema.HOCRFile>(); final String hocrFileZipFileName = kvExtract.getHOCRFile(); final String unZipFileLocation = unZipToTemporaryOutputLocation(hocrFileZipFileName, workingDir); final File fPageFolder = new File(unZipFileLocation); final String[] listOfHOCRFiles = fPageFolder .list(new CustomFileFilter(false, FileType.XML.getExtensionWithDot())); for (final String hocrFileName : listOfHOCRFiles) { final HOCRFile hocrFile1 = new HOCRFile(); final HOCRFile.DocumentLevelFields dlfs = new HOCRFile.DocumentLevelFields(); LOGGER.info("Number of HOCR files" + listOfHOCRFiles.length); List<com.ephesoft.dcma.da.domain.FieldType> fieldTypes = null; if (documentType != null) { fieldTypes = documentType.getFieldTypes(); } else { respStr = "Document Type doesn't Exist.Please enter a valid document type of batch class" + batchClass; final RestError restError = new RestError(HttpStatus.UNPROCESSABLE_ENTITY, WebServiceConstants.INPUT_XML_NOT_ABLE_TO_PARSE_CODE, respStr, WebServiceConstants.INPUT_XML_NOT_ABLE_TO_PARSE_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error("Error response at server:" + respStr); throw new InternalServerException(respStr, restError); } if (fieldTypes != null && !fieldTypes.isEmpty()) { for (final com.ephesoft.dcma.da.domain.FieldType fieldType : fieldTypes) { final List<com.ephesoft.dcma.da.domain.KVExtraction> kvExtracttion = fieldType .getKvExtraction(); final List<DocField> updtDocList = new ArrayList<DocField>(5); if (kvExtracttion != null && !kvExtracttion.isEmpty()) { for (final com.ephesoft.dcma.da.domain.KVExtraction extractKVFields : kvExtracttion) { final ExtractKVParams params = new ExtractKVParams(); final OutputStream outStream = null; final InputStream instream = null; final Params paramList = new Params(); if (extractKVFields.getLocationType() != null) { paramList.setLocationType( extractKVFields.getLocationType().toString()); } if (extractKVFields.getNoOfWords() != null) { paramList.setNoOfWords(extractKVFields.getNoOfWords()); } if (extractKVFields.getKeyPattern() != null) { paramList.setKeyPattern(extractKVFields.getKeyPattern()); } if (extractKVFields.getValuePattern() != null) { paramList.setValuePattern(extractKVFields.getValuePattern()); } if (extractKVFields.getFetchValue() != null) { paramList.setKVFetchValue( extractKVFields.getFetchValue().toString()); } // Null values are allowed paramList.setWeight(extractKVFields.getWeight()); paramList.setKeyFuzziness(extractKVFields.getKeyFuzziness()); if (extractKVFields.getAdvancedKVExtraction() != null) { paramList.setLength(extractKVFields.getLength()); paramList.setWidth(extractKVFields.getWidth()); paramList.setXoffset(extractKVFields.getXoffset()); paramList.setYoffset(extractKVFields.getYoffset()); paramList.setMultiplier(Float.valueOf(1)); paramList.setAdvancedKV(true); final AdvancedKVExtraction advancedKVExtraction = extractKVFields .getAdvancedKVExtraction(); if (advancedKVExtraction != null) { keyRectangleCoordinates = new Coordinates(); valueRectangleCoordinates = new Coordinates(); keyRectangleCoordinates.setX0(BigInteger .valueOf(advancedKVExtraction.getKeyX0Coord())); keyRectangleCoordinates.setY0(BigInteger .valueOf(advancedKVExtraction.getKeyY0Coord())); keyRectangleCoordinates.setX1(BigInteger .valueOf(advancedKVExtraction.getKeyX1Coord())); keyRectangleCoordinates.setY1(BigInteger .valueOf(advancedKVExtraction.getKeyY1Coord())); valueRectangleCoordinates.setX0(BigInteger .valueOf(advancedKVExtraction.getValueX0Coord())); valueRectangleCoordinates.setY0(BigInteger .valueOf(advancedKVExtraction.getValueY0Coord())); valueRectangleCoordinates.setX1(BigInteger .valueOf(advancedKVExtraction.getValueX1Coord())); valueRectangleCoordinates.setY1(BigInteger .valueOf(advancedKVExtraction.getValueY1Coord())); } } params.getParams().add(paramList); final String filePath = unZipFileLocation + File.separator + hocrFileName; final HocrPages hocrPages = batchSchemaService.getHOCR(filePath); final boolean isSuccess = kvService.extractKVDocumentFieldsFromHOCR( updtDocList, hocrPages, params, keyRectangleCoordinates, valueRectangleCoordinates); // final boolean // isSuccess=kvService.extractKVFromHOCRForBatchClass(updtDocList,hocrPages,kvDocTypeLearning.getBatchClass(),kvDocTypeLearning.getDocumentType()); if (!isSuccess) { respStr = "Unable to perform KV Extraction for HOCR file" + hocrFileName; final RestError restError = new RestError( HttpStatus.UNPROCESSABLE_ENTITY, WebServiceConstants.INTERNAL_SERVER_ERROR_CODE, WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE, WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error("Error response at server:" + respStr); throw new InternalServerException(respStr, restError); } hocrFile1.setFileName(hocrFileName); } } final DocField docField = getDocLevelField(fieldType, updtDocList); dlfs.getDocumentLevelField().add(docField); } } else { respStr = "No Field Type is Defined for the document.Please try again."; final RestError restError = new RestError(HttpStatus.UNPROCESSABLE_ENTITY, WebServiceConstants.INPUT_XML_NOT_ABLE_TO_PARSE_CODE, respStr, WebServiceConstants.INPUT_XML_NOT_ABLE_TO_PARSE_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error("Error response at server:" + respStr); throw new InternalServerException(respStr, restError); } hocrFile1.setDocumentLevelFields(dlfs); extractKV.getHOCRFile().add(hocrFile1); } } else { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); final RestError restError = new RestError(HttpStatus.UNPROCESSABLE_ENTITY, WebServiceConstants.PARAMETER_XML_INCORRECT_CODE, inputXMLValidationRes, WebServiceConstants.PARAMETER_XML_INCORRECT_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error(WebServiceConstants.PARAMETER_XML_INCORRECT_MESSAGE + WebServiceConstants.HTTP_STATUS + HttpStatus.UNPROCESSABLE_ENTITY); throw new InternalServerException(inputXMLValidationRes, restError); } } else { respStr = WebServiceConstants.INPUT_FILES_NOT_FOUND_MESSAGE; final RestError restError = new RestError(HttpStatus.UNPROCESSABLE_ENTITY, WebServiceConstants.INPUT_FILES_NOT_FOUND_CODE, WebServiceConstants.INPUT_FILES_NOT_FOUND_MESSAGE, WebServiceConstants.INPUT_FILES_NOT_FOUND_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error(WebServiceConstants.INPUT_FILES_NOT_FOUND_MESSAGE + WebServiceConstants.HTTP_STATUS + HttpStatus.UNPROCESSABLE_ENTITY); throw new ValidationException(WebServiceConstants.INPUT_FILES_NOT_FOUND_MESSAGE, restError); } } else { respStr = WebServiceConstants.INPUT_FILES_NOT_FOUND_MESSAGE; final RestError restError = new RestError(HttpStatus.UNPROCESSABLE_ENTITY, WebServiceConstants.INPUT_FILES_NOT_FOUND_CODE, WebServiceConstants.INPUT_FILES_NOT_FOUND_MESSAGE, WebServiceConstants.INPUT_FILES_NOT_FOUND_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error(WebServiceConstants.INPUT_FILES_NOT_FOUND_MESSAGE + WebServiceConstants.HTTP_STATUS + HttpStatus.UNPROCESSABLE_ENTITY); throw new ValidationException(WebServiceConstants.INPUT_FILES_NOT_FOUND_MESSAGE, restError); } } catch (final ValidationException validationException) { throw validationException; } catch (final InternalServerException internalServerError) { throw internalServerError; } catch (final java.io.FileNotFoundException ex) { respStr = "Input File not found.Please check logs for Exception"; final RestError restError = new RestError(HttpStatus.UNPROCESSABLE_ENTITY, WebServiceConstants.INPUT_FILES_NOT_FOUND_CODE, WebServiceConstants.INPUT_FILES_NOT_FOUND_MESSAGE, WebServiceConstants.INPUT_FILES_NOT_FOUND_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error(WebServiceConstants.INPUT_FILES_NOT_FOUND_MESSAGE + WebServiceConstants.HTTP_STATUS + HttpStatus.UNPROCESSABLE_ENTITY + ex); throw new ValidationException(respStr, restError); } catch (final org.xml.sax.SAXParseException Ex) { respStr = "Error in Parsing Input XML.Please try again"; final RestError restError = new RestError(HttpStatus.UNPROCESSABLE_ENTITY, WebServiceConstants.INPUT_XML_NOT_ABLE_TO_PARSE_CODE, respStr, WebServiceConstants.INPUT_XML_NOT_ABLE_TO_PARSE_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error("Error response at server:" + respStr); if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } final InternalServerException internalServerExcpetion = new InternalServerException( WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE, restError); LOGGER.error(respStr + WebServiceConstants.HTTP_STATUS); throw internalServerExcpetion; } catch (final Exception exception) { final HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; respStr = WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE + exception; final RestError restError = new RestError(status, WebServiceConstants.INTERNAL_SERVER_ERROR_CODE, WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE, WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error("Error response at server:" + respStr); if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } final InternalServerException internalServerExcpetion = new InternalServerException( WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE, restError); LOGGER.error(respStr + WebServiceConstants.HTTP_STATUS + status); throw internalServerExcpetion; } } else { final HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; respStr = WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE; final RestError restError = new RestError(status, WebServiceConstants.IMPROPER_INPUT_TO_SERVER_CODE, WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE, WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY, WebServiceConstants.DEFAULT_URL); LOGGER.error(respStr + WebServiceConstants.HTTP_STATUS + status); throw new InternalServerException(WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE, restError); } if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } return extractKV; }
From source file:com.ephesoft.dcma.webservice.util.WebServiceHelper.java
public void processCreateHOCRXML(final HttpServletRequest req, final HttpServletResponse resp) throws InternalServerException, ValidationException { LOGGER.info("Start processing web service for create HOCR-XML for Batch Class"); String respStr = WebServiceUtil.EMPTY_STRING; String workingDir = WebServiceUtil.EMPTY_STRING; File zipInFolder = null;//from w ww .jav a 2 s. c om File zipOutFolder = null; int responseCode = 0; WebServiceParams webServiceParams = null; if (req instanceof DefaultMultipartHttpServletRequest) { try { final String webServiceFolderPath = batchSchemaService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir); final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req; final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap(); if (fileMap.size() != 2) { LOGGER.error("Invalid Number of files sent to the server"); respStr = WebServiceConstants.INVALID_ARGUMENTS_FOR_CREATE_HOCR; responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE; } else { String xmlFileName = WebServiceUtil.EMPTY_STRING; String zipOutputLocation = WebServiceUtil.EMPTY_STRING; String zipFileNameWithOutExt = WebServiceUtil.EMPTY_STRING; for (final String fileName : fileMap.keySet()) { InputStream instream = null; OutputStream outStream = null; ZipInputStream zipstream = null; try { if (!(fileName.endsWith(FileType.ZIP.getExtensionWithDot()) || fileName.endsWith(FileType.XML.getExtensionWithDot()) || fileName.endsWith(FileType.TIF.getExtensionWithDot()) || fileName.endsWith(FileType.TIFF.getExtensionWithDot()))) { respStr = WebServiceConstants.INVALID_ARGUMENTS_FOR_CREATE_OCR_BATCH_CLASS; responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE; } final MultipartFile multiPartFile = multiPartRequest.getFile(fileName); instream = multiPartFile.getInputStream(); if (fileName.endsWith(FileType.XML.getExtensionWithDot())) { xmlFileName = fileName; final File file = new File(workingDir + File.separator + fileName); outStream = new FileOutputStream(file); final byte[] buf = new byte[WebServiceUtil.bufferSize]; int len; while ((len = instream.read(buf)) > 0) { outStream.write(buf, 0, len); } } if (fileName.endsWith(FileType.ZIP.getExtensionWithDot())) { zipFileNameWithOutExt = FilenameUtils.removeExtension(fileName); zipInFolder = new File(workingDir + File.separator + zipFileNameWithOutExt); if (zipInFolder != null) { zipInFolder.mkdirs(); } zipstream = new ZipInputStream(instream); ZipEntry ze = zipstream.getNextEntry(); if (ze == null) { respStr = WebServiceConstants.NO_FILES_IN_ZIP_DIR; responseCode = WebServiceConstants.NO_FILES_IN_ZIP_DIR_CODE; LOGGER.error(respStr + " No files in the zip directory "); } while (ze != null) { String upzipFileName = ze.getName(); LOGGER.info("Unzipping " + upzipFileName); if (!(upzipFileName.endsWith(FileType.TIF.getExtensionWithDot()) || upzipFileName.endsWith(FileType.TIFF.getExtensionWithDot()) || upzipFileName.endsWith(FileType.PDF.getExtensionWithDot()))) { respStr = WebServiceConstants.UNSUPPORTED_FILE_TYPE_EXCEPTION_MESSAGE; responseCode = WebServiceConstants.UNSUPPORTED_FILE_TYPE_EXCEPTION_CODE; LOGGER.error("File name should be a valid tif, tiff or pdf file name only"); } final File filePath = new File(zipInFolder + File.separator + upzipFileName); outStream = new FileOutputStream(filePath); final byte[] buf = new byte[WebServiceUtil.bufferSize]; int len; while ((len = zipstream.read(buf)) > 0) { outStream.write(buf, 0, len); } final int pageCount = TIFFUtil .getTIFFPageCount(zipInFolder + File.separator + upzipFileName); if (pageCount > 1 || upzipFileName.endsWith(FileType.PDF.getExtensionWithDot())) { final BatchInstanceThread threadList = new BatchInstanceThread( new File(zipInFolder.toString()).getName() + Math.random()); LOGGER.info( "Start spliting multipage tiff/pdf file into tiffs using image magick"); imService.convertPdfOrMultiPageTiffToTiffUsingIM("", filePath, "", new File(EphesoftStringUtil.concatenate(zipInFolder.toString(), File.separator, upzipFileName)), threadList); threadList.execute(); } ze = zipstream.getNextEntry(); } } if (fileName.endsWith(FileType.TIFF.getExtensionWithDot()) || fileName.endsWith(FileType.TIF.getExtensionWithDot())) { zipFileNameWithOutExt = WebServiceUtil.EMPTY_STRING; final File file = new File(workingDir + File.separator + fileName); zipInFolder = new File(workingDir); outStream = new FileOutputStream(file); final byte[] buf = new byte[WebServiceUtil.bufferSize]; int len; while ((len = instream.read(buf)) > 0) { outStream.write(buf, 0, len); } final int pageCount = TIFFUtil .getTIFFPageCount(workingDir + File.separator + fileName); if (pageCount > 1) { final BatchInstanceThread threadList = new BatchInstanceThread( zipInFolder.getName() + Math.random()); LOGGER.info( "Start spliting multipage tiff/pdf file into tiffs using image magick"); imService.convertPdfOrMultiPageTiffToTiffUsingIM(WebServiceUtil.EMPTY_STRING, file, WebServiceUtil.EMPTY_STRING, new File(EphesoftStringUtil .concatenate(workingDir.toString(), File.separator, fileName)), threadList); threadList.execute(); } } } finally { IOUtils.closeQuietly(instream); IOUtils.closeQuietly(outStream); IOUtils.closeQuietly(zipstream); } } final File xmlFile = new File(workingDir + File.separator + xmlFileName); if (StringUtils.isNotEmpty(xmlFileName) && xmlFile.exists()) { final FileInputStream inputStream = new FileInputStream(xmlFile); final Source source = XMLUtil.createSourceFromStream(inputStream); final Object unmarshelledObject = batchSchemaDao.getJAXB2Template().getJaxb2Marshaller() .unmarshal(source); if (!(unmarshelledObject instanceof WebServiceParams)) { respStr = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_MESSAGE; responseCode = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_CODE; } else { webServiceParams = (WebServiceParams) unmarshelledObject; if (null != webServiceParams.getParams()) { final List<Param> paramList = webServiceParams.getParams().getParam(); if (paramList == null || paramList.isEmpty()) { final HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; respStr = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_MESSAGE; responseCode = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_CODE; LOGGER.error(respStr + "\n No Parameters in the request" + status); } else { String batchClassId = WebServiceUtil.EMPTY_STRING; for (final Param param : paramList) { if (WebServiceConstants.BATCH_CLASS_IDENTIFIER .equalsIgnoreCase(param.getName())) { batchClassId = param.getValue(); continue; } if (WebServiceUtil.ZIP_OUTPUT_LOCATION.equalsIgnoreCase(param.getName())) { zipOutputLocation = param.getValue(); if (StringUtils.isBlank(zipOutputLocation) || !(new File(zipOutputLocation).isDirectory())) { respStr = WebServiceConstants.ZIP_OUTPUT_LOCATION_INVALID_MESSAGE; responseCode = WebServiceConstants.ZIP_OUTPUT_LOCATION_INVALID_CODE; LOGGER.error( "Zip output location is blank or invalid in xml input file"); } continue; } if (WebServiceUtil.ZIP_NAME.equalsIgnoreCase(param.getName())) { if (!((zipFileNameWithOutExt + FileType.ZIP.getExtensionWithDot()) .equals(param.getValue()))) { respStr = WebServiceConstants.INPUT_ZIP_NOT_FOUND_MESSAGE; responseCode = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_CODE; LOGGER.error( "Zip file name doesn't match zip file name in xml input file"); } else continue; } } if (respStr == null || respStr.isEmpty()) { if (batchClassId != null && !batchClassId.isEmpty()) { final BatchClass batchClass = batchClassService .getBatchClassByIdentifier(batchClassId); if (batchClass != null) { final String ocrEngine = getDefaultHOCRPlugin(batchClassId); String colorSwitch = WebServiceUtil.EMPTY_STRING; String cmdLanguage = WebServiceUtil.EMPTY_STRING; LOGGER.info(EphesoftStringUtil.concatenate("Ocr engine used is : ", ocrEngine)); if (WebServiceConstants.TESSERACT_HOCR_PLUGIN .equalsIgnoreCase(ocrEngine)) { final File dir = new File(zipInFolder + ""); File[] directoryListing = dir.listFiles(); if (directoryListing != null) { zipOutFolder = new File( outputDir + File.separator + zipFileNameWithOutExt); if (zipOutFolder != null) { zipOutFolder.mkdirs(); } for (File inputFile : directoryListing) { String inputFileName = inputFile.getName(); if (inputFileName != null && !inputFileName.isEmpty()) { if (inputFileName.endsWith( FileType.TIFF.getExtensionWithDot()) || inputFileName.endsWith(FileType.TIF .getExtensionWithDot())) { final int pageCountTiff = TIFFUtil .getTIFFPageCount(inputFile.toString()); if (pageCountTiff > 1) { continue; } if (WebServiceConstants.TESSERACT_HOCR_PLUGIN .equalsIgnoreCase(ocrEngine)) { final BatchPlugin pluginProperties = classPluginPropertiesService .getPluginProperties(batchClassId, WebServiceConstants.TESSERACT_HOCR_PLUGIN); if (pluginProperties != null) { if (pluginProperties .getPluginConfigurations( TesseractProperties.TESSERACT_COLOR_SWITCH) != null) { colorSwitch = classPluginPropertiesService .getPropertyValue( batchClassId, WebServiceConstants.TESSERACT_HOCR_PLUGIN, TesseractProperties.TESSERACT_COLOR_SWITCH); if (pluginProperties .getPluginConfigurations( TesseractProperties.TESSERACT_LANGUAGE) != null) { cmdLanguage = classPluginPropertiesService .getPropertyValue( batchClassId, WebServiceConstants.TESSERACT_HOCR_PLUGIN, TesseractProperties.TESSERACT_LANGUAGE); tesseractService.createOCR( zipInFolder.toString(), colorSwitch, inputFileName, zipOutFolder.toString(), cmdLanguage, WebServiceConstants.TESSERACT_CURRENT_VERSION); } else { respStr = WebServiceConstants.NO_TESSERACT_LANGUAGE_SUPPORT; responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE; LOGGER.error( "No Language Support"); } } else { respStr = WebServiceConstants.NO_TESSERACT_COLOR_SWITCH; responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE; LOGGER.error( "Colour Switch Not Found"); } } else { respStr = WebServiceConstants.NO_PROPERTY_FOR_TESSERACT_HOCR; responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE; } } } } else { respStr = WebServiceConstants.INVALID_FILE_NAME; responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE; LOGGER.error( "File Name should not be NULL or empty "); } } // End of for loop } else { respStr = WebServiceConstants.NO_FILES_IN_ZIP_DIR; responseCode = WebServiceConstants.NO_FILES_IN_ZIP_DIR_CODE; LOGGER.error(respStr + " No files in the zip directory "); } } if (respStr.isEmpty()) { ServletOutputStream out = null; ZipOutputStream zout = null; final String zipFileName = WebServiceUtil.serverOutputFolderName; resp.setContentType(WebServiceUtil.APPLICATION_X_ZIP); resp.setHeader(WebServiceUtil.CONTENT_DISPOSITION, WebServiceUtil.ATTACHMENT_FILENAME + zipFileName + FileType.ZIP.getExtensionWithDot() + "\"\r\n"); resp.setStatus(HttpServletResponse.SC_OK); try { out = resp.getOutputStream(); zout = new ZipOutputStream(out); FileUtils.zipDirectory(zipOutFolder.toString(), zout, zipFileName); } catch (final FileNotFoundException fileNotFoundException) { String messageString = fileNotFoundException.getMessage(); messageString = messageString.substring( messageString.lastIndexOf(File.separator)); respStr = WebServiceConstants.FILE_NOT_FOUND + messageString; responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE; LOGGER.error("Could Not Copy the File " + fileNotFoundException.getMessage()); } catch (final IOException ioExcpetion) { respStr = WebServiceConstants.ERROR_WHILE_CREATING_ZIPPED_FILE + ioExcpetion; responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE; LOGGER.error(respStr); } finally { IOUtils.closeQuietly(zout); IOUtils.closeQuietly(out); } } if (respStr.isEmpty()) { FileOutputStream fos = null; ZipOutputStream zos = null; final File out = new File(zipOutputLocation + File.separator + zipFileNameWithOutExt + FileType.ZIP.getExtensionWithDot()); try { fos = new FileOutputStream(out); zos = new ZipOutputStream(fos); FileUtils.zipDirectory(zipOutFolder.toString(), zos, zipFileNameWithOutExt); } catch (final FileNotFoundException fileNotFoundException) { String messageString = fileNotFoundException.getMessage(); messageString = messageString.substring( messageString.lastIndexOf(File.separator)); respStr = WebServiceConstants.FILE_NOT_FOUND + messageString; responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE; LOGGER.error("Could Not Copy the File " + fileNotFoundException.getMessage()); } catch (final IOException ioExcpetion) { respStr = WebServiceConstants.ERROR_WHILE_CREATING_ZIPPED_FILE + ioExcpetion; responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE; LOGGER.error(respStr); } finally { IOUtils.closeQuietly(zos); IOUtils.closeQuietly(fos); } } } else { respStr = WebServiceConstants.INVALID_BATCH_CLASS_ID_MESSAGE; responseCode = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_CODE; LOGGER.error(respStr + " Batch Class ID doesnot exist "); } } else { respStr = WebServiceConstants.INVALID_BATCH_CLASS_ID_MESSAGE; responseCode = WebServiceConstants.INVALID_ARGUMENTS_IN_XML_INPUT_CODE; LOGGER.error(respStr + " No input of Batch Class ID "); } } } } } } else { respStr = WebServiceConstants.INPUT_FILES_NOT_FOUND_MESSAGE; responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE; } } } catch (final FileNotFoundException fileNotFoundException) { String message = fileNotFoundException.getMessage(); message = message.substring(message.lastIndexOf(File.separator)); respStr = WebServiceConstants.FILE_NOT_FOUND + message; } catch (final ValidationException validationException) { throw validationException; } catch (final InternalServerException internalServerError) { throw internalServerError; } catch (final Exception exception) { respStr = WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE + exception; responseCode = WebServiceConstants.INTERNAL_SERVER_ERROR_CODE; exception.printStackTrace(); } finally { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir)); } } else { respStr = WebServiceConstants.INVALID_MULTIPART_REQUEST; responseCode = WebServiceConstants.INVALID_PARAMETERS_CODE; } validateResponse(responseCode, respStr); }
From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java
/** * To create OCR./*w w w. ja v a 2 s . c o m*/ * @param req {@link HttpServletRequest} * @param resp {@link HttpServletResponse} */ @RequestMapping(value = "/createOCR", method = RequestMethod.POST) @ResponseBody public void createOCR(final HttpServletRequest req, final HttpServletResponse resp) { LOGGER.info("Start processing web service for create OCRing"); String respStr = WebServiceUtil.EMPTY_STRING; String workingDir = WebServiceUtil.EMPTY_STRING; InputStream instream = null; OutputStream outStream = null; if (req instanceof DefaultMultipartHttpServletRequest) { try { final String webServiceFolderPath = bsService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir); final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req; final BatchInstanceThread batchInstanceThread = new BatchInstanceThread( new File(workingDir).getName() + Math.random()); final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap(); if (!(fileMap.size() >= 2 && fileMap.size() <= WebserviceConstants.THREE)) { respStr = "Invalid number of files. We are supposed only 3 files each of type:XML, Project RSP file(if recostar tool) and tif/tiff/png file."; } if (respStr.isEmpty()) { String xmlFileName = WebServiceUtil.EMPTY_STRING; for (final String fileName : fileMap.keySet()) { try { if (fileName.endsWith(FileType.XML.getExtensionWithDot())) { xmlFileName = fileName; } final MultipartFile multiPartFile = multiPartRequest.getFile(fileName); instream = multiPartFile.getInputStream(); final File file = new File(workingDir + File.separator + fileName); outStream = new FileOutputStream(file); final byte[] buf = new byte[WebServiceUtil.bufferSize]; int len = instream.read(buf); while (len > 0) { outStream.write(buf, 0, len); len = instream.read(buf); } if (fileName.endsWith(FileType.TIF.getExtensionWithDot()) || fileName.endsWith(FileType.TIFF.getExtensionWithDot())) { int pageCount = TIFFUtil.getTIFFPageCount(workingDir + File.separator + fileName); if (pageCount > 1) { respStr = ONLY_ONE_SINGLE_PAGE_TIFF_EXPECTED; break; } } } finally { IOUtils.closeQuietly(instream); IOUtils.closeQuietly(outStream); } } WebServiceParams webServiceParams = null; final File xmlFile = new File(workingDir + File.separator + xmlFileName); if (xmlFile.exists()) { final FileInputStream inputStream = new FileInputStream(xmlFile); Source source = XMLUtil.createSourceFromStream(inputStream); webServiceParams = (WebServiceParams) batchSchemaDao.getJAXB2Template().getJaxb2Marshaller() .unmarshal(source); } List<Param> paramList = webServiceParams.getParams().getParam(); if (paramList == null || paramList.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); respStr = IMPROPER_XML_PARAMETER; } else { String ocrEngine = WebServiceUtil.EMPTY_STRING; String colorSwitch = WebServiceUtil.EMPTY_STRING; String projectFile = WebServiceUtil.EMPTY_STRING; String tesseractVersion = WebServiceUtil.EMPTY_STRING; String cmdLanguage = WebServiceUtil.EMPTY_STRING; for (final Param param : paramList) { if (param.getName().equalsIgnoreCase(WebServiceUtil.OCR_ENGINE)) { ocrEngine = param.getValue(); continue; } if (param.getName().equalsIgnoreCase(WebServiceUtil.COLOR_SWITCH)) { colorSwitch = param.getValue(); continue; } if (param.getName().equalsIgnoreCase(WebServiceUtil.PROJECT_FILE)) { projectFile = param.getValue(); LOGGER.info("Project file for recostar is :" + projectFile); continue; } if (param.getName().equalsIgnoreCase(WebServiceUtil.TESSERACT_VERSION)) { tesseractVersion = param.getValue(); LOGGER.info("Tesseract version is: " + tesseractVersion); continue; } if (param.getName().equalsIgnoreCase(WebServiceUtil.CMD_LANGUAGE)) { // supported values are "eng" and "tha" for now provided tesseract engine is learnt. cmdLanguage = param.getValue(); LOGGER.info("cmd langugage is :" + cmdLanguage); continue; } } String results = WebServiceUtil.validateCreateOCRAPI(workingDir, ocrEngine, colorSwitch, projectFile, tesseractVersion, cmdLanguage); if (!results.isEmpty()) { respStr = results; } else { String[] fileNames = null; final File file = new File(workingDir); if (colorSwitch.equalsIgnoreCase(WebServiceUtil.ON_STRING)) { String[] tifFileNames = file.list(new CustomFileFilter(false, FileType.TIF.getExtensionWithDot(), FileType.TIFF.getExtensionWithDot())); // generate png file for each tiff/tif file for (String tifFile : tifFileNames) { imService.generatePNGForImage(new File(workingDir + File.separator + tifFile)); } LOGGER.info("Picking up the png file for processing."); fileNames = file .list(new CustomFileFilter(false, FileType.PNG.getExtensionWithDot())); } else { LOGGER.info("Picking up the tif file for processing."); fileNames = file.list(new CustomFileFilter(false, FileType.TIF.getExtensionWithDot(), FileType.TIFF.getExtensionWithDot())); } LOGGER.info("Number of file is:" + fileNames.length); LOGGER.info("OcrEngine used for generating ocr is :" + ocrEngine); if (ocrEngine.equalsIgnoreCase(WebServiceUtil.RECOSTAR)) { if (fileNames != null && fileNames.length > 0) { for (final String fileName : fileNames) { try { LOGGER.info("File processing for recostar is :" + fileName); recostarService.createOCR(projectFile, workingDir, colorSwitch, fileName, batchInstanceThread, outputDir); } catch (final DCMAException e) { respStr = "Error occuring while creating OCR file using recostar. Please try again." + e; LOGGER.error(SERVER_ERROR_MSG + respStr); break; } } } else { if (colorSwitch.equalsIgnoreCase(WebServiceUtil.OFF_STRING)) { respStr = "Improper input to server. No tiff files provided."; } else { respStr = "Improper input to server. No tiff/png files provided."; } } } else if (ocrEngine.equalsIgnoreCase(WebServiceUtil.TESSERACT)) { if (fileNames != null && fileNames.length > 0) { for (final String fileName : fileNames) { try { LOGGER.info("File processing for ocr with tesseract is :" + fileName); tesseractService.createOCR(workingDir, colorSwitch, fileName, batchInstanceThread, outputDir, cmdLanguage, tesseractVersion); } catch (final DCMAException e) { respStr = "Error occuring while creating OCR file using tesseract. Please try again." + e; LOGGER.error(SERVER_ERROR_MSG + respStr); break; } } } else { respStr = "Improper input to server. No tiff/png files provided."; LOGGER.error(SERVER_ERROR_MSG + respStr); } } else { respStr = "Please select valid tool for generating OCR file."; } if (respStr.isEmpty()) { try { batchInstanceThread.execute(); if (ocrEngine.equalsIgnoreCase(WebServiceUtil.RECOSTAR)) { for (final String fileName : fileNames) { final String recostarXMLFileName = fileName.substring(0, fileName.lastIndexOf(WebServiceUtil.DOT)) + FileType.XML.getExtensionWithDot(); try { FileUtils.copyFile( new File(workingDir + File.separator + recostarXMLFileName), new File(outputDir + File.separator + recostarXMLFileName)); } catch (final Exception e) { respStr = "Error while generating copying result file." + e; LOGGER.error(SERVER_ERROR_MSG + respStr); break; } } } } catch (final DCMAApplicationException e) { respStr = "Exception while generating ocr using threadpool" + e; } if (respStr.isEmpty()) { ServletOutputStream out = null; ZipOutputStream zout = null; final String zipFileName = WebServiceUtil.SERVEROUTPUTFOLDERNAME; resp.setContentType(WebServiceUtil.APPLICATION_X_ZIP); resp.setHeader(WebServiceUtil.CONTENT_DISPOSITION, WebServiceUtil.ATTACHMENT_FILENAME + zipFileName + FileType.ZIP.getExtensionWithDot() + NEXT_LINE_STRING); try { out = resp.getOutputStream(); zout = new ZipOutputStream(out); FileUtils.zipDirectory(outputDir, zout, zipFileName); resp.setStatus(HttpServletResponse.SC_OK); } catch (final IOException e) { respStr = "Error in creating output zip file.Please try again." + e; LOGGER.error(SERVER_ERROR_MSG + respStr); } finally { IOUtils.closeQuietly(zout); IOUtils.closeQuietly(out); FileUtils.deleteDirectoryAndContentsRecursive( new File(workingDir).getParentFile()); } } } } } } } catch (final XmlMappingException xmle) { respStr = ERROR_IN_MAPPING_INPUT + xmle; LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final DCMAException dcmae) { respStr = ERROR_PROCESSING_REQUEST + dcmae; LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final Exception e) { respStr = INTERNAL_SERVER_ERROR + e; LOGGER.error(SERVER_ERROR_MSG + respStr); if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } else { respStr = IMPROPER_INPUT_TO_SERVER; LOGGER.error(SERVER_ERROR_MSG + respStr); } if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } if (!respStr.isEmpty()) { try { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr); LOGGER.error(SERVER_ERROR_MSG + respStr); } catch (final IOException ioe) { LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe); } } }
From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java
/** * To extract Field from Hocr./* w w w . jav a2s . 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 Searchable PDF.// ww w .j a v a 2 s.c o 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 split Multi page File.//from w w w .ja v a2 s .co 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.workflow.service.webservices.EphesoftWebServiceAPI.java
@RequestMapping(value = "/classifyBarcodeImage", method = RequestMethod.POST) @ResponseBody/*from www . java2 s.com*/ 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; 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<BarcodeProperties, String> batchClassConfigMap = new HashMap<BarcodeProperties, 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 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 id."; } else if (docAssemblyPlugin.getPluginConfigurations( DocumentAssemblerProperties.DA_BARCODE_CONFIDENCE) == null) { respStr = "Incomplete properties of the Document assembler plugin for the specified batch id."; } 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 id."; } } } 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 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."; } tiffFileName = file.getName(); break; } else { respStr = "Improper input to server. Expected only one tiff 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); 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.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.workflow.service.webservices.EphesoftWebServiceAPI.java
@RequestMapping(value = "/classifyImage", method = RequestMethod.POST) @ResponseBody/*from www . j a v a 2s . co m*/ public void classifyImage(final HttpServletRequest req, final HttpServletResponse resp) { logger.info("Start processing web service for classifyImage."); String respStr = WebServiceUtil.EMPTY_STRING; String workingDir = WebServiceUtil.EMPTY_STRING; if (req instanceof DefaultMultipartHttpServletRequest) { try { final String webServiceFolderPath = bsService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); InputStream instream = null; OutputStream outStream = null; final DefaultMultipartHttpServletRequest multipartReq = (DefaultMultipartHttpServletRequest) req; String batchClassId = WebServiceUtil.EMPTY_STRING; for (final Enumeration<String> params = multipartReq.getParameterNames(); params .hasMoreElements();) { final String paramName = params.nextElement(); if (paramName.equalsIgnoreCase("batchClassId")) { batchClassId = multipartReq.getParameter(paramName); break; } } if (batchClassId == null || batchClassId.isEmpty()) { respStr = "Batch Class identifier not specified."; } else { BatchClass bc = bcService.getBatchClassByIdentifier(batchClassId); if (bc == null) { respStr = "Batch class with the specified identifier does not exist."; } else { BatchPlugin createThumbPlugin = batchClassPPService.getPluginProperties(batchClassId, ImageMagicKConstants.CREATE_THUMBNAILS_PLUGIN); BatchPlugin classifyImgPlugin = batchClassPPService.getPluginProperties(batchClassId, ImageMagicKConstants.CLASSIFY_IMAGES_PLUGIN); BatchPlugin docAssemblyPlugin = batchClassPPService.getPluginProperties(batchClassId, DocumentAssemblerConstants.DOCUMENT_ASSEMBLER_PLUGIN); if (createThumbPlugin == null || classifyImgPlugin == null || docAssemblyPlugin == null) { respStr = "Either create Thumbnails plugin or Classify Image plugin or document assembly plugin does not exist for the specified batch id."; } else if (createThumbPlugin.getPluginConfigurations( ImageMagicProperties.CREATE_THUMBNAILS_OUTPUT_IMAGE_PARAMETERS) == null || createThumbPlugin.getPluginConfigurations( ImageMagicProperties.CREATE_THUMBNAILS_COMP_THUMB_WIDTH) == null || createThumbPlugin.getPluginConfigurations( ImageMagicProperties.CREATE_THUMBNAILS_COMP_THUMB_HEIGHT) == null) { respStr = "Create Thumbnails Height or width or output image parameters does not exist for the specified batch id."; } else if (classifyImgPlugin .getPluginConfigurations(ImageMagicProperties.CLASSIFY_IMAGES_COMP_METRIC) == null || classifyImgPlugin.getPluginConfigurations( ImageMagicProperties.CLASSIFY_IMAGES_MAX_RESULTS) == null || classifyImgPlugin.getPluginConfigurations( ImageMagicProperties.CLASSIFY_IMAGES_FUZZ_PERCNT) == null) { respStr = "Classify Images comp metric or fuzz percent or max results does not exist for the specified batch id."; } else if (docAssemblyPlugin .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_FP_MP_LP) == null || docAssemblyPlugin .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_FP) == null || docAssemblyPlugin .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_MP) == null || docAssemblyPlugin .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_LP) == null || docAssemblyPlugin .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_FP_LP) == null || docAssemblyPlugin .getPluginConfigurations(DocumentAssemblerProperties.DA_RULE_FP_MP) == null || docAssemblyPlugin.getPluginConfigurations( DocumentAssemblerProperties.DA_RULE_MP_LP) == null) { respStr = "Incomplete properties of the Document assembler plugin for the specified batch id."; } } } if (respStr.isEmpty()) { final String outputParams = batchClassPPService.getPropertyValue(batchClassId, ImageMagicKConstants.CREATE_THUMBNAILS_PLUGIN, ImageMagicProperties.CREATE_THUMBNAILS_OUTPUT_IMAGE_PARAMETERS); final MultiValueMap<String, MultipartFile> fileMap = multipartReq.getMultiFileMap(); if (fileMap.size() == 1) { String[][] sListOfTiffFiles = new String[fileMap.size()][3]; for (final String fileName : fileMap.keySet()) { // only single tiff file is expected as input if ((fileName.toLowerCase().indexOf(FileType.TIF.getExtension()) > -1 || fileName.toLowerCase().indexOf(FileType.TIFF.getExtension()) > -1)) { final MultipartFile f = multipartReq.getFile(fileName); instream = f.getInputStream(); final File file = new File(workingDir + File.separator + fileName); outStream = new FileOutputStream(file); final byte buf[] = new byte[1024]; int len; while ((len = instream.read(buf)) > 0) { outStream.write(buf, 0, len); } if (instream != null) { instream.close(); } if (outStream != null) { outStream.close(); } if (TIFFUtil.getTIFFPageCount(file.getAbsolutePath()) > 1) { respStr = "Improper input to server. Expected only one single page tiff file. Returning without processing the results."; } break; } else { respStr = "Improper input to server. Expected only one tiff file. Returning without processing the results."; } } if (respStr.isEmpty()) { String compareThumbnailH = batchClassPPService.getPropertyValue(batchClassId, ImageMagicKConstants.CREATE_THUMBNAILS_PLUGIN, ImageMagicProperties.CREATE_THUMBNAILS_COMP_THUMB_HEIGHT); String compareThumbnailW = batchClassPPService.getPropertyValue(batchClassId, ImageMagicKConstants.CREATE_THUMBNAILS_PLUGIN, ImageMagicProperties.CREATE_THUMBNAILS_COMP_THUMB_WIDTH); String batchId = new File(workingDir).getName() + Math.random(); ObjectFactory objectFactory = new ObjectFactory(); Pages pages = new Pages(); List<Page> listOfPages = pages.getPage(); String[] imageFiles = new File(workingDir).list(new CustomFileFilter(false, FileType.TIFF.getExtensionWithDot(), FileType.TIF.getExtensionWithDot())); for (int i = 0; i < imageFiles.length; i++) { String fileName = workingDir + File.separator + imageFiles[i]; String thumbFileName = "th" + FileType.TIF.getExtensionWithDot(); String fileTiffPath = workingDir + File.separator + thumbFileName; sListOfTiffFiles[i][0] = fileName; sListOfTiffFiles[i][1] = fileTiffPath; sListOfTiffFiles[i][2] = Integer.toString(i); Page pageType = objectFactory.createPage(); pageType.setIdentifier(EphesoftProperty.PAGE.getProperty() + i); pageType.setNewFileName(fileName); pageType.setOldFileName(fileName); pageType.setDirection(Direction.NORTH); pageType.setIsRotated(false); pageType.setComparisonThumbnailFileName(thumbFileName); listOfPages.add(pageType); } final BatchInstanceThread threadList = imService.createCompThumbForImage(batchId, workingDir, sListOfTiffFiles, outputParams, compareThumbnailH, compareThumbnailW); try { threadList.execute(); // invoke the Classification Image plugin String imMetric = batchClassPPService.getPropertyValue(batchClassId, ImageMagicKConstants.CLASSIFY_IMAGES_PLUGIN, ImageMagicProperties.CLASSIFY_IMAGES_COMP_METRIC); String imFuzz = batchClassPPService.getPropertyValue(batchClassId, ImageMagicKConstants.CLASSIFY_IMAGES_PLUGIN, ImageMagicProperties.CLASSIFY_IMAGES_FUZZ_PERCNT); String maxVal = batchClassPPService.getPropertyValue(batchClassId, ImageMagicKConstants.CLASSIFY_IMAGES_PLUGIN, ImageMagicProperties.CLASSIFY_IMAGES_MAX_RESULTS); imService.classifyImagesAPI(maxVal, imMetric, imFuzz, batchId, batchClassId, workingDir, listOfPages); // invoke the document assembler plugin List<Document> doc = docAssembler.createDocumentAPI( DocumentClassificationFactory.IMAGE, batchClassId, listOfPages); Documents docs = new Documents(); docs.getDocument().addAll(doc); StreamResult result; try { result = new StreamResult(resp.getOutputStream()); batchSchemaDao.getJAXB2Template().getJaxb2Marshaller().marshal(docs, result); } catch (final IOException e) { respStr = "Internal Server error.Please check logs for further details." + e; } } catch (final DCMAApplicationException e) { threadList.remove(); respStr = "Error while executing threadpool. Detailed exception is " + e; } catch (final DCMAException e) { threadList.remove(); respStr = "Error while executing threadpool. Detailed exception is " + e; } } } else { respStr = "Improper input to server. Expected only one tiff file. Returning without processing the results."; } } } catch (final Exception e) { respStr = "Internal Server error.Please check logs for further details." + e; if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } else { respStr = "Improper input to server. Expected multipart request. Returning without processing the results."; } if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } if (!respStr.isEmpty()) { try { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr); } catch (final IOException ioe) { } } }
From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java
/** * To classify Barcode Image./*from ww w . ja va 2s.com*/ * @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); } } }