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:fast.servicescreen.server.RequestServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //get the URL out of the requests parameter and form escape codes back to a real URL
    String url = req.getParameter("url");

    if (url != null && !"".equals(url)) {
        //execute a GET call with the params URL
        String value = sendHttpRequest_GET(url);

        // to facilitate debugging strip xslt tag
        // value = value.replaceFirst("<\\?xml-stylesheet type=\"text/xsl\" href=\"http://ergast.com/schemas/mrd-1.1.xsl\"\\?>", "");

        //attach the responses output stream
        ServletOutputStream out = resp.getOutputStream();

        //write the GET result into the response (this will trigger
        //the forward to the original transmitter)
        byte[] outByte = value.getBytes("utf-8");
        out.write(outByte);//from   w w  w  . ja va  2  s  .c  o  m
        out.flush();
        out.close();
    }
}

From source file:info.magnolia.cms.servlets.ResourceDispatcher.java

/**
 * Send data as is.//from   w w  w.  j  ava 2  s .co  m
 *
 * @param is  Input stream for the resource
 * @param res HttpServletResponse as received by the service method
 * @throws IOException standard servlet exception
 */
private void sendUnCompressed(InputStream is, HttpServletResponse res) throws IOException {
    ServletOutputStream os = res.getOutputStream();
    byte[] buffer = new byte[8192];
    int read = 0;
    while ((read = is.read(buffer)) > 0) {
        os.write(buffer, 0, read);
    }
    os.flush();
    IOUtils.closeQuietly(os);
}

From source file:com.ibm.watson.ta.retail.DemoServlet.java

/**
 * Create and POST a request to the Watson service
 *
 * @param req/*  ww w. java 2s  .co m*/
 *            the Http Servlet request
 * @param resp
 *            the Http Servlet response
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    req.setCharacterEncoding("UTF-8");
    try {
        String queryStr = req.getQueryString();
        String url = baseURL + "/v1/dilemmas";
        if (queryStr != null) {
            url += "?" + queryStr;
        }
        URI uri = new URI(url).normalize();
        logger.info("posting to " + url);

        Request newReq = Request.Post(uri);
        newReq.addHeader("Accept", "application/json");
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream());
        newReq.bodyString(EntityUtils.toString(entity, "UTF-8"), ContentType.APPLICATION_JSON);

        Executor executor = this.buildExecutor(uri);
        Response response = executor.execute(newReq);
        HttpResponse httpResponse = response.returnResponse();
        resp.setStatus(httpResponse.getStatusLine().getStatusCode());

        ServletOutputStream servletOutputStream = resp.getOutputStream();
        httpResponse.getEntity().writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();

        logger.info("post done");
    } catch (Exception e) {
        // Log something and return an error message
        logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
        resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
    }
}

From source file:com.cisco.ca.cstg.pdi.utils.Util.java

/**
 * This method is used to download files from specified path
 * @param response// w  w w .  j ava2  s.c  om
 * @param archiveFile
 */
public static void downloadArchiveFile(HttpServletResponse response, File archiveFile) {
    if (archiveFile.isFile()) {
        response.reset();
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + archiveFile.getName() + "\"");
        FileInputStream is = null;
        ServletOutputStream op = null;
        try {
            op = response.getOutputStream();
            double dLength = archiveFile.length();
            int iLength = 0;
            int num_read = 0;

            if (dLength >= Integer.MIN_VALUE && dLength <= Integer.MAX_VALUE) {
                iLength = (int) dLength;
            }
            byte[] arBytes = new byte[iLength];
            is = new FileInputStream(archiveFile);

            while (num_read < iLength) {
                int count = is.read(arBytes, num_read, iLength - num_read);
                if (count < 0) {
                    throw new IOException("end of stream reached");
                }
                num_read += count;
            }
            op.write(arBytes);
            op.flush();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
            if (null != op) {
                try {
                    op.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
    }
}

From source file:com.ace.erp.filter.jcaptcha.JCaptchaFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    response.setDateHeader("Expires", 0L);
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("image/jpeg");

    ServletOutputStream out = response.getOutputStream();

    try {//from   w  w  w  . j a va 2s  .  c om
        String id = request.getSession(true).getId();
        //String id = request.getRequestedSessionId();
        BufferedImage bi = JCaptcha.captchaService.getImageChallengeForID(id);

        ImageIO.write(bi, "jpg", out);
        out.flush();
    } finally {
        out.close();
    }
}

From source file:com.hzc.framework.ssh.controller.WebUtil.java

public static void callCtl(String class_method) throws RuntimeException {
    try {//www.  ja  v  a2s .  c  o  m
        HttpServletRequest req = ActionContext.getReq();
        HttpServletResponse resp = ActionContext.getResp();
        if (StringUtils.isNotBlank(class_method)) {
            Cache cache = SshConstant.CACHE_MAP.get(class_method);
            if (null != cache && !SshConstant.DEBUG_MODE) {
                // long begin = System.currentTimeMillis();
                cache.getMethod().invoke(cache.getObject(), req, resp);
                // long end = System.currentTimeMillis();
                // //System.out.println("" + (end - begin));
            } else {
                // long begin = System.currentTimeMillis();
                int lastIndex = class_method.lastIndexOf(".");
                String clazzTemp = class_method.substring(0, lastIndex);
                // 
                Class<?> ctlClazz = null;
                for (String packageName : SshConstant.PACKAGE_NAME) {
                    try {
                        String clazz = (clazzTemp.indexOf(".") == clazzTemp.lastIndexOf("."))
                                ? (packageName + "." + clazzTemp)
                                : clazzTemp;
                        ctlClazz = Class.forName(clazz);
                    } catch (Exception e) {
                    }
                    if (ctlClazz != null)
                        break;
                }
                Object ctlObj = ctlClazz.newInstance();
                String method = class_method.substring(++lastIndex);
                // Method ctlMet = ctlClazz.getMethod(method,
                // HttpServletRequest.class, HttpServletResponse.class);
                Method ctlMet = ctlClazz.getMethod(method);
                SshConstant.CACHE_MAP.put(class_method, new Cache(ctlObj, ctlMet));// put
                // cache

                // ctlMet.invoke(ctlObj, req, resp);
                ctlMet.invoke(ctlObj);
                // long end = System.currentTimeMillis();
                // //System.out.println("" + (end - begin));
            }
        } else {
            ServletOutputStream out = resp.getOutputStream();
            out.print("error");
            out.flush();
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:org.apache.nifi.remote.client.http.TestHttpClient.java

private static void respondWithText(HttpServletResponse resp, String result, int statusCode)
        throws IOException {
    resp.setContentType("text/plain");
    resp.setStatus(statusCode);/* w ww  .ja va2  s .  co  m*/
    final ServletOutputStream out = resp.getOutputStream();
    out.write(result.getBytes());
    out.flush();
}

From source file:com.mobicage.rogerthat.CallbackApiServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json-rpc; charset=utf-8");

    // Validate incomming request
    final String contentType = req.getHeader("Content-type");
    if (contentType == null || !contentType.startsWith("application/json-rpc")) {
        resp.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
        return;/*w ww  . ja v  a  2s  . c o  m*/
    }
    final String sikKey = req.getHeader("X-Nuntiuz-Service-Key");
    if (!validateSIK(sikKey)) {
        resp.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED);
        return;
    }

    // Parse
    final InputStream is = req.getInputStream();
    final JSONObject request;
    try {
        request = (JSONObject) JSONValue.parse(new BufferedReader(new InputStreamReader(is, "UTF-8")));
    } finally {
        is.close();
    }

    if (logTraffic)
        log.info(String.format("Incoming Rogerthat API Callback.\nSIK: %s\n\n%s", sikKey,
                request.toJSONString()));

    final String id = (String) request.get("id");

    if (callbackDedup != null) {
        byte[] response = callbackDedup.getResponse(id);
        if (response != null) {
            ServletOutputStream outputStream = resp.getOutputStream();
            outputStream.write(response);
            outputStream.flush();
            return;
        }
    }

    final JSONObject result = new JSONObject();
    final RequestContext requestContext = new RequestContext(id, sikKey);
    try {
        processor.process(request, result, requestContext);
    } finally {
        String jsonString = result.toJSONString();
        if (logTraffic)
            log.info("Returning result:\n" + jsonString);

        byte[] response = jsonString.getBytes("UTF-8");
        if (callbackDedup != null) {
            callbackDedup.storeResponse(id, response);
        }

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

From source file:eu.europa.ejusticeportal.dss.controller.action.DownloadSealedPdf.java

/**
 * Send the PDF to the http response//from   w  w w .j  a  v a 2 s.co  m
 * @param is the stream containing the PDF
 * @param pdfName the name of the PDF
 * @param response the HttpServletResponse to which the PDF will be written
 * @throws IOException
 */
private void sendPdf(InputStream is, String pdfName, HttpServletResponse response) throws IOException {
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + pdfName + "\"");

    ServletOutputStream outs = null;
    try {
        outs = response.getOutputStream();
        int r = 0;
        byte[] chunk = new byte[8192];
        while ((r = is.read(chunk)) != -1) {
            outs.write(chunk, 0, r);
        }
        outs.flush();
    } finally {
        IOUtils.closeQuietly(outs);
    }

}

From source file:net.shopxx.controller.shop.QRCodeController.java

/**
  * ?base64?  ?? base64//  ww w  .  j  a v a2 s. c  om
  */
@RequestMapping(value = "/encodeBase64", method = RequestMethod.GET)
public void image(String text, String ico, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    text = new String(new BASE64Decoder().decodeBuffer(text), "utf-8");
    String[] splits = text.split("\\?");

    text = splits[0] + "?parameter=" + Base64.encodeBase64String(splits[1].getBytes());

    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    ServletOutputStream servletOutputStream = null;
    try {
        servletOutputStream = response.getOutputStream();
        BufferedImage bufferedImage = QRCodeUtil.createImageInUrl(text, ico, true, 0, 0);
        ImageIO.write(bufferedImage, "jpg", servletOutputStream);
        servletOutputStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(servletOutputStream);
    }
}