Example usage for javax.servlet ServletOutputStream flush

List of usage examples for javax.servlet ServletOutputStream flush

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:com.ibm.ioes.actions.NewOrderAction.java

/**
 * Method to get all data for Masters Download
 * @param mapping//  w  w  w . ja  va2  s.  c  o  m
 * @param form
 * @param request
 * @param response
 * @return
 */
public ActionForward downloadMasters(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {

    NewOrderModel objModel = new NewOrderModel();
    NewOrderBean formBean = (NewOrderBean) form;
    //formBean.getProductID()
    HSSFWorkbook wb = objModel.downloadMasters(Long.parseLong(formBean.getHdnSelectedServiceDetailId()));
    formBean.setExcelWorkbookFormaster(wb);

    response.setHeader("Content-Disposition", "attachment; filename=Masters.xls");

    try {
        ServletOutputStream out = response.getOutputStream();
        formBean.getExcelWorkbookFormaster().write(out);
        out.flush();
        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

From source file:org.fcrepo.server.access.FedoraAccessServlet.java

public void getDatastreamDissemination(Context context, String PID, String dsID, Date asOfDateTime,
        HttpServletResponse response, HttpServletRequest request) throws IOException, ServerException {
    ServletOutputStream out = null;
    MIMETypedStream dissemination = null;
    dissemination = m_access.getDatastreamDissemination(context, PID, dsID, asOfDateTime);
    try {//from  www.j a va  2  s . com
        // testing to see what's in request header that might be of interest
        if (logger.isDebugEnabled()) {
            for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                Enumeration<?> headerValues = request.getHeaders(name);
                StringBuffer sb = new StringBuffer();
                while (headerValues.hasMoreElements()) {
                    sb.append((String) headerValues.nextElement());
                }
                String value = sb.toString();
                logger.debug("FEDORASERVLET REQUEST HEADER CONTAINED: {} : {}", name, value);
            }
        }

        // Dissemination was successful;
        // Return MIMETypedStream back to browser client
        if (dissemination.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            String location = "";
            for (Property prop : dissemination.header) {
                if (prop.name.equalsIgnoreCase(HttpHeaders.LOCATION)) {
                    location = prop.value;
                    break;
                }
            }

            response.sendRedirect(location);
        } else {
            int status = dissemination.getStatusCode();
            response.setStatus(status);
            if (status == HttpStatus.SC_OK) {
                response.setContentType(dissemination.getMIMEType());
            }
            Property[] headerArray = dissemination.header;
            if (headerArray != null) {
                for (int i = 0; i < headerArray.length; i++) {
                    if (headerArray[i].name != null
                            && !headerArray[i].name.equalsIgnoreCase("transfer-encoding")
                            && !headerArray[i].name.equalsIgnoreCase("content-type")) {
                        response.addHeader(headerArray[i].name, headerArray[i].value);
                        logger.debug(
                                "THIS WAS ADDED TO FEDORASERVLET RESPONSE HEADER FROM ORIGINATING PROVIDER {} : {}",
                                headerArray[i].name, headerArray[i].value);
                    }
                }
            }
            out = response.getOutputStream();
            int byteStream = 0;
            logger.debug("Started reading dissemination stream");
            InputStream dissemResult = dissemination.getStream();
            byte[] buffer = new byte[BUF];
            while ((byteStream = dissemResult.read(buffer)) != -1) {
                out.write(buffer, 0, byteStream);
            }
            buffer = null;
            dissemResult.close();
            dissemResult = null;
            out.flush();
            out.close();
            logger.debug("Finished reading dissemination stream");
        }
    } finally {
        dissemination.close();
    }
}

From source file:com.ibm.ioes.actions.NewOrderAction.java

public ActionForward downloadTemplateExcelForPrdCatelog(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
    String forwardMapping = null;

    try {//from w  w  w  .  j a  va2s. c o  m

        NewOrderBean formBean = (NewOrderBean) form;
        NewOrderModel model = new NewOrderModel();
        //String[] serviceProductId=request.getParameterValues("chk_spId");

        //make excel
        model.downloadTemplateExcelForPrdCatelog(formBean);
        //send excel in request
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=ProductCatelogExcel.xls");
        ServletOutputStream out = response.getOutputStream();
        formBean.getProductCatelogTemplateWorkbook().write(out);
        out.flush();
        out.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        //AppConstants.NPDLOGGER.error(ex.getMessage()
        //   + " Exception occured in downloadPlanExcelForEdit method of "
        //   + this.getClass().getSimpleName()+AppUtility.getStackTrace(ex));
        forwardMapping = Messages.getMessageValue("errorGlobalForward");
        return mapping.findForward(forwardMapping);
    }

    return null;
}

From source file:com.ibm.ioes.actions.NewOrderAction.java

public ActionForward goToDownloadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    NewOrderBean formBean = (NewOrderBean) form;
    //String fileName=formBean.getFileName();
    ActionForward forward = new ActionForward();
    ActionMessages messages = new ActionMessages();

    FileAttachmentDto downloadedFile = new FileAttachmentDto();

    CommonBaseModel commonBaseModel = new CommonBaseModel();
    byte[] File = null;

    FileAttachmentDto fileDto = new FileAttachmentDto();
    fileDto.setHdnOrderNo(request.getParameter("hdnOrderNo"));
    fileDto.setHdnAccountNo(request.getParameter("accountID"));

    //--Added & modified by vijay--//
    /*these code is modify for solving the error 
      of downloading file whose name contain special characters */

    //fileDto.setFileName(request.getParameter("fileName"));
    fileDto.setFileName(request.getParameter("hdnFileName"));
    fileDto.setCreateDate(request.getParameter("createDate"));
    //String slNO=request.getParameter("sLNO");
    //fileDto.setSlno(Integer.parseInt(slNO));
    String slNO = request.getParameter("hdnslno");
    fileDto.setSlno(Integer.parseInt(slNO));

    //--end of code--//

    NewOrderModel objModel = new NewOrderModel();
    downloadedFile = objModel.getDownloadedFile(fileDto);
    //java.sql.Blob blob=null;
    File = commonBaseModel.blobToByteArray(downloadedFile.getFile());
    String ContentType = commonBaseModel.setContentTypeForFile(downloadedFile.getFileName());//CHANGES FOR SYSTEM TESTING DEFECTS
    response.setContentType(ContentType);

    //---added by vijay--//

    //response.setHeader("Content-Disposition","attachment;filename=" + downloadedFile.getFileName());//CHANGES FOR SYSTEM TESTING DEFECTS

    /*/*from w w w . j  ava 2s. c om*/
     * Here file name is encoded and space is replace by special secequence of charcters,
     * because if file name contain space then bydefault space is converting in a plus sign (+) while downloading,
     * so for recognize any space in file name, space is replacing by this string @%20@
     */
    String encodedFileName = java.net.URLEncoder.encode(downloadedFile.getFileName().replace(" ", "@%20@"),
            "ISO-8859-1");
    System.out.println("encoded file name is - " + encodedFileName);
    /* 
     * After encoding file name, for maintaing the space character, again replace this special sequence %40%2520%40% with space character.
     * This sequence of characters %40%2520%40% means file name containg space space 
     */
    response.setHeader("Content-Disposition",
            "attachment;filename=" + encodedFileName.replace("%40%2520%40", " "));

    //--end of code--//

    ServletOutputStream outs = response.getOutputStream();
    outs.write(File);
    outs.flush();
    outs.close();

    if (downloadedFile.getIsDownload().equalsIgnoreCase("1")) {
        formBean.setIsDownload("successDownload");
        forward = mapping.findForward("");
    } else {
        messages.add("saveDownloadFile", new ActionMessage("FileDownloadFailed"));
        saveMessages(request, messages);
        forward = mapping.findForward("");
    }

    try {

    } catch (Exception e) {
        AppConstants.IOES_LOGGER.error(AppUtility.getStackTrace(e));
    }
    return forward;
}

From source file:edu.harvard.iq.dataverse.DatasetPage.java

public void downloadRsyncScript() {

    String bibFormatDowload = new BibtexCitation(workingVersion).toString();
    FacesContext ctx = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
    response.setContentType("application/download");

    String contentDispositionString;

    contentDispositionString = "attachment;filename=" + rsyncScriptFilename;
    response.setHeader("Content-Disposition", contentDispositionString);

    try {/*from   www  .  java  2s.co  m*/
        ServletOutputStream out = response.getOutputStream();
        out.write(getRsyncScript().getBytes());
        out.flush();
        ctx.responseComplete();
    } catch (IOException e) {
        String error = "Problem getting bytes from rsync script: " + e;
        logger.warning(error);
        return;
    }

    // If the script has been successfully downloaded, lock the dataset:
    String lockInfoMessage = "script downloaded";
    DatasetLock lock = datasetService.addDatasetLock(dataset.getId(), DatasetLock.Reason.DcmUpload,
            session.getUser() != null ? ((AuthenticatedUser) session.getUser()).getId() : null,
            lockInfoMessage);
    if (lock != null) {
        dataset.addLock(lock);
    } else {
        logger.log(Level.WARNING, "Failed to lock the dataset (dataset id={0})", dataset.getId());
    }

}

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

@RequestMapping(value = "/splitMultipageFile", method = RequestMethod.POST)
@ResponseBody/*from w ww .  j a  va 2 s .  c  o  m*/
public void splitMultipageFile(final HttpServletRequest req, final HttpServletResponse resp) {
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    try {
        if (req instanceof DefaultMultipartHttpServletRequest) {
            logger.info("Start spliting multipage file");
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir);

            InputStream instream = null;
            OutputStream outStream = null;

            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;

            final BatchInstanceThread threadList = new BatchInstanceThread(
                    new File(workingDir).getName() + Math.random());
            String inputParams = WebServiceUtil.EMPTY_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("isGhostscript")) {
                    isGSTool = Boolean.parseBoolean(multiPartRequest.getParameter(paramName));
                    logger.info("Value for isGhostscript parameter is " + isGSTool);
                    continue;
                }

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

                if (paramName.equalsIgnoreCase("outputParams")) {
                    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 {

                for (final String fileName : fileMap.keySet()) {
                    if (fileName.toLowerCase().indexOf(FileType.PDF.getExtension()) > -1
                            || fileName.toLowerCase().indexOf(FileType.TIF.getExtension()) > -1
                            || fileName.toLowerCase().indexOf(FileType.TIFF.getExtension()) > -1) {
                        // only tiffs and RSP file is expected
                        if (isGSTool && (fileName.toLowerCase().indexOf(FileType.TIF.getExtension()) > -1
                                || fileName.toLowerCase().indexOf(FileType.TIFF.getExtension()) > -1)) {
                            respStr = "Only PDF files expected with GhostScript tool.";
                            break;
                        }
                        final MultipartFile multipartFile = multiPartRequest.getFile(fileName);
                        instream = multipartFile.getInputStream();
                        final File file = new File(workingDir + File.separator + fileName);
                        outStream = new FileOutputStream(file);
                        final byte[] buf = new byte[WebServiceUtil.bufferSize];
                        int len;
                        while ((len = instream.read(buf)) > 0) {
                            outStream.write(buf, 0, len);
                        }
                        if (instream != null) {
                            instream.close();
                        }

                        if (outStream != null) {
                            outStream.close();
                        }
                    } else {
                        respStr = "Files other than tiff, tif and pdf formats are provided.";
                        break;
                    }
                }
                if (respStr.isEmpty()) {
                    for (final String fileName : fileMap.keySet()) {
                        final File file = new File(workingDir + File.separator + fileName);
                        if (isGSTool) {
                            logger.info(
                                    "Start spliting multipage file using ghost script for file :" + fileName);
                            imService.convertPdfToSinglePageTiffsUsingGSAPI(inputParams, file, outputParams,
                                    new File(outputDir + File.separator + fileName), threadList);
                        } else {
                            logger.info(
                                    "Start spliting multipage file using image magick for file :" + fileName);
                            imService.convertPdfOrMultiPageTiffToTiffUsingIM(inputParams, file, outputParams,
                                    new File(outputDir + File.separator + fileName), threadList);
                        }
                    }
                    try {
                        logger.info("Executing batch instance thread using thread pool");
                        threadList.execute();
                    } catch (final DCMAApplicationException e) {
                        threadList.remove();
                        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                        throw new Exception(e.getMessage(), e);
                    }

                    ServletOutputStream out = null;
                    ZipOutputStream zout = null;
                    final String zipFileName = WebServiceUtil.serverOutputFolderName;
                    resp.setContentType("application/x-zip\r\n");
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName
                            + FileType.ZIP.getExtensionWithDot() + "\"\r\n");
                    try {
                        out = resp.getOutputStream();
                        zout = new ZipOutputStream(out);
                        FileUtils.zipDirectory(outputDir, zout, zipFileName);
                        resp.setStatus(HttpServletResponse.SC_OK);
                    } catch (final IOException e) {
                        respStr = "Unable to process web service request.Please check you ghostscipt or imagemagick configuration.";
                    } finally {
                        if (zout != null) {
                            zout.close();
                        }
                        if (out != null) {
                            out.flush();
                        }
                        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                    }
                }
            }
        } else {
            respStr = "Improper input to server. Expected multipart request. Returning without processing the results.";
        }
    } catch (Exception e) {
        respStr = "Internal Server error.Please check logs for further details." + e;
    }
    if (!workingDir.isEmpty()) {
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {

        }
    }
}

From source file:org.openmrs.module.mohtracportal.util.FileExporter.java

/**
 * Auto generated method comment/*from  w w  w  .  j a  va 2  s. c o  m*/
 * 
 * @param request
 * @param response
 * @param res
 * @param filename
 * @param title
 * @param to
 * @param from
 * @param selectedUsers
 * @throws Exception
 */
public void exportToCSVFile(HttpServletRequest request, HttpServletResponse response, List<Object> res,
        String filename, String title, String from, String to, List<Integer> selectedUsers) throws Exception {

    SimpleDateFormat sdf = Context.getDateFormat();
    ServletOutputStream outputStream = null;

    try {
        outputStream = response.getOutputStream();
        PersonService ps = Context.getPersonService();

        String users = "";
        for (Integer usrId : selectedUsers) {
            users += ps.getPerson(usrId).getPersonName() + "; ";
        }

        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        outputStream.println(MohTracUtil.getMessage("mohtracportal.report.title", null) + ", : " + title);
        if (from.trim().compareTo("") != 0)
            outputStream.println(MohTracUtil.getMessage("mohtracportal.from", null) + ", : " + from);
        if (to.trim().compareTo("") != 0)
            outputStream.println(MohTracUtil.getMessage("mohtracportal.to", null) + ", : " + to);
        outputStream.println(MohTracUtil.getMessage("mohtracportal.report.created.on", null) + ", : "
                + sdf.format(new Date()));// Report
        // date
        outputStream.println(MohTracUtil.getMessage("mohtracportal.report.created.by", null) + ", : "
                + Context.getAuthenticatedUser().getPersonName());// Report
        // author
        if (users.trim().compareTo("") != 0)
            outputStream
                    .println(MohTracUtil.getMessage("mohtracportal.patient.enterers", null) + ", : " + users);
        outputStream.println();
        Integer numberOfPatients = res.size();
        outputStream.println(MohTracUtil.getMessage("mohtracportal.numberOfPatients", null) + ", "
                + numberOfPatients.toString());
        outputStream.println();

        boolean hasPrivToViewPatientNames = Context.getAuthenticatedUser().hasPrivilege("View Patient Names");

        outputStream.println(MohTracUtil.getMessage("mohtracportal.report.list.no", null) + ","
                + ((hasPrivToViewPatientNames)
                        ? MohTracUtil.getMessage("mohtracportal.patient.names", null) + ", "
                        : "")
                + MohTracPortalTag.getIdentifierTypeNameByIdAsString(
                        "" + MohTracConfigurationUtil.getTracNetIdentifierTypeId())
                + ", "
                + MohTracPortalTag.getIdentifierTypeNameByIdAsString(
                        "" + MohTracConfigurationUtil.getLocalHealthCenterIdentifierTypeId())
                + ", " + MohTracUtil.getMessage("mohtracportal.patient.date.created", null) + "("
                + Context.getDateFormat().toPattern() + "), "
                + MohTracUtil.getMessage("mohtracportal.numberOfEncounters", null));
        outputStream.println();

        int ids = 0;

        for (Object patient : res) {
            Object[] o = (Object[]) patient;

            ids += 1;
            outputStream.println(ids + ","
                    + ((hasPrivToViewPatientNames)
                            ? MohTracPortalTag.getPersonNames(Integer.valueOf(o[0].toString())) + ","
                            : "")
                    + MohTracPortalTag.personIdentifierByPatientIdAndIdentifierTypeId(
                            Integer.valueOf(o[0].toString()),
                            MohTracConfigurationUtil.getTracNetIdentifierTypeId())
                    + ","
                    + MohTracPortalTag.personIdentifierByPatientIdAndIdentifierTypeId(
                            Integer.valueOf(o[0].toString()),
                            MohTracConfigurationUtil.getLocalHealthCenterIdentifierTypeId())
                    + "," + sdf.format(o[1]) + ","
                    + MohTracPortalTag.getNumberOfEncounterByPatient(Integer.valueOf(o[0].toString())));
        }

        outputStream.flush();
        log.info("csv File created");
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    } finally {
        if (null != outputStream)
            outputStream.close();
    }
}

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

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

            InputStream instream = null;
            OutputStream outStream = null;

            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;

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

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

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

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

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

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

            }

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

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

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

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

        }
    }
}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

private void writeRangesData(DataSource data, List<AcceptRange> ranges, HttpServletResponse response,
        String dbHint, long size) throws IOException, HttpErrorException, UnsupportedEncodingException {

    ServletOutputStream out = response.getOutputStream();
    for (AcceptRange range : ranges) {
        InputStream in = data.getInputStream();
        if (in == null) {
            throw new HttpErrorException(404, "File not found: " + data.getName(), dbHint);
        }//from   ww  w.ja v a2 s.c o  m

        if (ranges.size() != 1) {
            out.println();
            out.println("--" + BYTERANGE_BOUNDARY);
            out.println("Content-Type: " + data.getContentType());
            out.println("Content-Range: bytes " + range.from + "-" + range.to + "/" + size);
            out.println();
        }

        if (range.from > 0) {
            in.skip(range.from);
        }

        try {
            WGUtils.inToOutLimited(in, out, (new Long(range.to - range.from + 1)).intValue(), 2048);
            out.flush();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    }

    if (ranges.size() != 1) {
        out.println();
        out.print("--" + BYTERANGE_BOUNDARY + "--");
        out.flush();
    }

}

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

@RequestMapping(value = "/createMultiPageFile", method = RequestMethod.POST)
@ResponseBody/*from  w ww  . jav a  2 s. c  o m*/
public void createMultiPageFile(final HttpServletRequest req, final HttpServletResponse resp) {
    logger.info("Start processing web service for createMultiPageFile.");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    if (req instanceof DefaultMultipartHttpServletRequest) {
        try {
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir);
            InputStream instream = null;
            OutputStream outStream = null;
            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;
            final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();
            String xmlFileName = WebServiceUtil.EMPTY_STRING;
            List<File> fileList = new ArrayList<File>();
            for (final String fileName : fileMap.keySet()) {
                if (fileName.endsWith(FileType.XML.getExtensionWithDot())
                        || fileName.endsWith(FileType.TIF.getExtensionWithDot())
                        || fileName.endsWith(FileType.TIFF.getExtensionWithDot())) {
                    final File file = new File(workingDir + File.separator + fileName);
                    if (fileName.endsWith(FileType.XML.getExtensionWithDot())) {
                        xmlFileName = fileName;
                    } else {
                        fileList.add(file);
                    }
                    final MultipartFile multiPartFile = multiPartRequest.getFile(fileName);
                    instream = multiPartFile.getInputStream();
                    outStream = new FileOutputStream(file);
                    final byte[] buf = new byte[WebServiceUtil.bufferSize];
                    int len;
                    while ((len = instream.read(buf)) > 0) {
                        outStream.write(buf, 0, len);
                    }
                    if (instream != null) {
                        instream.close();
                    }
                    if (outStream != null) {
                        outStream.close();
                    }
                } else {
                    respStr = "Expected only tif, tiff files.";
                }
            }
            if (respStr.isEmpty()) {
                final File xmlFile = new File(workingDir + File.separator + xmlFileName);
                final FileInputStream inputStream = new FileInputStream(xmlFile);
                Source source = XMLUtil.createSourceFromStream(inputStream);
                final WebServiceParams webServiceParams = (WebServiceParams) batchSchemaDao.getJAXB2Template()
                        .getJaxb2Marshaller().unmarshal(source);
                if (webServiceParams.getParams() == null || webServiceParams.getParams().getParam() == null
                        || webServiceParams.getParams().getParam().isEmpty()) {
                    FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                    respStr = "Improper input to server. Parameter XML is incorrect. Returning without processing the results.";
                } else {
                    List<Param> paramList = webServiceParams.getParams().getParam();
                    String imageProcessingAPI = WebServiceUtil.EMPTY_STRING;
                    String pdfOptimizationParams = WebServiceUtil.EMPTY_STRING;
                    String multipageTifSwitch = WebServiceUtil.EMPTY_STRING;
                    String pdfOptimizationSwitch = WebServiceUtil.EMPTY_STRING,
                            ghostscriptPdfParameters = WebServiceUtil.EMPTY_STRING;
                    for (final Param param : paramList) {
                        if (param.getName().equalsIgnoreCase("imageProcessingAPI")) {
                            imageProcessingAPI = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase("pdfOptimizationParams")) {
                            pdfOptimizationParams = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase("multipageTifSwitch")) {
                            multipageTifSwitch = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase("pdfOptimizationSwitch")) {
                            pdfOptimizationSwitch = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase("ghostscriptPdfParameters")) {
                            ghostscriptPdfParameters = param.getValue();
                            continue;
                        }
                    }
                    String results = WebServiceUtil.validateCreateMultiPageFile(ghostscriptPdfParameters,
                            imageProcessingAPI, pdfOptimizationSwitch, multipageTifSwitch,
                            pdfOptimizationParams);
                    if (!results.isEmpty()) {
                        respStr = results;
                    } else {
                        imService.createMultiPageFilesAPI(ghostscriptPdfParameters, pdfOptimizationParams,
                                multipageTifSwitch, imageProcessingAPI, pdfOptimizationSwitch, workingDir,
                                outputDir, fileList, new File(workingDir).getName() + Math.random());
                        ServletOutputStream out = null;
                        ZipOutputStream zout = null;
                        final String zipFileName = WebServiceUtil.serverOutputFolderName;
                        resp.setContentType("application/x-zip\r\n");
                        resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName
                                + FileType.ZIP.getExtensionWithDot() + "\"\r\n");
                        try {
                            out = resp.getOutputStream();
                            zout = new ZipOutputStream(out);
                            FileUtils.zipDirectory(outputDir, zout, zipFileName);
                            resp.setStatus(HttpServletResponse.SC_OK);
                        } catch (final IOException e) {
                            respStr = "Unable to process web service request.Please try again." + e;
                        } finally {
                            if (zout != null) {
                                zout.close();
                            }
                            if (out != null) {
                                out.flush();
                            }
                            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                        }
                    }
                }
            }
        } catch (final XmlMappingException xmle) {
            respStr = "Error in mapping input XML in the desired format. Please send it in the specified format. Detailed exception is "
                    + xmle;
        } catch (final DCMAException dcmae) {
            respStr = "Error in processing request. Detailed exception is " + dcmae;
        } catch (final Exception e) {
            respStr = "Internal Server error.Please check logs for further details." + e;
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        }
    } else {
        respStr = "Improper input to server. Expected multipart request. Returning without processing the results.";
    }
    if (!workingDir.isEmpty()) {
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {
        }
    }
}