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.portfolio.data.attachment.XSLService.java

void RetrieveAnswer(HttpURLConnection connection, HttpServletResponse response, String referer)
        throws MalformedURLException, IOException {
    /// Receive answer
    InputStream in;/*from  w  w w  .  ja  va  2 s  .co  m*/
    try {
        in = connection.getInputStream();
    } catch (Exception e) {
        System.out.println(e.toString());
        in = connection.getErrorStream();
    }

    String ref = null;
    if (referer != null) {
        int first = referer.indexOf('/', 7);
        int last = referer.lastIndexOf('/');
        ref = referer.substring(first, last);
    }

    response.setContentType(connection.getContentType());
    response.setStatus(connection.getResponseCode());
    response.setContentLength(connection.getContentLength());

    /// Transfer headers
    Map<String, List<String>> headers = connection.getHeaderFields();
    int size = headers.size();
    for (int i = 1; i < size; ++i) {
        String key = connection.getHeaderFieldKey(i);
        String value = connection.getHeaderField(i);
        //         response.setHeader(key, value);
        response.addHeader(key, value);
    }

    /// Deal with correct path with set cookie
    List<String> setValues = headers.get("Set-Cookie");
    if (setValues != null) {
        String setVal = setValues.get(0);
        int pathPlace = setVal.indexOf("Path=");
        if (pathPlace > 0) {
            setVal = setVal.substring(0, pathPlace + 5); // Some assumption, may break
            setVal = setVal + ref;

            response.setHeader("Set-Cookie", setVal);
        }
    }

    /// Write back data
    DataInputStream stream = new DataInputStream(in);
    byte[] buffer = new byte[1024];
    //       int size;
    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        while ((size = stream.read(buffer, 0, buffer.length)) != -1)
            out.write(buffer, 0, size);

    } catch (Exception e) {
        System.out.println(e.toString());
        System.out.println("Writing messed up!");
    } finally {
        in.close();
        out.flush(); // close() should flush already, but Tomcat 5.5 doesn't
        out.close();
    }
}

From source file:org.inbio.ait.web.ajax.controller.TableController.java

/**
 * Return the XML with the results/*from   ww  w.  j a  va2s .  c om*/
 * @param request
 * @param response
 * @param species
 * @param matchesByPolygon
 * @return
 * @throws java.lang.Exception
 */
private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response, Long[][] matrix,
        List<SpeciesNode> species) throws Exception {

    response.setCharacterEncoding("ISO-8859-1");
    response.setContentType("text/xml");
    ServletOutputStream out = response.getOutputStream();

    StringBuilder result = new StringBuilder();
    result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response>");
    result.append("<speciesList>");
    for (SpeciesNode sp : species) {
        result.append("<species>" + sp.getName() + "</species>");
    }
    result.append("</speciesList>");
    if (matrix.length > 0) {
        int rows = matrix.length;
        int columns = matrix[0].length;
        for (int i = 0; i < rows; i++) {
            result.append("<row>");
            for (int j = 0; j < columns; j++) {
                result.append("<column>" + matrix[i][j] + "</column>");
            }
            result.append("</row>");
        }
    }
    result.append("</response>");

    out.println(result.toString());
    out.flush();
    out.close();

    return null;
}

From source file:eu.earthobservatory.org.StrabonEndpoint.DescribeBean.java

/**
 * Processes the request made from the HTML visual interface of Strabon Endpoint.
 * /*from www. j  a  v  a2  s .  c  om*/
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void processVIEWRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // get the dispatcher for forwarding the rendering of the response
    RequestDispatcher dispatcher = request.getRequestDispatcher("describe.jsp");

    String query = URLDecoder.decode(request.getParameter("query"), "UTF-8");
    String format = request.getParameter("format");
    String handle = request.getParameter("handle");
    RDFFormat rdfFormat = RDFFormat.valueOf(format);

    if (format == null || query == null || rdfFormat == null) {
        request.setAttribute(ERROR, PARAM_ERROR);
        dispatcher.forward(request, response);

    } else {
        // set the query, format and handle to be selected in the rendered page
        //request.setAttribute("query", URLDecoder.decode(query, "UTF-8"));
        //request.setAttribute("format", URLDecoder.decode(reqFormat, "UTF-8"));
        //request.setAttribute("handle", URLDecoder.decode(handle, "UTF-8"));

        if ("download".equals(handle)) { // download as attachment
            ServletOutputStream out = response.getOutputStream();

            response.setContentType(rdfFormat.getDefaultMIMEType());
            response.setHeader("Content-Disposition", "attachment; filename=results."
                    + rdfFormat.getDefaultFileExtension() + "; " + rdfFormat.getCharset());

            try {
                strabonWrapper.describe(query, format, out);
                response.setStatus(HttpServletResponse.SC_OK);

            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                out.print(ResponseMessages.getXMLHeader());
                out.print(ResponseMessages.getXMLException(e.getMessage()));
                out.print(ResponseMessages.getXMLFooter());
            }

            out.flush();

        } else //plain
        {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                strabonWrapper.describe(query, format, bos);

                request.setAttribute(RESPONSE, StringEscapeUtils.escapeHtml(bos.toString()));

            } catch (Exception e) {
                request.setAttribute(ERROR, e.getMessage());
            }
            dispatcher.forward(request, response);
        }
    }
}

From source file:org.fao.geonet.api.registries.vocabularies.KeywordsApi.java

/**
 * Gets the thesaurus.//  w w w. j av  a 2 s .c  om
 *
 * @param thesaurus the thesaurus
 * @param request the request
 * @param response the response
 * @return the thesaurus
 * @throws Exception the exception
 */
@ApiOperation(value = "Download a thesaurus by name", nickname = "getThesaurus", notes = "Download the thesaurus in SKOS format.")
@RequestMapping(value = "/{thesaurus:.+}", method = RequestMethod.GET, produces = { MediaType.TEXT_XML_VALUE })
@ApiResponses(value = { @ApiResponse(code = 200, message = "Thesaurus in SKOS format."),
        @ApiResponse(code = 404, message = ApiParams.API_RESPONSE_RESOURCE_NOT_FOUND) })
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public void getThesaurus(
        @ApiParam(value = "Thesaurus to download.", required = true) @PathVariable(value = "thesaurus") String thesaurus,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    ServiceContext context = ApiUtils.createServiceContext(request);
    GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
    ThesaurusManager manager = gc.getBean(ThesaurusManager.class);

    Thesaurus directory = manager.getThesaurusByName(thesaurus);
    if (directory == null)
        throw new IllegalArgumentException("Thesaurus not found --> " + thesaurus);

    Path directoryFile = directory.getFile();
    if (!Files.exists(directoryFile))
        throw new IllegalArgumentException("Thesaurus file not found --> " + thesaurus);

    response.setContentType("text/xml");
    response.setHeader("Content-Disposition", "attachment;filename=" + directoryFile.getFileName());
    ServletOutputStream out = response.getOutputStream();
    BufferedReader reader1 = new BufferedReader(
            new InputStreamReader(new FileInputStream(directoryFile.toFile()), Charset.forName("UTF-8")));
    IOUtils.copy(reader1, out);
    out.flush();
    out.close();
}

From source file:com.fufang.bi.controllers.ChainReportController.java

@ApiOperation(value = "Excel", notes = "Excel")
@ApiResponses(value = { @ApiResponse(code = 200, message = RETURNMESSAGE) })
@RequestMapping(value = "/jxctzh/downExcel", method = RequestMethod.POST) //, method = RequestMethod.POST
public void downExcel(HttpServletRequest request, HttpServletResponse response,
        @ApiParam(required = false, value = excels) @RequestParam String query) {
    String path = request.getSession().getServletContext().getRealPath("/");
    try {/*w w w .  j  ava2s .  c  o m*/
        User user = (User) request.getSession().getAttribute("user");
        String role = "";
        role = (String) request.getSession().getAttribute("mark");
        Integer chaintype = user.getChainType();
        logger.debug("chaintype:" + chaintype);

        String data = request.getParameter("query");
        System.out.println("query:" + data);
        JSONObject object = JSONObject.fromObject(data);
        Map<String, Comparable> querymap = new HashMap<String, Comparable>();
        querymap = (Map) object;
        Integer select = (Integer) querymap.get("select");//??
        String way = "";
        if (null != querymap.get("way")) {
            way = (String) querymap.get("way").toString().trim();
        } else {
            return;
        }
        Integer type = (Integer) querymap.get("type");
        String sourcefilePath = path + "/" + "down/taizhang" + select + ".xls";
        List<?> list = new ArrayList();
        querymap.put("mark", role);
        if (type == 0) {
            querymap.put("amount", "t.notaxAmount");//
        } else {
            querymap.put("amount", "t.amount");
        }
        InputStream inputStream;
        inputStream = new FileInputStream(sourcefilePath);
        String fileName = "tmp.xls";

        Object obj = null;

        if (select == 1) {
            fileName = "?_.xls";
            Integer id = user.getPharmacyId();
            querymap.put("id", id);
            list = chainService.findAllCpharmacyExcel(querymap);
            StorageTotal sumData = new StorageTotal();
            sumData = chainService.findAllCpharmacySum(querymap);
            obj = sumData;
        } else if (select == 2) {
            fileName = "?_?.xls";
            if (way.equals("0")) {//
                Integer id = (Integer) querymap.get("id");
                if (id == null) {
                    logger.error("/jxctzh/downExcel id==null error");
                    return;
                }
                querymap.put("needs", 0);
                querymap.put("parent", 8);
            } else if (way.equals("1")) {//
                Integer id = null;
                if (user != null && (querymap.get("id") == null || "".equals(querymap.get("id")))) {
                    id = user.getPharmacyId();
                    querymap.put("id", id);
                }
                String pharmacyCode = "";
                String name = "";
                String pinyin = "";
                pharmacyCode = (String) querymap.get("pharmacyCode");
                name = (String) querymap.get("name");
                pinyin = (String) querymap.get("pinyin");
                if ((pharmacyCode == null && name == null && pinyin == null)
                        || ("".equals(pharmacyCode) && "".equals(name) && "".equals(pinyin))) {
                    querymap.put("parent", 9);// ?
                    if (0 == chaintype) {
                        querymap.put("needs", 2);
                    } else {
                        querymap.put("needs", 3);
                    }
                } else {
                    querymap.put("needs", 1);//?  ?
                }
            }
            StorageMilde sumData = new StorageMilde();
            list = chainService.findAllCpharmacyMildeExcel(querymap);
            sumData = chainService.findAllCpharmacyMildeSum(querymap);
            obj = sumData;
        } else if (select == 3) {
            fileName = "?_.xls";
            if (way.equals("0")) {
                querymap.put("needs", 0);
                querymap.put("parent", 8);
            } else if (way.equals("1")) {
                Integer id = null;
                if (user != null && (querymap.get("id") == null || "".equals(querymap.get("id")))) {
                    id = user.getPharmacyId();
                    querymap.put("pharmacyid", id);
                }
                String pharmacyCode = "";
                String name = "";
                String pinyin = "";
                pharmacyCode = (String) querymap.get("pharmacyCode");
                name = (String) querymap.get("name");
                pinyin = (String) querymap.get("pinyin");
                if ((pharmacyCode == null && name == null && pinyin == null)
                        || ("".equals(pharmacyCode) && "".equals(name) && "".equals(pinyin))) {
                    querymap.put("parent", 9);// ?
                    if (0 == chaintype) {
                        querymap.put("needs", 2);
                    } else {
                        querymap.put("needs", 3);
                    }
                } else {
                    querymap.put("needs", 1);//?  ?
                }
                querymap.put("pharmacyid", id);
            }
            StorageDetail sumData = new StorageDetail();
            list = chainService.findAllCpharmacyDetailExcel(querymap);
            sumData = chainService.findAllCpharmacyDetailSum(querymap);
            obj = sumData;
        }
        fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
        HSSFWorkbook workbook = createUploadSplitExcel(list, inputStream, select, obj);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        // ?
        ServletOutputStream fOut = response.getOutputStream();
        workbook.write(fOut);
        fOut.flush();
        fOut.close();

    } catch (FileNotFoundException e) {
        logger.error("/jxctzh/downExcel FileNotFoundException error");
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        logger.error("/jxctzh/downExcel UnsupportedEncodingException error");
        e.printStackTrace();
    } catch (IOException e) {
        logger.error("/jxctzh/downExcel IOException error");
        e.printStackTrace();
    }

}

From source file:com.baidu.upload.controller.ImageController.java

@RequestMapping("downloadImg")
public void downloadImg(Integer id, HttpServletRequest request, HttpServletResponse response) {
    Image image = imageService.get(id);
    String imgname = image.getName();
    ServletOutputStream out = null;
    try {/*  w w  w .  j  av  a2s .  c  om*/
        response.reset();
        String userAgent = request.getHeader("User-Agent");
        byte[] bytes = userAgent.contains("MSIE") ? imgname.getBytes() : imgname.getBytes("UTF-8");
        // fileName.getBytes("UTF-8")?safari?
        String fileName = new String(bytes, "ISO-8859-1");
        System.out.println(fileName);
        // ?
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(imgname, "UTF-8"));
        //?blob
        byte[] contents = image.getImgblob();
        out = response.getOutputStream();
        //?
        out.write(contents);
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:guru.nidi.ramlproxy.core.MockServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    final String pathInfo = req.getPathInfo();
    final int pos = pathInfo.lastIndexOf('/');
    final String path = pathInfo.substring(1, pos + 1);
    final String name = pathInfo.substring(pos + 1);
    final ServletOutputStream out = res.getOutputStream();
    final File targetDir = new File(mockDir, path);
    final File file = findFileOrParent(targetDir, name, req.getMethod());
    CommandDecorators.ALLOW_ORIGIN.set(req, res);
    if (file == null) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND,
                "No or multiple file '" + name + "' found in directory '" + targetDir.getAbsolutePath() + "'");
        return;//w  w w .j a  v a2s . c  om
    }
    handleMeta(req, res, file.getParentFile(), file.getName());
    res.setContentLength((int) file.length());
    res.setContentType(mineType(file));
    try (final InputStream in = new FileInputStream(file)) {
        copy(in, out);
    } catch (IOException e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Problem delivering file '" + file.getAbsolutePath() + "': " + e);
    }
    out.flush();
}

From source file:com.ephesoft.gxt.admin.server.ExportDocumentTypeDownloadServlet.java

/**
 * This API is used to process request to export the documents .
 * /*from w  ww .ja v a2 s .c o m*/
 * @param docTypeList {@link List<{@link DocumentType}>} selected document type list to export.
 * @param resp {@link HttpServletResponse}.
 * @return
 */
private void process(final List<DocumentType> docTypeList, final HttpServletResponse resp) throws IOException {

    final BatchSchemaService bSService = this.getSingleBeanOfType(BatchSchemaService.class);
    final String exportSerDirPath = bSService.getBatchExportFolderLocation();
    final BatchClass batchClass = docTypeList.get(0).getBatchClass();

    final String zipFileName = batchClass.getIdentifier() + "_" + "DocumentTypes";
    final String copiedParentFolderPath = exportSerDirPath + File.separator + zipFileName;
    final File copiedFd = createDirectory(copiedParentFolderPath);
    // final boolean isIMFdSelected = checkBaseDirectorySelection("image-classification-sample",
    // bSService.getImagemagickBaseFolderName());
    // final boolean isSSFdSelected = checkBaseDirectorySelection("lucene-search-classification-sample",
    // bSService.getSearchSampleName());
    final boolean isIMFdSelected = true;
    final boolean isSSFdSelected = true;
    processDocumentTypes(docTypeList, batchClass, bSService, isIMFdSelected, isSSFdSelected, resp);
    resp.setContentType("application/x-zip\r\n");
    resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + ZIP_EXT + "\"\r\n");
    ServletOutputStream out = null;
    ZipOutputStream zout = null;
    try {
        out = resp.getOutputStream();
        zout = new ZipOutputStream(out);
        FileUtils.zipDirectory(copiedParentFolderPath, zout, zipFileName);
        resp.setStatus(HttpServletResponse.SC_OK);
    } catch (final IOException e) {
        // Unable to create the temporary export file(s)/folder(s)
        log.error("Error occurred while creating the zip file." + e, e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again.");
    } finally {
        // clean up code
        if (zout != null) {
            zout.close();
        }
        if (out != null) {
            out.flush();
        }
        FileUtils.deleteDirectoryAndContentsRecursive(copiedFd);
    }
}

From source file:org.betaconceptframework.astroboa.console.export.XmlExportBean.java

public void exportTaxonomy(Taxonomy taxonomy) {

    if (taxonomy == null || taxonomy.getName() == null) {
        JSFUtilities.addMessage(null, "taxonomy.export.nullTaxonomy", null, FacesMessage.SEVERITY_WARN);
        return;/*  w  ww.j  av  a2  s .c o  m*/
    }

    try {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        if (!facesContext.getResponseComplete()) {
            HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext()
                    .getResponse();
            response.setContentType("text/xml");
            response.setCharacterEncoding("UTF-8");

            response.setHeader("Content-Disposition", "attachment;filename=" + taxonomy.getName() + ".xml");

            ServletOutputStream servletOutputStream = response.getOutputStream();

            Taxonomy taxonomyToBeExported = astroboaClient.getTaxonomyService().getTaxonomy(taxonomy.getName(),
                    ResourceRepresentationType.TAXONOMY_INSTANCE, FetchLevel.FULL, true);

            //Currently this is not supported at back end. 
            //loadTree(taxonomyToBeExported.getRootTopics());

            //Remove all unnecessary info. mostly identifiers
            removeUnnecessaryInfo(taxonomyToBeExported);

            IOUtils.write(taxonomyToBeExported.xml(true), servletOutputStream);

            servletOutputStream.flush();

            facesContext.responseComplete();
        }
    } catch (Exception e) {
        logger.error("An error occurred while writing xml to servlet output stream", e);
        JSFUtilities.addMessage(null, "object.action.export.message.error", null, FacesMessage.SEVERITY_WARN);
    }
}

From source file:org.activiti.app.service.editor.ActivitiDecisionTableService.java

protected void exportDecisionTable(HttpServletResponse response, AbstractModel decisionTableModel) {
    DecisionTableRepresentation decisionTableRepresentation = getDecisionTableRepresentation(
            decisionTableModel);/*from ww  w  .  j  a v a  2  s  .  c  o m*/

    // TODO Validate

    try {

        JsonNode editorJsonNode = objectMapper.readTree(decisionTableModel.getModelEditorJson());

        // URLEncoder.encode will replace spaces with '+', to keep the actual name replacing '+' to '%20'
        String fileName = URLEncoder.encode(decisionTableRepresentation.getName(), "UTF-8").replaceAll("\\+",
                "%20") + ".dmn";
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);

        ServletOutputStream servletOutputStream = response.getOutputStream();
        response.setContentType("application/xml");

        DmnDefinition dmnDefinition = dmnJsonConverter.convertToDmn(editorJsonNode, decisionTableModel.getId(),
                decisionTableModel.getVersion(), decisionTableModel.getLastUpdated());
        byte[] xmlBytes = dmnXmlConverter.convertToXML(dmnDefinition);

        BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(xmlBytes));

        byte[] buffer = new byte[8096];
        while (true) {
            int count = in.read(buffer);
            if (count == -1)
                break;
            servletOutputStream.write(buffer, 0, count);
        }

        // Flush and close stream
        servletOutputStream.flush();
        servletOutputStream.close();

    } catch (Exception e) {
        logger.error("Could not export decision table model", e);
        throw new InternalServerErrorException("Could not export decision table model");
    }
}