Example usage for javax.servlet.http HttpServletResponse getOutputStream

List of usage examples for javax.servlet.http HttpServletResponse getOutputStream

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse getOutputStream.

Prototype

public ServletOutputStream getOutputStream() throws IOException;

Source Link

Document

Returns a ServletOutputStream suitable for writing binary data in the response.

Usage

From source file:net.sf.appstatus.web.pages.ServicesPage.java

@Override
public void doGet(StatusWebHandler webHandler, HttpServletRequest req, HttpServletResponse resp)
        throws UnsupportedEncodingException, IOException {

    setup(resp, "text/html");
    ServletOutputStream os = resp.getOutputStream();

    Map<String, String> valuesMap = new HashMap<String, String>();

    List<IService> services = webHandler.getAppStatus().getServices();
    Collections.sort(services);/*  w ww.j  av a 2s  .  com*/

    StrBuilder sbServicesTable = new StrBuilder();

    if (HtmlUtils.generateBeginTable(sbServicesTable, services.size())) {

        HtmlUtils.generateHeaders(sbServicesTable, "", "Group", "Name", "Hits", "Cache", "Running", "min",
                "max", "avg", "nested", "min (c)", "max (c)", "avg (c)", "nested (c)", "Errors", "Failures",
                "Hit rate");

        for (IService service : services) {
            HtmlUtils.generateRow(sbServicesTable, Resources.STATUS_JOB, service.getGroup(), service.getName(),
                    service.getHits(),
                    service.getCacheHits() + getPercent(service.getCacheHits(), service.getHits()),
                    service.getRunning(), service.getMinResponseTime(), service.getMaxResponseTime(),
                    Math.round(service.getAvgResponseTime()), Math.round(service.getAvgNestedCalls()),
                    service.getMinResponseTimeWithCache(), service.getMaxResponseTimeWithCache(),
                    Math.round(service.getAvgResponseTimeWithCache()),
                    Math.round(service.getAvgNestedCallsWithCache()),
                    service.getErrors() + getPercent(service.getErrors(), service.getHits()),
                    service.getFailures() + getPercent(service.getFailures(), service.getHits()),
                    getRate(service.getCurrentRate()));
        }

        HtmlUtils.generateEndTable(sbServicesTable, services.size());
    }

    // generating content
    valuesMap.put("servicesTable", sbServicesTable.toString());
    String content = HtmlUtils.applyLayout(valuesMap, PAGECONTENTLAYOUT);

    valuesMap.clear();
    valuesMap.put("content", content);
    // generating page
    os.write(getPage(webHandler, valuesMap).getBytes(ENCODING));
}

From source file:net.sourceforge.ajaxtags.servlets.SourceLoader.java

/**
 * Write the content from the jarfile to the client stream. Use bufferedwriter to handle
 * newline. The filename is found in the requestURI, the contextpath is excluded and replaced
 * with the base package name.//from   ww  w  . j a v  a  2  s . c  o  m
 *
 * @param req
 *            the request
 * @param resp
 *            the response
 * @throws ServletException
 *             any errors
 * @throws IOException
 *             any io errors
 */
public void service(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final String res = req.getRequestURI();
    final OutputStream stream = resp.getOutputStream();
    final byte[] buffer = new byte[BUFFER];

    String loadPath = res.substring(req.getContextPath().length());

    if (prefix != null && loadPath.startsWith(prefix)) {
        loadPath = loadPath.substring(prefix.length());
    }

    InputStream in = null;
    try {
        in = getClass().getResourceAsStream(SourceLoader.BASE + loadPath);
        if (in == null) {
            throw new IOException("resource not found");
        }
        int read = -1;
        while ((read = in.read(buffer)) != -1) {
            stream.write(buffer, 0, read);
        }
    } finally {
        if (in != null) {
            in.close();
        }
        stream.flush();
        stream.close();
    }
}

From source file:DeleteClobFromOracleServlet.java

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

    Connection conn = null;//  w  w w  .j  a  v a 2s. co m
    PreparedStatement pstmt = null;
    String id = "001";
    ServletOutputStream out = response.getOutputStream();
    response.setContentType("text/html");
    out.println("<html><head><title>Delete CLOB Record</title></head>");

    try {
        conn = getConnection();
        pstmt = conn.prepareStatement("delete from DataFiles where id = ?");
        pstmt.setString(1, id);
        pstmt.executeUpdate();
        out.println("<body><h4>deleted CLOB record with id=" + id + "</h4></body></html>");
    } catch (Exception e) {
        out.println("<body><h4>Error=" + e.getMessage() + "</h4></body></html>");
    } finally {
        try {
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.hbs.common.josn.JSONUtil.java

public static void writeJSONToResponse(HttpServletResponse response, String encoding, boolean wrapWithComments,
        String serializedJSON, boolean smd, boolean gzip, String contentType) throws IOException {
    String json = serializedJSON == null ? "" : serializedJSON;
    if (wrapWithComments) {
        StringBuilder sb = new StringBuilder("/* ");
        sb.append(json);/*from   ww w.ja  v a2  s  .c  om*/
        sb.append(" */");
        json = sb.toString();
    }
    if (log.isDebugEnabled()) {
        log.debug("[JSON]" + json);
    }

    if (contentType == null) {
        contentType = "application/json";
    }
    response.setContentType((smd ? "application/json-rpc;charset=" : contentType + ";charset=") + encoding);
    if (gzip) {
        response.addHeader("Content-Encoding", "gzip");
        GZIPOutputStream out = null;
        InputStream in = null;
        try {
            out = new GZIPOutputStream(response.getOutputStream());
            in = new ByteArrayInputStream(json.getBytes());
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            if (in != null)
                in.close();
            if (out != null) {
                out.finish();
                out.close();
            }
        }

    } else {
        response.setContentLength(json.getBytes(encoding).length);
        PrintWriter out = response.getWriter();
        out.print(json);
    }
}

From source file:com.silverpeas.directory.servlets.ImageDisplay.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    ImageProfil profile = new ImageProfil(getAvatar(req));
    InputStream in = null;/*from  w  w  w .ja  va  2s.c  om*/
    OutputStream out = null;
    try {
        in = profile.getImage();
        out = res.getOutputStream();
        IOUtils.copy(in, out);
    } finally {
        if (in != null) {
            IOUtils.closeQuietly(in);
        }
        if (out != null) {
            IOUtils.closeQuietly(out);
        }
    }
}

From source file:com.aurel.track.util.ImageServerAction.java

/**
 * Write the image in the format given to the output stream
 *//*w  w  w.ja  va  2  s  .  co m*/
@Override

public String execute() {
    System.out.println("IMAGE ACTION !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

    ImageProvider imageProvider = (ImageProvider) session.get(imageProviderKey);
    if (imageProvider == null) {
        LOGGER.error("Image provider is Null for: " + imageProviderKey);
        return null;
    }

    Map configParametersMap = (Map) session.get(imageProviderParams);
    LOGGER.debug("imageProviderParams Name :" + imageProviderParams);
    LOGGER.debug("imageProviderParams Value :" + configParametersMap);

    if (imageFormat == null || imageFormat.length() < 1) {
        imageFormat = "png";
    }

    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType("image/" + imageFormat);
    try {
        ServletOutputStream out = response.getOutputStream();
        imageProvider.writeImage(out, configParametersMap, imageFormat);
    } catch (IOException e) {
        LOGGER.error("Error on write Image:" + e.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    return null;
}

From source file:com.zuoxiaolong.niubi.job.test.http.DownloadFileController.java

@RequestMapping("/download/test.txt")
public void downloadTxt(HttpServletResponse response) throws IOException {
    String fileName = "test.txt";
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    OutputStream outputStream = response.getOutputStream();
    outputStream.write("hello".getBytes());
    outputStream.flush();/*  www.  j a  va2s  . c om*/
    outputStream.close();
}

From source file:com.example.multipart.MultipartServiceImpl.java

@Override
public void downloadByteArrayData(byte[] content, String contentType, String filename,
        HttpServletResponse response) throws IOException {

    InputStream is = new ByteArrayInputStream(content);

    response.setContentType(contentType);
    response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filename + "\"");
    copy(is, response.getOutputStream());
    response.flushBuffer();//ww  w  .ja v a2s . c  o m
}

From source file:com.nzion.web.PdfServlet.java

@Override
protected void service(HttpServletRequest reqqest, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/plm");
    response.setHeader("Content-Disposition", "attachment; filename=2D.plm");
    ServletOutputStream outputStream = response.getOutputStream();
    BufferedInputStream bufferedInputStream = new BufferedInputStream(
            new FileInputStream(new File("F:\\PDF_Stamping\\2D\\2D.zip")));
    IOUtils.copy(bufferedInputStream, outputStream);
    bufferedInputStream.close();/*from ww w.  j a  va2 s.  c  o m*/
    outputStream.flush();
}

From source file:net.dstc.mkts.rest.MktSurveyService.java

@POST
@Protected//w  w w. ja  va  2s. c o m
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Register new survey", code = 201, authorizations = { @Authorization(value = "oauth2") })
public void insert(SurveyDTO survey, @Context HttpServletResponse response)
        throws NotAuthException, OAuthSystemException {

    service.insert(survey);

    response.setStatus(HttpServletResponse.SC_CREATED);
    try {
        response.getOutputStream().close();
    } catch (Exception ex) {
    }
}