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.geoserver.wfs.json.JSONType.java

/**
 * Handle Exception in JSON and JSONP format
 * //w  w  w.j ava  2 s  . c  om
 * @param LOGGER the logger to use (can be null)
 * @param exception the exception to write to the response outputStream
 * @param request the request generated the exception
 * @param charset the desired charset
 * @param verbose be verbose
 * @param isJsonp switch writing json (false) or jsonp (true)
 */
public static void handleJsonException(Logger LOGGER, ServiceException exception, Request request,
        String charset, boolean verbose, boolean isJsonp) {

    final HttpServletResponse response = request.getHttpResponse();
    // TODO: server encoding options?
    response.setCharacterEncoding(charset);

    ServletOutputStream os = null;
    try {
        os = response.getOutputStream();
        if (isJsonp) {
            // jsonp
            response.setContentType(JSONType.jsonp);
            JSONType.writeJsonpException(exception, request, os, charset, verbose);
        } else {
            // json
            OutputStreamWriter outWriter = null;
            try {
                outWriter = new OutputStreamWriter(os, charset);
                response.setContentType(JSONType.json);
                JSONType.writeJsonException(exception, request, outWriter, verbose);
            } finally {
                if (outWriter != null) {
                    try {
                        outWriter.flush();
                    } catch (IOException ioe) {
                    }
                    IOUtils.closeQuietly(outWriter);
                }
            }

        }
    } catch (Exception e) {
        if (LOGGER != null && LOGGER.isLoggable(Level.SEVERE))
            LOGGER.severe(e.getLocalizedMessage());
    } finally {
        if (os != null) {
            try {
                os.flush();
            } catch (IOException ioe) {
            }
            IOUtils.closeQuietly(os);
        }
    }
}

From source file:de.iteratec.iteraplan.presentation.dialog.ExcelImport.ExportFrontendServiceImpl.java

/**
 * Download model as xmi file//from w  w w  . ja va2 s .co  m
 * @param context
 * @return true, if download succeeds
 */
public boolean downloadBundle(RequestContext context) {
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getNativeResponse();
    setContentTypeAndHeader(response, MIME_TYPE_ZIP, ZIP_FILENAME);
    try {
        ServletOutputStream out = response.getOutputStream();
        emfExportService.serializeBundle(out);
        out.flush();
        markFinished(context);
    } catch (IOException e) {
        LOGGER.error(e);
        return false;
    }
    return true;
}

From source file:gov.utah.dts.det.ccl.actions.reports.ReportsPrintAction.java

private void sendToResponse(ByteArrayOutputStream ba, String filename) throws IOException {
    if (ba != null && ba.size() > 0) {
        response.setContentLength(ba.size());
        response.setContentType("application/pdf");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        if (StringUtils.isNotBlank(filename)) {
            response.setHeader("Content-disposition", "attachment; filename=\"" + filename + "\"");
        } else {/*from  w ww .j a  va 2  s  .  c o  m*/
            response.setHeader("Content-disposition", "attachment");
        }

        ServletOutputStream out = response.getOutputStream();
        ba.writeTo(out);
        out.flush();
    }
}

From source file:org.jtalks.jcommune.plugin.kaptcha.KaptchaPluginService.java

/**
 * Refresh captcha image on registration form.
 *
 * @param request http request//from  w w w .j av a  2s.c o  m
 * @param response http response
 * @throws IOException
 */
public void refreshCaptchaImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ServletOutputStream out = response.getOutputStream();
    response.setContentType("image/jpeg");
    String capText = getCaptchaProducer().createText();
    request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
    BufferedImage bi = getCaptchaProducer().createImage(capText);
    ImageIO.write(bi, "jpg", out);
    out.flush();
}

From source file:com.hp.security.jauth.admin.controller.BaseController.java

@RequestMapping("getResource")
public void getResource(String path, HttpServletRequest request, HttpServletResponse response)
        throws IOException, TemplateException {
    if (null != path) {
        if (path.endsWith(".js")) {
            response.setContentType("text/js");
        } else if (path.endsWith(".css")) {
            response.setContentType("text/css");
        } else if (path.endsWith(".gif")) {
            response.setContentType("image/gif");
        } else if (path.endsWith(".jpg") || path.endsWith(".jpeg")) {
            response.setContentType("image/jpeg");
        } else if (path.endsWith(".png")) {
            response.setContentType("image/png");
        } else {// w w w .jav  a  2s .  c  o  m
            response.setContentType("text/html");
        }
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource resource = resolver.getResource("jauth/resources/" + path);
        ServletOutputStream out = response.getOutputStream();
        InputStream is = resource.getInputStream();
        int read = 0;
        byte[] buffer = new byte[8192];
        while ((read = is.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        out.flush();
        out.close();
    }
}

From source file:ch.ralscha.extdirectspring.controller.ApiController.java

/**
 * Method that handles api.js and api-debug.js calls. Generates a javascript with the
 * necessary code for Ext Direct./*w w  w.  j a  v  a2s. c om*/
 *
 * @param apiNs name of the namespace the variable remotingApiVar will live in.
 * Defaults to Ext.app
 * @param actionNs name of the namespace the action will live in.
 * @param remotingApiVar name of the remoting api variable. Defaults to REMOTING_API
 * @param pollingUrlsVar name of the polling urls object. Defaults to POLLING_URLS
 * @param group name of the api group. Multiple groups delimited with comma
 * @param fullRouterUrl if true the router property contains the full request URL with
 * method, server and port. Defaults to false returns only the URL without method,
 * server and port
 * @param format only valid value is "json2. Ext Designer sends this parameter and the
 * response is a JSON. Defaults to null and response is Javascript.
 * @param baseRouterUrl Sets the path to the router and poll controllers. If set
 * overrides default behavior that uses request.getRequestURI
 * @param request the HTTP servlet request
 * @param response the HTTP servlet response
 * @throws IOException
 */
@SuppressWarnings({ "resource" })
@RequestMapping(value = { "/api.js", "/api-debug.js", "/api-debug-doc.js" }, method = RequestMethod.GET)
public void api(@RequestParam(value = "apiNs", required = false) String apiNs,
        @RequestParam(value = "actionNs", required = false) String actionNs,
        @RequestParam(value = "remotingApiVar", required = false) String remotingApiVar,
        @RequestParam(value = "pollingUrlsVar", required = false) String pollingUrlsVar,
        @RequestParam(value = "group", required = false) String group,
        @RequestParam(value = "fullRouterUrl", required = false) Boolean fullRouterUrl,
        @RequestParam(value = "format", required = false) String format,
        @RequestParam(value = "baseRouterUrl", required = false) String baseRouterUrl,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    if (format == null) {
        response.setContentType(this.configurationService.getConfiguration().getJsContentType());
        response.setCharacterEncoding(ExtDirectSpringUtil.UTF8_CHARSET.name());

        String apiString = buildAndCacheApiString(apiNs, actionNs, remotingApiVar, pollingUrlsVar, group,
                fullRouterUrl, baseRouterUrl, request);

        byte[] outputBytes = apiString.getBytes(ExtDirectSpringUtil.UTF8_CHARSET);
        response.setContentLength(outputBytes.length);

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(outputBytes);
        outputStream.flush();
    } else {
        response.setContentType(RouterController.APPLICATION_JSON.toString());
        response.setCharacterEncoding(RouterController.APPLICATION_JSON.getCharset().name());

        String requestUrlString = request.getRequestURL().toString();

        boolean debug = requestUrlString.contains("api-debug.js");
        String routerUrl = requestUrlString.replaceFirst("api[^/]*?\\.js", "router");

        String apiString = buildApiJson(apiNs, actionNs, remotingApiVar, routerUrl, group, debug);
        byte[] outputBytes = apiString.getBytes(ExtDirectSpringUtil.UTF8_CHARSET);
        response.setContentLength(outputBytes.length);

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(outputBytes);
        outputStream.flush();
    }
}

From source file:nz.net.orcon.kanban.controllers.XmlFileController.java

private void generateXml(HttpServletResponse response, String boardId, Collection<Card> cardList)
        throws Exception {
    String xmlFileName = boardId + "-" + Calendar.getInstance().getTime() + ".xml";
    HashMap<String, String> aliases = new HashMap<String, String>();
    aliases.put("Card", "nz.net.orcon.kanban.model.Card");
    xstreamMarshaller.setAliases(aliases);
    XStream xStream = xstreamMarshaller.getXStream();
    xStream.registerConverter(new CardConverter());

    StringBuffer xmlCards = new StringBuffer();
    xmlCards.append("<Cards> \n");
    for (Card card : cardList) {
        xmlCards.append(xStream.toXML(card));
        xmlCards.append("\n");
    }//w  w w .  ja  v a  2 s .c  om
    xmlCards.append("</Cards>");

    InputStream in = new ByteArrayInputStream(xmlCards.toString().getBytes("UTF-8"));
    ServletOutputStream out = response.getOutputStream();
    response.setContentLength(xmlCards.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + xmlFileName + "\"");

    byte[] outputByte = new byte[4096];
    //copy binary content to output stream
    while (in.read(outputByte, 0, 4096) != -1) {
        out.write(outputByte, 0, 4096);
    }
    in.close();
    out.flush();
    out.close();
}

From source file:com.rplt.studioMusik.controller.MemberController.java

@RequestMapping(value = "/cetakNota", method = RequestMethod.GET)
public String cetakNota(HttpServletResponse response) {
    //        Connection conn = DatabaseConnection.getmConnection();
    //            File reportFile = new File(application.getRealPath("Coba.jasper"));//your report_name.jasper file
    File reportFile = new File(
            servletConfig.getServletContext().getRealPath("/resources/report/nota_persewaan.jasper"));

    //        Map<String, Object> params = new HashMap<String, Object>();
    //        params.put("P_KODESEWA", request.getParameter("kodeSewa"));

    byte[] bytes = persewaanStudioMusik.cetakNota(request.getParameter("kodeSewa"), reportFile);
    //        //from  w w  w.  jav  a 2  s  .c  o m
    //        try {
    //            bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), params, conn);
    //        } catch (JRException ex) {
    //            Logger.getLogger(MemberController.class.getName()).log(Level.SEVERE, null, ex);
    //        }

    response.setContentType("application/pdf");
    response.setContentLength(bytes.length);

    try {
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(bytes, 0, bytes.length);
        outStream.flush();
        outStream.close();
    } catch (IOException ex) {
        Logger.getLogger(MemberController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "halaman-cetakNota-operator";
}

From source file:com.jaspersoft.jasperserver.war.action.AbstractReportExporter.java

protected void exportBuffered(RequestContext context, HttpServletResponse response, JasperPrint jasperPrint,
        String reportUnitURI) throws IOException, JRException {
    Map parameters = new HashMap();
    parameters.put(JRExporterParameter.JASPER_PRINT, jasperPrint);

    FileBufferedOutputStream bufferedOutput = new FileBufferedOutputStream(getMemoryThreshold(),
            getInitialMemoryBufferSize());
    parameters.put(JRExporterParameter.OUTPUT_STREAM, bufferedOutput);

    try {/*from w ww.j  a  v  a2s . c  o m*/
        export(context, getExecutionContext(context), reportUnitURI, parameters);
        bufferedOutput.close();

        int exportSize = bufferedOutput.size();
        if (log.isDebugEnabled()) {
            log.debug("exported to buffer of size " + exportSize);
        }

        response.setContentType(getContentType(context));
        setAdditionalResponseHeaders(context, response);
        response.setContentLength(exportSize);
        ServletOutputStream ouputStream = response.getOutputStream();

        try {
            bufferedOutput.writeData(ouputStream);
            bufferedOutput.dispose();

            ouputStream.flush();
        } finally {
            if (ouputStream != null) {
                try {
                    ouputStream.close();
                } catch (IOException ex) {
                    log.warn("Error closing output stream", ex);
                }
            }
        }
    } finally {
        bufferedOutput.close();
        bufferedOutput.dispose();
    }
}