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:org.geowebcache.service.wms.WMSService.java

/**
 * Handles a getfeatureinfo request/*  w ww .  ja v  a2s .  co  m*/
 * 
 * @param conv
 */
private void handleGetFeatureInfo(ConveyorTile tile) throws GeoWebCacheException {
    TileLayer tl = tld.getTileLayer(tile.getLayerId());

    if (tl == null) {
        throw new GeoWebCacheException(tile.getLayerId() + " is unknown.");
    }

    String[] keys = { "x", "y", "srs", "info_format", "bbox", "height", "width" };
    Map<String, String> values = ServletUtils.selectedStringsFromMap(tile.servletReq.getParameterMap(),
            tile.servletReq.getCharacterEncoding(), keys);

    // TODO Arent we missing some format stuff here?
    GridSubset gridSubset = tl.getGridSubsetForSRS(SRS.getSRS(values.get("srs")));

    BoundingBox bbox = null;
    try {
        bbox = new BoundingBox(values.get("bbox"));
    } catch (NumberFormatException nfe) {
        log.debug(nfe.getMessage());
    }

    if (bbox == null || !bbox.isSane()) {
        throw new ServiceException(
                "The bounding box parameter (" + values.get("srs") + ") is missing or not sane");
    }

    // long[] tileIndex = gridSubset.closestIndex(bbox);

    MimeType mimeType;
    try {
        mimeType = MimeType.createFromFormat(values.get("info_format"));
    } catch (MimeException me) {
        throw new GeoWebCacheException(
                "The info_format parameter (" + values.get("info_format") + ")is missing or not recognized.");
    }

    if (mimeType != null && !tl.getInfoMimeTypes().contains(mimeType)) {
        throw new GeoWebCacheException(
                "The info_format parameter (" + values.get("info_format") + ") is not supported.");
    }

    ConveyorTile gfiConv = new ConveyorTile(sb, tl.getName(), gridSubset.getName(), null, mimeType,
            tile.getFullParameters(), tile.servletReq, tile.servletResp);
    gfiConv.setTileLayer(tl);

    int x, y;
    try {
        x = Integer.parseInt(values.get("x"));
        y = Integer.parseInt(values.get("y"));
    } catch (NumberFormatException nfe) {
        throw new GeoWebCacheException("The parameters for x and y must both be positive integers.");
    }

    int height, width;
    try {
        height = Integer.parseInt(values.get("height"));
        width = Integer.parseInt(values.get("width"));
    } catch (NumberFormatException nfe) {
        throw new GeoWebCacheException("The parameters for height and width must both be positive integers.");
    }

    Resource data = tl.getFeatureInfo(gfiConv, bbox, height, width, x, y);

    try {
        tile.servletResp.setContentType(mimeType.getMimeType());
        ServletOutputStream outputStream = tile.servletResp.getOutputStream();
        data.transferTo(Channels.newChannel(outputStream));
        outputStream.flush();
    } catch (IOException ioe) {
        tile.servletResp.setStatus(500);
        log.error(ioe.getMessage());
    }

}

From source file:com.jd.survey.web.reports.ReportController.java

/**
 * Exports survey data to a comma delimited values file
 * @param surveyDefinitionId//ww w .j a va2s.co  m
 * @param principal
 * @param response
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "csv", produces = "text/html")
public void surveyCSVExport(@PathVariable("id") Long surveyDefinitionId, Principal principal,
        HttpServletRequest httpServletRequest, HttpServletResponse response) {
    try {

        User user = userService.user_findByLogin(principal.getName());
        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            response.sendRedirect("../accessDenied");
            //throw new AccessDeniedException("Unauthorized access attempt");
        }

        String columnName;
        SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId);
        List<Map<String, Object>> surveys = reportDAO.getSurveyData(surveyDefinitionId);

        StringBuilder stringBuilder = new StringBuilder();

        stringBuilder.append(
                "\"id\",\"Survey Name\",\"User Login\",\"Submission Date\",\"Creation Date\",\"Last Update Date\",");
        for (SurveyDefinitionPage page : surveyDefinition.getPages()) {
            for (Question question : page.getQuestions()) {
                if (question.getType().getIsMatrix()) {
                    for (QuestionRowLabel questionRowLabel : question.getRowLabels()) {
                        for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) {
                            stringBuilder.append("\" p" + page.getOrder() + "q" + question.getOrder() + "r"
                                    + questionRowLabel.getOrder() + "c" + questionColumnLabel.getOrder()
                                    + "\",");
                        }
                    }
                    continue;
                }

                if (question.getType().getIsMultipleValue()) {
                    for (QuestionOption questionOption : question.getOptions()) {
                        stringBuilder.append("\" p" + page.getOrder() + "q" + question.getOrder() + "o"
                                + questionOption.getOrder() + "\",");

                    }
                    continue;
                }
                stringBuilder.append("\"p" + page.getOrder() + "q" + question.getOrder() + "\",");
            }
        }

        stringBuilder.deleteCharAt(stringBuilder.length() - 1); //delete the last comma
        stringBuilder.append("\n");

        for (Map<String, Object> record : surveys) {
            stringBuilder.append(record.get("survey_id") == null ? ""
                    : "\"" + record.get("survey_id").toString().replace("\"", "\"\"") + "\",");
            stringBuilder.append(record.get("type_name") == null ? ""
                    : "\"" + record.get("type_name").toString().replace("\"", "\"\"") + "\",");
            stringBuilder.append(record.get("login") == null ? ""
                    : "\"" + record.get("login").toString().replace("\"", "\"\"") + "\",");
            stringBuilder.append(record.get("submission_date") == null ? ""
                    : "\"" + record.get("creation_date").toString().replace("\"", "\"\"") + "\",");
            stringBuilder.append(record.get("creation_date") == null ? ""
                    : "\"" + record.get("last_update_date").toString().replace("\"", "\"\"") + "\",");
            stringBuilder.append(record.get("last_update_date") == null ? ""
                    : "\"" + record.get("last_update_date").toString().replace("\"", "\"\"") + "\",");

            for (SurveyDefinitionPage page : surveyDefinition.getPages()) {
                for (Question question : page.getQuestions()) {
                    if (question.getType().getIsMatrix()) {
                        for (QuestionRowLabel questionRowLabel : question.getRowLabels()) {
                            for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) {
                                columnName = "p" + page.getOrder() + "q" + question.getOrder() + "r"
                                        + questionRowLabel.getOrder() + "c" + questionColumnLabel.getOrder();
                                stringBuilder.append(record.get(columnName) == null ? ","
                                        : "\"" + record.get(columnName).toString().replace("\"", "\"\"")
                                                + "\",");
                            }
                        }
                        continue;
                    }
                    if (question.getType().getIsMultipleValue()) {
                        for (QuestionOption questionOption : question.getOptions()) {
                            columnName = "p" + page.getOrder() + "q" + question.getOrder() + "o"
                                    + questionOption.getOrder();
                            stringBuilder.append(record.get(columnName) == null ? ","
                                    : "\"" + record.get(columnName).toString().replace("\"", "\"\"") + "\",");
                        }
                        continue;
                    }
                    columnName = "p" + page.getOrder() + "q" + question.getOrder();
                    stringBuilder.append(record.get(columnName) == null ? ","
                            : "\"" + record.get(columnName).toString().replace("\"", "\"\"") + "\",");

                }
            }
            stringBuilder.deleteCharAt(stringBuilder.length() - 1); //delete the last comma
            stringBuilder.append("\n");
        }

        //Zip file manipulations Code
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ZipEntry zipentry;
        ZipOutputStream zipfile = new ZipOutputStream(bos);
        zipentry = new ZipEntry("survey" + surveyDefinition.getId() + ".csv");
        zipfile.putNextEntry(zipentry);
        zipfile.write(stringBuilder.toString().getBytes("UTF-8"));
        zipfile.close();

        //response.setContentType("text/html; charset=utf-8");
        response.setContentType("application/octet-stream");
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Content-Disposition", "inline;filename=survey" + surveyDefinition.getId() + ".zip");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        //servletOutputStream.write(stringBuilder.toString().getBytes("UTF-8"));
        servletOutputStream.write(bos.toByteArray());
        servletOutputStream.flush();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.struts2.views.jasperreports.JasperReportsResult.java

/**
 * Writes report bytes to response output stream.
 *
 * @param response Current response./*w  w w .j av a 2 s. c o  m*/
 * @param output   Report bytes to write.
 * @throws ServletException on stream IOException.
 */
private void writeReport(HttpServletResponse response, byte[] output) throws ServletException {
    ServletOutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
        outputStream.write(output);
        outputStream.flush();
    } catch (IOException e) {
        LOG.error("Error writing report output", e);
        throw new ServletException(e.getMessage(), e);
    } finally {
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            LOG.error("Error closing report output stream", e);
            throw new ServletException(e.getMessage(), e);
        }
    }
}

From source file:org.extensiblecatalog.ncip.v2.responder.implprof1.NCIPServlet.java

/**
 * Create a valid version 2 NCIPMessage response indicating a "Temporary Processing Failure", without
 * relying on any facilities of the Toolkit. This method is to be used when handling exceptions that
 * indicate that Toolkit services such as
 * {@link ServiceHelper#generateProblems(org.extensiblecatalog.ncip.v2.service.ProblemType, String, String, String)} ()}
 * may fail./*  ww  w .j  a v a2 s.  c  o  m*/
 * @param response the HttpServletResponse object to use
 * @param detail the text message to include in the ProblemDetail element
 * @throws ServletException if there is an IOException writing to the response object's output stream
 */
protected void returnProblem(HttpServletResponse response, String detail) throws ServletException {
    String problemMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            // TODO: The version, namespace, etc. ought to come from ServiceContext
            + "<ns1:NCIPMessage ns1:version=\"http://www.niso.org/ncip/v2_0/imp1/xsd/ncip_v2_0.xsd\""
            + " xmlns:ns1=\"http://www.niso.org/2008/ncip\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
            + " xsi:schemaLocation=\"http://www.niso.org/2008/ncip ncip_v2_0.xsd\">\n" + "  <ns1:Problem>\n"
            + "    <ns1:ProblemType ns1:Scheme=\"http://www.niso.org/ncip/v1_0/schemes/processingerrortype/generalprocessingerror.scm\">Temporary Processing Failure</ns1:ProblemType>\n"
            + "    <ns1:ProblemDetail>" + StringEscapeUtils.escapeXml(detail) + "</ns1:ProblemDetail>\n"
            + "  </ns1:Problem>\n" + "</ns1:NCIPMessage>";

    byte[] problemMsgBytes = problemMsg.getBytes();

    response.setContentLength(problemMsgBytes.length);

    try {

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(problemMsgBytes);
        outputStream.flush();

    } catch (IOException e) {

        throw new ServletException("Exception writing Problem response.", e);

    }

}

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

/**
 * Write the XML to be parsed on the analysis view
 * Case 0: If there is just one criteria category or especifically these categories
 * (geographical-taxonomical or or taxonomical-indicator). It means type 0 on xml
 * @param request/*from  w  w  w.  j  ava 2s  .  c om*/
 * @param response
 * @param totalMatch
 * @param matchesByPolygon
 * @return
 * @throws java.lang.Exception
 */
private ModelAndView writeReponse0(HttpServletRequest request, HttpServletResponse response, Long totalMatch,
        Long totalPercentage) 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("<type>0</type>");
    result.append("<total>" + totalMatch + "</total>");
    result.append("<totalp>" + totalPercentage + "</totalp></response>");

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

    return null;
}

From source file:org.apache.stratos.theme.mgt.ui.servlets.ThemeResourceServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from   w  ww.j av  a 2  s . c  o  m
        ThemeMgtServiceClient client = new ThemeMgtServiceClient(servletConfig, request.getSession());
        String path = request.getParameter("path");
        String viewImage = request.getParameter("viewImage");
        if (path == null) {
            String msg = "Could not get the resource content. Path is not specified.";
            log.error(msg);
            response.setStatus(400);
            return;
        }

        ContentDownloadBean bean = client.getContentDownloadBean(path);

        InputStream contentStream = null;
        if (bean.getContent() != null) {
            contentStream = bean.getContent().getInputStream();
        } else {
            String msg = "The resource content was empty.";
            log.error(msg);
            response.setStatus(204);
            return;
        }

        response.setDateHeader("Last-Modified", bean.getLastUpdatedTime().getTime().getTime());
        String ext = "jpg";
        if (path.lastIndexOf(".") < path.length() - 1 && path.lastIndexOf(".") > 0) {
            ext = path.substring(path.lastIndexOf(".") + 1);
        }

        if (viewImage != null && viewImage.equals("1")) {
            response.setContentType("img/" + ext);
        } else {
            if (bean.getMediatype() != null && bean.getMediatype().length() > 0) {
                response.setContentType(bean.getMediatype());
            } else {
                response.setContentType("application/download");
            }

            if (bean.getResourceName() != null) {
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"" + bean.getResourceName() + "\"");
            }
        }

        if (contentStream != null) {

            ServletOutputStream servletOutputStream = null;
            try {
                servletOutputStream = response.getOutputStream();

                byte[] contentChunk = new byte[1024];
                int byteCount;
                while ((byteCount = contentStream.read(contentChunk)) != -1) {
                    servletOutputStream.write(contentChunk, 0, byteCount);
                }

                response.flushBuffer();
                servletOutputStream.flush();

            } finally {
                contentStream.close();

                if (servletOutputStream != null) {
                    servletOutputStream.close();
                }
            }
        }
    } catch (Exception e) {

        String msg = "Failed to get resource content. " + e.getMessage();
        log.error(msg, e);
        response.setStatus(500);
    }
}

From source file:org.apache.jena.fuseki.ctl.ActionStats.java

private void statsTxt(HttpServletResponse resp, DataAccessPointRegistry registry) throws IOException {
    ServletOutputStream out = resp.getOutputStream();
    resp.setContentType(contentTypeTextPlain);
    resp.setCharacterEncoding(charsetUTF8);

    Iterator<String> iter = registry.keys().iterator();
    while (iter.hasNext()) {
        String ds = iter.next();/*from   w  w w .ja v  a 2s.co  m*/
        DataAccessPoint desc = registry.get(ds);
        statsTxt(out, desc);
        if (iter.hasNext())
            out.println();
    }
    out.flush();
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.candidacy.CandidacyProcessDA.java

public ActionForward prepareExecuteExportCandidacies(ActionMapping mapping, ActionForm actionForm,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment; filename=" + getReportFilename());

    final ServletOutputStream writer = response.getOutputStream();
    writeCandidaciesReport(request, getProcess(request), writer);
    writer.flush();
    response.flushBuffer();//from ww  w . j  ava 2 s . co m
    return null;
}

From source file:cn.newgxu.lab.core.config.MappingJacksonJsonpView.java

@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    if (request.getMethod().toUpperCase().equals("GET")) {
        if (request.getParameterMap().containsKey("callback")) {
            ServletOutputStream ostream = response.getOutputStream();
            //            try
            ostream.write(new String("try{" + request.getParameter("callback") + "(").getBytes());
            super.render(model, request, response);
            ostream.write(new String(");}catch(e){}").getBytes());
            //            ????closeflushspring?
            //            ?
            ostream.flush();
            ostream.close();//ww  w .jav  a2s.  co m
        } else {
            super.render(model, request, response);
        }
    } else {
        super.render(model, request, response);
    }
}

From source file:eu.fusepool.p3.webid.proxy.ProxyServlet.java

/**
 * The service method from HttpServlet, performs handling of all
 * HTTP-requests independent of their method. Requests and responses within
 * the method can be distinguished by belonging to the "frontend" (i.e. the
 * client connecting to the proxy) or the "backend" (the server being
 * contacted on behalf of the client)//w w w .j ava2  s  . c  o  m
 *
 * @param frontendRequest Request coming in from the client
 * @param frontendResponse Response being returned to the client
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void service(final HttpServletRequest frontendRequest, final HttpServletResponse frontendResponse)
        throws ServletException, IOException {
    log(LogService.LOG_INFO,
            "Proxying request: " + frontendRequest.getRemoteAddr() + ":" + frontendRequest.getRemotePort()
                    + " (" + frontendRequest.getHeader("Host") + ") " + frontendRequest.getMethod() + " "
                    + frontendRequest.getRequestURI());

    if (targetBaseUri == null) {
        // FIXME return status page
        return;
    }

    //////////////////// Setup backend request
    final HttpEntityEnclosingRequestBase backendRequest = new HttpEntityEnclosingRequestBase() {
        @Override
        public String getMethod() {
            return frontendRequest.getMethod();
        }
    };
    try {
        backendRequest.setURI(new URL(targetBaseUri + frontendRequest.getRequestURI()).toURI());
    } catch (URISyntaxException ex) {
        throw new IOException(ex);
    }

    //////////////////// Copy headers to backend request
    final Enumeration<String> frontendHeaderNames = frontendRequest.getHeaderNames();
    while (frontendHeaderNames.hasMoreElements()) {
        final String headerName = frontendHeaderNames.nextElement();
        final Enumeration<String> headerValues = frontendRequest.getHeaders(headerName);
        while (headerValues.hasMoreElements()) {
            final String headerValue = headerValues.nextElement();
            if (!headerName.equalsIgnoreCase("Content-Length")) {
                backendRequest.setHeader(headerName, headerValue);
            }
        }
    }

    //////////////////// Copy Entity - if any
    final byte[] inEntityBytes = IOUtils.toByteArray(frontendRequest.getInputStream());
    if (inEntityBytes.length > 0) {
        backendRequest.setEntity(new ByteArrayEntity(inEntityBytes));
    }

    //////////////////// Execute request to backend
    try (CloseableHttpResponse backendResponse = httpclient.execute(backendRequest)) {
        frontendResponse.setStatus(backendResponse.getStatusLine().getStatusCode());

        // Copy back headers
        final Header[] backendHeaders = backendResponse.getAllHeaders();
        final Set<String> backendHeaderNames = new HashSet<>(backendHeaders.length);
        for (Header header : backendHeaders) {
            if (backendHeaderNames.add(header.getName())) {
                frontendResponse.setHeader(header.getName(), header.getValue());
            } else {
                frontendResponse.addHeader(header.getName(), header.getValue());
            }
        }

        final ServletOutputStream outStream = frontendResponse.getOutputStream();

        // Copy back entity
        final HttpEntity entity = backendResponse.getEntity();
        if (entity != null) {
            try (InputStream inStream = entity.getContent()) {
                IOUtils.copy(inStream, outStream);
            }
        }
        outStream.flush();
    }
}