Example usage for org.springframework.http HttpStatus UNPROCESSABLE_ENTITY

List of usage examples for org.springframework.http HttpStatus UNPROCESSABLE_ENTITY

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus UNPROCESSABLE_ENTITY.

Prototype

HttpStatus UNPROCESSABLE_ENTITY

To view the source code for org.springframework.http HttpStatus UNPROCESSABLE_ENTITY.

Click Source Link

Document

422 Unprocessable Entity .

Usage

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

/**
 * Import batch class internal. Process the request fetched from the Import Function and import the batch class using various DAO
 * Services/* ww w.j a  v  a  2  s . c o  m*/
 * 
 * @param workingDir {@link String} The working directory of the user
 * @param option {@link ImportBatchClassOptions} The import batch class options
 * @param zipFilePath {@link String} Path to the zipped file
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws ValidationException : When could not validate the input or input condition required for the request
 * @throws InternalServerException : When input is valid but server could not process the request
 */
private void importBatchClassInternal(final String workingDir, final ImportBatchClassOptions option,
        final String zipFilePath) throws IOException, InternalServerException, ValidationException {
    LOGGER.info("Reached Batch Class Internal");
    Set<String> assignedGroups = null;
    if (option != null && !zipFilePath.isEmpty()) {
        final Map<Boolean, String> results = importBatchService.validateInputXML(option);
        final String errorMsg = results.get(Boolean.FALSE);
        if (StringUtils.isNotBlank(errorMsg)) {
            throw new InternalServerException(
                    WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE + getAdditionalInfo(errorMsg),
                    createUnprocessableEntityRestError(
                            WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE + getAdditionalInfo(errorMsg),
                            WebServiceConstants.INTERNAL_SERVER_ERROR_CODE));
        } else {
            LOGGER.info("zip file path:" + zipFilePath);
            final File tempZipFile = new File(zipFilePath);
            final String tempOutputUnZipDir = tempZipFile.getParent() + File.separator
                    + tempZipFile.getName().substring(0, tempZipFile.getName().indexOf(WebServiceUtil.DOT));
            LOGGER.info("temporary Output UnZip Directory:" + tempOutputUnZipDir);
            try {
                FileUtils.unzip(tempZipFile, tempOutputUnZipDir);
            } catch (final Exception e) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                tempZipFile.delete();
                final String errorMessage = "Unable to unzip file. Returning without processing the results.";
                LOGGER.error(errorMessage);
                throw new InternalServerException(
                        WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE + getAdditionalInfo(errorMessage),
                        createUnprocessableEntityRestError(
                                WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE
                                        + getAdditionalInfo(errorMessage),
                                WebServiceConstants.INTERNAL_SERVER_ERROR_CODE));
            }

            option.setZipFilePath(tempOutputUnZipDir);
            LOGGER.info("Importing batch class");

            // JIRA-Bug-11092
            if (!option.isRolesImported()) {
                assignedGroups = userConnectivityService.getAllSuperAdminGroups();
            }
            final boolean isDeployed = deploymentService.isDeployed(option.getName());
            // final Map<Boolean, String> resultsImport =
            // importBatchService.importBatchClass(option, isDeployed, true,
            // assignedGroups);
            ImportBatchClassResultCarrier importBatchClassResultCarrier = importBatchService
                    .importBatchClass(option, isDeployed, true, assignedGroups);
            if (null != importBatchClassResultCarrier
                    && null != importBatchClassResultCarrier.getImportResults()) {
                final Map<Boolean, String> resultsImport = importBatchClassResultCarrier.getImportResults();
                final String errorMessgImport = resultsImport.get(Boolean.FALSE);
                if (StringUtils.isNotBlank(errorMessgImport)) {
                    throw new InternalServerException(
                            WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE
                                    + getAdditionalInfo(errorMessgImport),
                            createUnprocessableEntityRestError(
                                    WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE
                                            + getAdditionalInfo(errorMessgImport),
                                    WebServiceConstants.INTERNAL_SERVER_ERROR_CODE));
                } else {
                    final String batchClassId = resultsImport.get(Boolean.TRUE);
                    final BatchClass batchClass = batchClassService.get(batchClassId);
                    batchClassService.evict(batchClassService.getLoadedBatchClassByIdentifier(batchClassId));
                    deployBatchClass(batchClassId);
                    // if success in importing batch class and generating
                    // key,
                    // clear the HOCR files from diff folders.
                    // Adding check for use case as it has to be checked in
                    // case
                    // of Windows only.
                    if (OSUtil.isWindows() && !option.isUseKey()) {
                        try {
                            generateBatchClassLevelKey(option.getBatchClassKey(),
                                    option.getEncryptionAlgorithm(), batchClassId);
                        } catch (Exception e) {
                            RestError restError = new RestError(HttpStatus.INTERNAL_SERVER_ERROR,
                                    WebServiceConstants.INTERNAL_SERVER_ERROR_CODE, e.getMessage(),
                                    e.getMessage() + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY,
                                    WebServiceConstants.DEFAULT_URL);
                            LOGGER.error(WebServiceConstants.HTTP_STATUS + HttpStatus.UNPROCESSABLE_ENTITY);
                            InternalServerException internalServerExcpetion = new InternalServerException(
                                    WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE, restError);
                            throw internalServerExcpetion;
                        }
                        clearFoldersAfterKeyGeneration(option);
                    }
                    LOGGER.info("Batch class with identifier:" + batchClass.getIdentifier()
                            + " imported successfully.");
                }
            }
        }
    } else {
        LOGGER.error(WebServiceConstants.HTTP_STATUS + HttpStatus.UNPROCESSABLE_ENTITY);
        throw new ValidationException(WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE,
                createUnprocessableEntityRestError(WebServiceConstants.IMPROPER_INPUT_TO_SERVER_MESSAGE,
                        WebServiceConstants.IMPROPER_INPUT_TO_SERVER_CODE));
    }
}

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

private void deployBatchClass(final String batchClassId) throws InternalServerException {
    try {/*from   w ww.j a va 2  s.  c  o  m*/
        deployNewBatchClass(batchClassId, false);
    } catch (DCMAException dcmaException) {

        RestError restError = new RestError(HttpStatus.INTERNAL_SERVER_ERROR,
                WebServiceConstants.INTERNAL_SERVER_ERROR_CODE, dcmaException.getMessage(),
                dcmaException.getMessage() + WebServiceConstants.CLASS_WEB_SERVICE_UTILITY,
                WebServiceConstants.DEFAULT_URL);
        LOGGER.error(WebServiceConstants.HTTP_STATUS + HttpStatus.UNPROCESSABLE_ENTITY);
        InternalServerException internalServerExcpetion = new InternalServerException(
                WebServiceConstants.INTERNAL_SERVER_ERROR_MESSAGE, restError);
        throw internalServerExcpetion;
    }
}

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
 * //  www .j  a v a 2 s .  co  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
 * // www.  j a  v a2  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

/**
 * This Method contains functionality to copy document type of batch Class passed as an input
 * //from w w w  .j  a  v  a  2  s .  c  o  m
 * @param req {@link HttpServletRequest} the request header for this web service hit
 * @param resp {@link HttpServletResponse} the response header for this web service.
 */
public void processCopyDocumentType(final HttpServletRequest req)
        throws InternalServerException, ValidationException {
    {
        LOGGER.info("Processing Copy Document Type for Batch Class Web Service.");
        String respStr = WebServiceUtil.EMPTY_STRING;
        String workingDir = WebServiceUtil.EMPTY_STRING;
        DocumentType existingDoctype = new DocumentType();
        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();
                String xmlFileName = WebServiceConstants.EMPTY_STRING;
                LOGGER.info("Retreiving xml file.");
                CopyDocumentType copyDocType = null;
                xmlFileName = getXMLFile(workingDir, multiPartRequest, fileMap);
                LOGGER.info("XML file name is" + xmlFileName);
                final File xmlFile = new File(workingDir + File.separator + xmlFileName);
                if (xmlFile.exists()) {
                    final FileInputStream inputStream = new FileInputStream(xmlFile);
                    final Source source = XMLUtil.createSourceFromStream(inputStream);
                    copyDocType = (CopyDocumentType) batchSchemaDao.getJAXB2Template().getJaxb2Marshaller()
                            .unmarshal(source);
                    if (copyDocType != null && respStr.isEmpty()) {
                        // Create Method to Validate Input XML
                        respStr = validateCopyDocTypeInputXML(copyDocType);

                        if (respStr.isEmpty()) {
                            final DocumentType newDocumentType = new DocumentType();
                            final BatchClass batchClass = batchClassService
                                    .getBatchClassByIdentifier(copyDocType.getBatchClassId());
                            final List<DocumentType> documentList = batchClass.getDocumentTypes();
                            if (documentList != null) {
                                for (final DocumentType docType : documentList) {
                                    if (docType.getName().equals(copyDocType.getExistingDocTypeName())) {
                                        existingDoctype = batchClass
                                                .getDocumentTypeByIdentifier(docType.getIdentifier());
                                    }
                                }
                            }
                            newDocumentType.setName(copyDocType.getNewDocumentType().getName());
                            newDocumentType.setDescription(copyDocType.getNewDocumentType().getDescription());
                            newDocumentType.setMinConfidenceThreshold(Float
                                    .parseFloat(copyDocType.getNewDocumentType().getConfidenceThreshold()));
                            if (existingDoctype.getFirstPageProjectFileName() != null) {
                                newDocumentType.setFirstPageProjectFileName(
                                        existingDoctype.getFirstPageProjectFileName());
                            }
                            if (existingDoctype.getSecondPageProjectFileName() != null) {
                                newDocumentType.setFirstPageProjectFileName(
                                        existingDoctype.getSecondPageProjectFileName());
                            }
                            if (existingDoctype.getThirdPageProjectFileName() != null) {
                                newDocumentType.setFirstPageProjectFileName(
                                        existingDoctype.getThirdPageProjectFileName());
                            }
                            if (existingDoctype.getFourthPageProjectFileName() != null) {
                                newDocumentType.setFirstPageProjectFileName(
                                        existingDoctype.getFourthPageProjectFileName());
                            }
                            docTypeService.copyDocumentType(existingDoctype, newDocumentType);
                            batchClass.addDocumentType(newDocumentType);
                            batchClassService.merge(batchClass);
                        } else {
                            final RestError restError = new RestError(HttpStatus.UNPROCESSABLE_ENTITY,
                                    WebServiceConstants.PARAMETER_XML_INCORRECT_CODE, respStr,
                                    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(respStr, 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 XmlMappingException xmle) {
                respStr = "Error in mapping input XML. Please send it in the specified format.";
                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(WebServiceConstants.INPUT_XML_NOT_ABLE_TO_PARSE_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 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 {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        } 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

/**
 * Creates the UNPROCESSABLE Entity Rest Error with the Response Code and the response Message.
 * // w  ww  . j a v a2 s.c  om
 * @param responseString {@link String}
 * @param responseCode int
 */
public static RestError createUnprocessableEntityRestError(final String responseString,
        final int responseCode) {
    final RestError restError = new RestError(HttpStatus.UNPROCESSABLE_ENTITY, responseCode, responseString,
            responseString, WebServiceConstants.DEFAULT_URL);
    return restError;
}

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

private void validateResponse(final int responseCode, final String respStr)
        throws ValidationException, InternalServerException {
    if (!respStr.isEmpty()) {
        final RestError error = new RestError(HttpStatus.UNPROCESSABLE_ENTITY, responseCode, respStr, respStr,
                WebServiceConstants.DEFAULT_URL);
        if (responseCode == WebServiceConstants.INTERNAL_SERVER_ERROR_CODE) {
            throw new ValidationException(respStr, error);
        } else {//from   ww w.  j av  a 2 s  . c o  m
            throw new InternalServerException(respStr, error);
        }
    }
}

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

/**
 * Creates and throws {@link ValidationException} with specified batch instance, error code and error message.
 * /*from  www .j av a 2 s  . c o m*/
 * @param batchClassIdentifier to be logged in error message.
 * @param code for error.
 * @param message for error.
 * @throws ValidationException with specified message and error.
 */
private void createAndThrowValidationException(final String batchClassIdentifier, final int code,
        final String message) throws ValidationException {
    if (null == batchClassIdentifier) {
        LOGGER.error(EphesoftStringUtil.concatenate(message, WebServiceConstants.ERROR_CODE_MESSAGE, code));
        throw new ValidationException(message,
                new RestError(HttpStatus.INTERNAL_SERVER_ERROR, code, message,
                        EphesoftStringUtil.concatenate(message, WebServiceConstants.CLASS_WEB_SERVICE_UTILITY),
                        WebServiceConstants.DEFAULT_URL));
    } else {
        LOGGER.error(EphesoftStringUtil.concatenate(message, code, batchClassIdentifier));
        throw new ValidationException(
                EphesoftStringUtil.concatenate(message, getAdditionalInfo(batchClassIdentifier)),
                new RestError(HttpStatus.UNPROCESSABLE_ENTITY, code,
                        EphesoftStringUtil.concatenate(message, getAdditionalInfo(batchClassIdentifier)),
                        EphesoftStringUtil.concatenate(message, getAdditionalInfo(batchClassIdentifier),
                                WebServiceConstants.CLASS_WEB_SERVICE_UTILITY),
                        WebServiceConstants.DEFAULT_URL));
    }
}

From source file:de.tobiasbruns.content.storage.ContentController.java

@RequestMapping(method = RequestMethod.GET, params = "projection=content")
public void loadContentData(HttpServletRequest req, HttpServletResponse response) throws IOException {
    ContentHeader header = service.loadContentHeader(getPath(req));

    if (header.getType() == ContentItemType.NODE) {
        response.sendError(HttpStatus.UNPROCESSABLE_ENTITY.value());
        return;/*from   w w w.ja va 2  s .  com*/
    }

    response.setContentType(header.getContentType().orElse("application/octet-stream"));
    IOUtils.copy(service.loadContentData(getPath(req)), response.getOutputStream());
}

From source file:org.cloudfoundry.identity.uaa.account.ResetPasswordController.java

private String handleUnprocessableEntity(Model model, HttpServletResponse response, String attributeKey,
        String attributeValue) {/*from  ww  w.j  a  v  a  2  s.  c o m*/
    model.addAttribute(attributeKey, attributeValue);
    response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
    return "forgot_password";
}