Example usage for javax.servlet ServletOutputStream close

List of usage examples for javax.servlet ServletOutputStream close

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with this stream.

Usage

From source file:org.apache.catalina.core.ApplicationDispatcher.java

private void doForward(ServletRequest request, ServletResponse response) throws ServletException, IOException {

    // Reset any output that has been buffered, but keep headers/cookies
    if (response.isCommitted()) {
        if (log.isDebugEnabled())
            log.debug("  Forward on committed response --> ISE");
        throw new IllegalStateException(sm.getString("applicationDispatcher.forward.ise"));
    }/*from   w  w  w.  j a  va 2 s.c  o  m*/
    try {
        response.resetBuffer();
    } catch (IllegalStateException e) {
        if (log.isDebugEnabled())
            log.debug("  Forward resetBuffer() returned ISE: " + e);
        throw e;
    }

    // Set up to handle the specified request and response
    setup(request, response, false);

    // Identify the HTTP-specific request and response objects (if any)
    HttpServletRequest hrequest = null;
    if (request instanceof HttpServletRequest)
        hrequest = (HttpServletRequest) request;
    HttpServletResponse hresponse = null;
    if (response instanceof HttpServletResponse)
        hresponse = (HttpServletResponse) response;

    // Handle a non-HTTP forward by passing the existing request/response
    if ((hrequest == null) || (hresponse == null)) {

        if (log.isDebugEnabled())
            log.debug(" Non-HTTP Forward");

        processRequest(hrequest, hresponse);

    }

    // Handle an HTTP named dispatcher forward
    else if ((servletPath == null) && (pathInfo == null)) {

        if (log.isDebugEnabled())
            log.debug(" Named Dispatcher Forward");

        processRequest(request, response);

    }

    // Handle an HTTP path-based forward
    else {

        if (log.isDebugEnabled())
            log.debug(" Path Based Forward");

        ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest();
        String contextPath = context.getPath();
        wrequest.setContextPath(contextPath);
        wrequest.setRequestURI(requestURI);
        wrequest.setServletPath(servletPath);
        wrequest.setPathInfo(pathInfo);

        wrequest.setAttribute(Globals.FORWARD_REQUEST_URI_ATTR, hrequest.getRequestURI());
        wrequest.setAttribute(Globals.FORWARD_CONTEXT_PATH_ATTR, hrequest.getContextPath());
        wrequest.setAttribute(Globals.FORWARD_SERVLET_PATH_ATTR, hrequest.getServletPath());
        wrequest.setAttribute(Globals.FORWARD_PATH_INFO_ATTR, hrequest.getPathInfo());
        wrequest.setAttribute(Globals.FORWARD_QUERY_STRING_ATTR, hrequest.getQueryString());

        if (queryString != null) {
            wrequest.setQueryString(queryString);
            wrequest.setQueryParams(queryString);
        }

        processRequest(request, response);
        unwrapRequest();

    }

    // This is not a real close in order to support error processing
    if (log.isDebugEnabled())
        log.debug(" Disabling the response for futher output");

    if (response instanceof ResponseFacade) {
        ((ResponseFacade) response).finish();
    } else {
        // Servlet SRV.6.2.2. The Resquest/Response may have been wrapped
        // and may no longer be instance of RequestFacade 
        if (log.isDebugEnabled()) {
            log.debug(" The Response is vehiculed using a wrapper: " + response.getClass().getName());
        }

        // Close anyway
        try {
            PrintWriter writer = response.getWriter();
            writer.close();
        } catch (IllegalStateException e) {
            try {
                ServletOutputStream stream = response.getOutputStream();
                stream.close();
            } catch (IllegalStateException f) {
                ;
            } catch (IOException f) {
                ;
            }
        } catch (IOException e) {
            ;
        }
    }

}

From source file:com.ewcms.plugin.vote.manager.web.ResultServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletOutputStream out = null;
    StringBuffer output = new StringBuffer();
    try {//w w w.  j  av  a 2s . c o m
        String id = req.getParameter("id");

        if (!id.equals("") && StringUtils.isNumeric(id)) {
            Long questionnaireId = new Long(id);

            ServletContext application = getServletContext();
            WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);
            VoteFacable voteFac = (VoteFacable) wac.getBean("voteFac");

            String ipAddr = req.getRemoteAddr();

            output = voteFac.getQuestionnaireResultClientToHtml(questionnaireId,
                    getServletContext().getContextPath(), ipAddr);
        }
        out = resp.getOutputStream();
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        out.write(output.toString().getBytes("UTF-8"));
        out.flush();
    } finally {
        if (out != null) {
            out.close();
            out = null;
        }
    }
}

From source file:com.esri.gpt.control.cart.XslBundler.java

/**
 * Processes the HTTP request./*from   www .  j a v a2  s. c om*/
 * @param request the HTTP request
 * @param response HTTP response
 * @param context request context
 * @throws Exception if an exception occurs
 */
@Override
public void execute(HttpServletRequest request, HttpServletResponse response, RequestContext context)
        throws Exception {
    String[] keys = this.readKeys(request, context, true);
    String sXsltPath = Val.chkStr(request.getParameter("xslt"));
    String sMimeType = Val.chkStr(request.getParameter("mimeType"));
    String sContentDisposition = Val.chkStr(request.getParameter("contentDisposition"));
    if ((keys.length > 0) && (sXsltPath.length() > 0)) {
        if (!assertWhiteList(context, "catalog.cart.xslt.whitelist", sXsltPath)) {
            throw new ServletException("Invalid xslt parameter");
        }
        XsltTemplate template = this.getCompiledTemplate(sXsltPath);
        ServletOutputStream out = response.getOutputStream();

        if (sMimeType.length() == 0) {
            sMimeType = "text/plain";
        }
        response.setContentType(StringEscapeUtils.escapeHtml4(Val.stripControls(sMimeType)) + ";charset=UTF-8");
        if (sContentDisposition.length() > 0) {
            response.addHeader("Content-Disposition",
                    StringEscapeUtils.escapeHtml4(Val.stripControls(sContentDisposition)));
        }

        try {
            for (String sKey : keys) {
                String sXml = this.readXml(request, context, sKey);
                String sResult = Val.chkStr(template.transform(sXml));
                if (sResult.length() > 0) {
                    byte[] bytes = sResult.getBytes("UTF-8");
                    out.write(bytes);
                    out.flush();
                }
            }
        } finally {
            out.flush();
            out.close();
        }
    }
}

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   www .  j  a v  a 2 s .c o 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:com.aaasec.sigserv.csspserver.SpServlet.java

/**
 * Processes requests for both HTTP//from   ww w. ja  v  a 2s .c o m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");

    SpSession session = getSession(request, response);

    RequestModel req = reqFactory.getRequestModel(request, session);
    AuthData authdata = req.getAuthData();

    // Supporting devmode login
    if (SpModel.isDevmode()) {
        authdata = TestIdentities.getTestID(request, req);
        req.setAuthData(authdata);
        if (authdata.getAuthType().length() == 0) {
            authdata.setAuthType("devlogin");
        }
        session.setIdpEntityId(authdata.getIdpEntityID());
        session.setSignerAttribute(RequestModelFactory.getAttrOidString(authdata.getIdAttribute()));
        session.setSignerId(authdata.getId());
    }

    //Terminate if no valid request data
    if (req == null) {
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        response.getWriter().write("");
        return;
    }

    // Handle form post from web page
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        response.getWriter().write(SpServerLogic.processFileUpload(request, response, req));
        return;
    }

    // Handle auth data request 
    if (req.getAction().equals("authdata")) {
        response.setContentType("application/json");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write(gson.toJson(authdata));
        return;
    }

    // Get list of serverstored xml documents
    if (req.getAction().equals("doclist")) {
        response.setContentType("application/json");
        response.getWriter().write(SpServerLogic.getDocList());
        return;
    }

    // Provide info about the session for logout handling
    if (req.getAction().equals("logout")) {
        response.setContentType("application/json");
        Logout lo = new Logout();
        lo.authType = (request.getAuthType() == null) ? "" : request.getAuthType();
        lo.devmode = String.valueOf(SpModel.isDevmode());
        response.getWriter().write(gson.toJson(lo));
        return;
    }

    // Respons to a client alive check to test if the server session is alive
    if (req.getAction().equals("alive")) {
        response.setContentType("application/json");
        response.getWriter().write("[]");
        return;
    }

    // Handle sign request and return Xhtml form with post data to the signature server
    if (req.getAction().equals("sign")) {
        boolean addSignMessage = (req.getParameter().equals("message"));
        String xhtml = SpServerLogic.prepareSignRedirect(req, addSignMessage);
        response.getWriter().write(xhtml);
        return;
    }

    // Get status data about the current session
    if (req.getAction().equals("status")) {
        response.setContentType("application/json");
        response.getWriter().write(gson.toJson(session.getStatus()));
        return;
    }

    // Handle a declined sign request
    if (req.getAction().equals("declined")) {
        if (SpModel.isDevmode()) {
            response.sendRedirect("index.jsp?declined=true");
            return;
        }
        response.sendRedirect("https://eid2cssp.3xasecurity.com/sign/index.jsp?declined=true");
        return;
    }

    // Return Request and response data as a file.
    if (req.getAction().equalsIgnoreCase("getReqRes")) {
        response.setContentType("text/xml;charset=UTF-8");
        byte[] data = TestCases.getRawData(req);
        BufferedInputStream fis = new BufferedInputStream(new ByteArrayInputStream(data));
        ServletOutputStream output = response.getOutputStream();
        if (req.getParameter().equalsIgnoreCase("download")) {
            response.setHeader("Content-Disposition", "attachment; filename=" + req.getId() + ".xml");
        }

        int readBytes = 0;
        byte[] buffer = new byte[10000];
        while ((readBytes = fis.read(buffer, 0, 10000)) != -1) {
            output.write(buffer, 0, readBytes);
        }
        output.flush();
        output.close();
        fis.close();
        return;
    }

    // Return the signed document
    if (req.getAction().equalsIgnoreCase("getSignedDoc")
            || req.getAction().equalsIgnoreCase("getUnsignedDoc")) {
        // If the request if for a plaintext document, or only if the document has a valid signature
        if (session.getStatus().signedDocValid || req.getAction().equalsIgnoreCase("getUnsignedDoc")) {
            response.setContentType(session.getDocumentType().getMimeType());
            switch (session.getDocumentType()) {
            case XML:
                response.getWriter().write(new String(session.getSignedDoc(), Charset.forName("UTF-8")));
                return;
            case PDF:
                File docFile = session.getDocumentFile();
                if (req.getAction().equalsIgnoreCase("getSignedDoc") && session.getStatus().signedDocValid) {
                    docFile = session.getSigFile();
                }
                FileInputStream fis = new FileInputStream(docFile);
                ServletOutputStream output = response.getOutputStream();
                if (req.getParameter().equalsIgnoreCase("download")) {
                    response.setHeader("Content-Disposition", "attachment; filename=" + "signedPdf.pdf");
                }

                int readBytes = 0;
                byte[] buffer = new byte[10000];
                while ((readBytes = fis.read(buffer, 0, 10000)) != -1) {
                    output.write(buffer, 0, readBytes);
                }
                output.flush();
                output.close();
                fis.close();
                return;
            }
            return;
        } else {
            if (SpModel.isDevmode()) {
                response.sendRedirect("index.jsp");
                return;
            }
            response.sendRedirect("https://eid2cssp.3xasecurity.com/sign/index.jsp");
            return;
        }
    }

    // Process a sign response from the signature server
    if (req.getSigResponse().length() > 0) {
        try {
            byte[] sigResponse = Base64Coder.decode(req.getSigResponse().trim());

            // Handle response
            SpServerLogic.completeSignedDoc(sigResponse, req);

        } catch (Exception ex) {
        }
        if (SpModel.isDevmode()) {
            response.sendRedirect("index.jsp");
            return;
        }
        response.sendRedirect("https://eid2cssp.3xasecurity.com/sign/index.jsp");
        return;
    }

    // Handle testcases
    if (req.getAction().equals("test")) {
        boolean addSignMessage = (req.getParameter().equals("message"));
        String xhtml = TestCases.prepareTestRedirect(request, response, req, addSignMessage);
        respond(response, xhtml);
        return;
    }

    // Get test data for display such as request data, response data, certificates etc.
    if (req.getAction().equals("info")) {
        switch (session.getDocumentType()) {
        case PDF:
            File returnFile = null;
            if (req.getId().equalsIgnoreCase("document")) {
                respond(response, getDocIframe("getUnsignedDoc", needPdfDownloadButton(request)));
            }
            if (req.getId().equalsIgnoreCase("formSigDoc")) {
                respond(response, getDocIframe("getSignedDoc", needPdfDownloadButton(request)));
            }
            respond(response, TestCases.getTestData(req));
            return;
        default:
            respond(response, TestCases.getTestData(req));
            return;
        }
    }

    if (req.getAction().equals("verify")) {
        response.setContentType("text/xml;charset=UTF-8");
        String sigVerifyReport = TestCases.getTestData(req);
        if (sigVerifyReport != null) {
            respond(response, sigVerifyReport);
            return;
        }
    }

    nullResponse(response);
}

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

protected void exportDecisionTable(HttpServletResponse response, AbstractModel decisionTableModel) {
    DecisionTableRepresentation decisionTableRepresentation = getDecisionTableRepresentation(
            decisionTableModel);/* w  ww  .  j  ava 2s.  c  om*/

    // 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");
    }
}

From source file:com.sample.JavaHTTPResource.java

public void execute(HttpHost host, HttpUriRequest req, HttpServletResponse resultResponse)
        throws IOException, IllegalStateException, SAXException {
    HttpResponse RSSResponse = client.execute(host, req);
    ServletOutputStream os = resultResponse.getOutputStream();
    if (RSSResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        resultResponse.addHeader("Content-Type", "application/json");
        //String json = IOUtils.toString(RSSResponse.getEntity().getContent());
        InputStream in = RSSResponse.getEntity().getContent();
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String read;//ww  w. ja va2  s .co m

        while ((read = br.readLine()) != null) {
            //System.out.println(read);
            sb.append(read);
        }

        br.close();
        os.write(sb.toString().getBytes(Charset.forName("UTF-8")));

    } else {
        resultResponse.setStatus(RSSResponse.getStatusLine().getStatusCode());
        RSSResponse.getEntity().getContent().close();
        os.write(RSSResponse.getStatusLine().getReasonPhrase().getBytes());
    }
    os.flush();
    os.close();
}

From source file:com.synnex.saas.platform.core.servlet.CaptchaServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from  w w  w . ja  v a 2  s.co  m
        int width = 50;
        int height = 18;
        String captchaCode = RandomStringUtils.random(4, true, true);
        HttpSession session = request.getSession(true);
        session.setAttribute("captchaCode", captchaCode);

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

        ServletOutputStream out = response.getOutputStream();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);
        Font mFont = new Font("Times New Roman", Font.BOLD, 18);
        g.setFont(mFont);
        g.setColor(getRandColor(160, 200));
        Random random = new Random();
        for (int i = 0; i < 155; i++) {
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            int x3 = random.nextInt(12);
            int y3 = random.nextInt(12);
            g.drawLine(x2, y2, x2 + x3, y2 + y3);
        }
        g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
        g.drawString(captchaCode, 2, 16);
        g.dispose();
        ImageIO.write((BufferedImage) image, "JPEG", out);
        out.close();
    } catch (Exception e) {
        logger.error("Generate captcha failed.", e);
    }
}

From source file:org.flowable.ui.modeler.service.FlowableDecisionTableService.java

protected void exportDecisionTable(HttpServletResponse response, AbstractModel decisionTableModel) {
    DecisionTableRepresentation decisionTableRepresentation = getDecisionTableRepresentation(
            decisionTableModel);/*from w  w  w.  java2s . c o m*/

    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");
    }
}

From source file:UrlServlet.java

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

    //get the 'file' parameter
    String fileName = (String) request.getParameter("file");
    if (fileName == null || fileName.equals(""))
        throw new ServletException("Invalid or non-existent file parameter in UrlServlet servlet.");

    if (fileName.indexOf(".pdf") == -1)
        fileName = fileName + ".pdf";

    URL pdfDir = null;/*from  w  ww.  j a va2 s.  c o  m*/
    URLConnection urlConn = null;
    ServletOutputStream stream = null;
    BufferedInputStream buf = null;
    try {

        pdfDir = new URL(getServletContext().getInitParameter("remote-pdf-dir") + fileName);

    } catch (MalformedURLException mue) {

        throw new ServletException(mue.getMessage());
    }
    try {

        stream = response.getOutputStream();

        //set response headers
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=" + fileName);

        urlConn = pdfDir.openConnection();
        response.setContentLength((int) urlConn.getContentLength());

        buf = new BufferedInputStream(urlConn.getInputStream());
        int readBytes = 0;

        //read from the file; write to the ServletOutputStream
        while ((readBytes = buf.read()) != -1)
            stream.write(readBytes);
    } catch (IOException ioe) {
        throw new ServletException(ioe.getMessage());
    } finally {
        if (stream != null)
            stream.close();
        if (buf != null)
            buf.close();
    }
}