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:be.fedict.eid.applet.service.PhotoServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");
    response.setContentType("image/jpg");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    response.setHeader("Pragma", "no-cache, no-store"); // http 1.0
    response.setDateHeader("Expires", -1);
    ServletOutputStream out = response.getOutputStream();
    HttpSession session = request.getSession();
    byte[] photoData = (byte[]) session.getAttribute(IdentityDataMessageHandler.PHOTO_SESSION_ATTRIBUTE);
    if (null != photoData) {
        BufferedImage photo = ImageIO.read(new ByteArrayInputStream(photoData));
        if (null == photo) {
            /*// w ww . j av  a  2  s .  c o m
             * In this case we render a photo containing some error message.
             */
            photo = new BufferedImage(140, 200, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = (Graphics2D) photo.getGraphics();
            RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.setRenderingHints(renderingHints);
            graphics.setColor(Color.WHITE);
            graphics.fillRect(1, 1, 140 - 1 - 1, 200 - 1 - 1);
            graphics.setColor(Color.RED);
            graphics.setFont(new Font("Dialog", Font.BOLD, 20));
            graphics.drawString("Photo Error", 0, 200 / 2);
            graphics.dispose();
            ImageIO.write(photo, "jpg", out);
        } else {
            out.write(photoData);
        }
    }
    out.close();
}

From source file:com.globalsight.everest.webapp.pagehandler.tasks.UpdateLeverageHandler.java

@ActionHandler(action = "checkHaveNonReadyWFSelected", formClass = "")
public void checkHaveNonReadyWFSelected(HttpServletRequest p_request, HttpServletResponse p_response,
        Object form) throws Exception {
    HttpSession session = p_request.getSession(false);
    Locale uiLocale = (Locale) session.getAttribute(WebAppConstants.UILOCALE);

    String selectedWfs = (String) p_request.getParameter("selectedWorkFlows");
    List<Long> wfIds = UpdateLeverageHelper.getWfIds(selectedWfs);
    StringBuffer readyWfIds = new StringBuffer();
    StringBuffer nonReadyWfs = new StringBuffer();
    int count = 0;
    for (Iterator<Long> it = wfIds.iterator(); it.hasNext();) {
        Long wfId = it.next();//from w  w w . j  a  v a  2 s.  com
        Workflow wf = workflowManager.getWorkflowById(wfId);
        if (Workflow.READY_TO_BE_DISPATCHED.equals(wf.getState())) {
            readyWfIds.append(" ").append(wfId);
        } else {
            count++;
            String wfDisplayName = wf.getTargetLocale().getDisplayName(uiLocale);
            if (nonReadyWfs.length() == 0) {
                nonReadyWfs.append(count).append(". ").append(wfDisplayName);
            } else {
                nonReadyWfs.append("_returnPH_").append(count).append(". ").append(wfDisplayName);
            }
        }
    }

    // Write back
    String strReadyWfIds = (readyWfIds.toString().trim().length() > 0 ? readyWfIds.toString().trim() : "");
    String strNonReadyWfs = (nonReadyWfs.length() > 0 ? nonReadyWfs.toString() : "");
    ServletOutputStream out = p_response.getOutputStream();
    try {
        p_response.setContentType("text/plain");
        out = p_response.getOutputStream();
        StringBuffer sb = new StringBuffer();
        sb.append("{\"readyWfIds\":\"");
        sb.append(strReadyWfIds).append("\", \"nonReadyWfs\":\"").append(strNonReadyWfs).append("\"}");
        out.write(sb.toString().getBytes("UTF-8"));
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        out.close();
        pageReturn();
    }
}

From source file:com.bluexml.xforms.controller.navigation.NavigationManager.java

/**
 * Send XForms to Chiba filter.<br>
 * Inserts session id into form.<br>
 * No data manipulation has to be made here.
 * /*from w  ww  . ja v a  2s  . co  m*/
 * @param req
 *            the req
 * @param resp
 *            the resp
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public void sendXForms(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    HttpSession session = req.getSession(true);
    String sessionId = session.getId();

    controller = getController();

    String testStr = StringUtils.trimToNull(req.getParameter(MsgId.PARAM_SERVE_TEST_PAGE.getText()));
    boolean serveTestPage = StringUtils.equals(testStr, "true");
    String pageId = StringUtils.trimToNull(req.getParameter(PAGE_ID));

    // called from a direct link? set our info (pageId, stackId)
    if (pageId == null) {
        // check for a possible initialisation call
        boolean isInit = StringUtils.equals(req.getParameter(MsgId.PARAM_INIT_CALL.getText()), "true");
        if (isInit) {
            ServletOutputStream stream = resp.getOutputStream();
            String result = (loadConfiguration(req, true) == -1) ? "success" : "failure";
            stream.write(result.getBytes());
            stream.close();
            return;
        }
        pageId = NavigationSessionListener.getPageId(sessionId);
        NavigationPath navigationPath = NavigationSessionListener.getNavigationPath(sessionId, pageId);

        // check whether reloading of the mapping.xml file was asked for
        if (StringUtils.equals(req.getParameter(MsgId.PARAM_RELOAD_MAPPING_FILE.getText()), "true")) {
            controller.performDynamicReload();
        }
        // check whether reloading of properties/configuration files was asked for
        if (StringUtils.equals(req.getParameter(MsgId.PARAM_RELOAD_PROPERTIES.getText()), "true")) {
            int resLoad = loadConfiguration(req, false);
            if (logger.isDebugEnabled()) {
                if (resLoad == -1) {
                    logger.debug("Reloaded properties: OK.");
                } else {
                    String reason = "";
                    switch (resLoad) {
                    case 0:
                        reason = "an exception occured";
                        break;
                    case 1:
                        reason = "properties files";
                        break;
                    case 2:
                        reason = "redirection file";
                        break;
                    }
                    logger.debug("Failed in loading the configuration. Reason: " + reason);
                }
            }
        }
        // set specific CSS if given
        this.setCssUrl(req);
        // initial status message. CAUTION: may be overridden later in case of errors.
        String statusMsg = StringUtils.trimToNull(req.getParameter(MsgId.PARAM_STATUS_MSG.getText()));
        if (statusMsg != null) {
            navigationPath.setStatusMsg(statusMsg);
        }
        // deal with standalone mode
        if (StringUtils.equals(req.getParameter(MsgId.PARAM_STANDALONE.getText()), "true")) {
            controller.setStandaloneMode(true);
        }
        if (StringUtils.equals(req.getParameter(MsgId.PARAM_STANDALONE.getText()), "false")) {
            controller.setStandaloneMode(false);
        }

        PageInfoBean pageInfo = collectPageInfo(req);
        // save session and URL we were called with (useful when a host is multi-domain'ed)
        String curServletURL = this.registerSessionURL(req, sessionId);
        // remember where we are
        navigationPath.setCurrentPage(pageInfo);
        String location = curServletURL + "?pageId=" + pageId + "&stackId=" + navigationPath.getSize();
        // propagate queryString
        location += "&" + req.getQueryString();
        if (serveTestPage == false) {
            // redirect the web client, providing ids we need
            resp.sendRedirect(resp.encodeRedirectURL(location));
            return;
        }
    }
    // the ids are available
    NavigationPath navigationPath = NavigationSessionListener.getNavigationPath(sessionId, pageId);
    if (navigationPath.isEmpty()) {
        // the servlet is called directly with ids we did not register
        throw new ServletException(MsgPool.getMsg(MsgId.MSG_SESSION_TIMED_OUT));
    }
    Page currentPage = navigationPath.peekCurrentPage();
    // set the warning if page was called with an object it can't display
    if (currentPage.isWrongCallType()) {
        navigationPath.setStatusMsg("WARNING: the data Id provided is not appropriate for this form.");
    }

    // get the form template as a string
    String statusDisplayedMsg = navigationPath.getStatusDisplayedMsg();
    Document doc = loadXFormsDocument(req, sessionId, pageId, statusDisplayedMsg, currentPage);

    req.setAttribute(WebFactory.XFORMS_NODE, doc);
    resp.getOutputStream().close();
}

From source file:com.portfolio.data.attachment.FileServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    initialize(request);//ww  w . j ava  2 s.  co  m

    int userId = 0;
    int groupId = 0;
    String user = "";
    String context = request.getContextPath();
    String url = request.getPathInfo();

    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    Credential credential = null;
    try {
        //On initialise le dataProvider
        Connection c = null;
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // =====================================================================================
    boolean trace = false;
    StringBuffer outTrace = new StringBuffer();
    StringBuffer outPrint = new StringBuffer();
    String logFName = null;

    response.setCharacterEncoding("UTF-8");

    System.out.println("FileServlet::doGet");
    try {
        // ====== URI : /resources/file[/{lang}]/{context-id}
        // ====== PathInfo: /resources/file[/{uuid}?lang={fr|en}&size={S|L}] pathInfo
        //         String uri = request.getRequestURI();
        String[] token = url.split("/");
        String uuid = token[1];
        //wadbackend.WadUtilities.appendlogfile(logFName, "GETfile:"+request.getRemoteAddr()+":"+uri);

        /// FIXME: Passe la scurit si la source provient de localhost, il faudrait un change afin de s'assurer que n'importe quel servlet ne puisse y accder
        String sourceip = request.getRemoteAddr();
        System.out.println("IP: " + sourceip);

        /// Vrification des droits d'accs
        // TODO: Might be something special with proxy and export/PDF, to investigate
        if (!ourIPs.contains(sourceip)) {
            if (userId == 0)
                throw new RestWebApplicationException(Status.FORBIDDEN, "");

            if (!credential.hasNodeRight(userId, groupId, uuid, Credential.READ)) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                //throw new Exception("L'utilisateur userId="+userId+" n'a pas le droit READ sur le noeud "+nodeUuid);
            }
        } else // Si la requte est locale et qu'il n'y a pas de session, on ignore la vrification
        {
            System.out.println("IP OK: bypass");
        }

        /// On rcupre le noeud de la ressource pour retrouver le lien
        String data = dataProvider.getResNode(uuid, userId, groupId);

        //         javax.servlet.http.HttpSession session = request.getSession(true);
        //====================================================
        //String ppath = session.getServletContext().getRealPath("/");
        //logFName = ppath +"logs/logNode.txt";
        //====================================================
        String size = request.getParameter("size");
        if (size == null)
            size = "S";

        String lang = request.getParameter("lang");
        if (lang == null) {
            lang = "fr";
        }

        /*
        String nodeUuid = uri.substring(uri.lastIndexOf("/")+1);
        if  (uri.lastIndexOf("/")>uri.indexOf("file/")+6) { // -- file/ = 5 carac. --
           lang = uri.substring(uri.indexOf("file/")+5,uri.lastIndexOf("/"));
        }
        //*/

        String ref = request.getHeader("referer");

        /// Parse les donnes
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader("<node>" + data + "</node>"));
        Document doc = documentBuilder.parse(is);
        DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0");
        LSSerializer serial = impl.createLSSerializer();
        serial.getDomConfig().setParameter("xml-declaration", false);

        /// Trouve le bon noeud
        XPath xPath = XPathFactory.newInstance().newXPath();

        /// Either we have a fileid per language
        String filterRes = "//fileid[@lang='" + lang + "']";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);
        String resolve = "";
        if (nodelist.getLength() != 0) {
            Element fileNode = (Element) nodelist.item(0);
            resolve = fileNode.getTextContent();
        }

        /// Or just a single one shared
        if ("".equals(resolve)) {
            response.setStatus(404);
            return;
        }

        String filterName = "//filename[@lang='" + lang + "']";
        NodeList textList = (NodeList) xPath.compile(filterName).evaluate(doc, XPathConstants.NODESET);
        String filename = "";
        if (textList.getLength() != 0) {
            Element fileNode = (Element) textList.item(0);
            filename = fileNode.getTextContent();
        }

        String filterType = "//type[@lang='" + lang + "']";
        textList = (NodeList) xPath.compile(filterType).evaluate(doc, XPathConstants.NODESET);
        String type = "";
        if (textList.getLength() != 0) {
            Element fileNode = (Element) textList.item(0);
            type = fileNode.getTextContent();
        }

        /*
        String filterSize = "//size[@lang='"+lang+"']";
        textList = (NodeList) xPath.compile(filterName).evaluate(doc, XPathConstants.NODESET);
        String filesize = "";
        if( textList.getLength() != 0 )
        {
           Element fileNode = (Element) textList.item(0);
           filesize = fileNode.getTextContent();
        }
        //*/

        System.out.println("!!! RESOLVE: " + resolve);

        /// Envoie de la requte au servlet de fichiers
        // http://localhost:8080/MiniRestFileServer/user/claudecoulombe/file/a8e0f07f-671c-4f6a-be6c-9dba12c519cf/ptype/sql
        /// TODO: Ne plus avoir besoin du switch
        String urlTarget = "http://" + server + "/" + resolve;
        //         String urlTarget = "http://"+ server + "/user/" + resolve +"/"+ lang + "/ptype/fs";

        HttpURLConnection connection = CreateConnection(urlTarget, request);
        connection.connect();
        InputStream input = connection.getInputStream();
        String sizeComplete = connection.getHeaderField("Content-Length");
        int completeSize = Integer.parseInt(sizeComplete);

        response.setContentLength(completeSize);
        response.setContentType(type);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        ServletOutputStream output = response.getOutputStream();

        byte[] buffer = new byte[completeSize];
        int totalRead = 0;
        int bytesRead = -1;

        while ((bytesRead = input.read(buffer, 0, completeSize)) != -1 || totalRead < completeSize) {
            output.write(buffer, 0, bytesRead);
            totalRead += bytesRead;
        }

        //         IOUtils.copy(input, output);
        //         IOUtils.closeQuietly(output);

        output.flush();
        output.close();
        input.close();
        connection.disconnect();
    } catch (RestWebApplicationException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        logger.error(e.toString() + " -> " + e.getLocalizedMessage());
        e.printStackTrace();
        //wadbackend.WadUtilities.appendlogfile(logFName, "GETfile: error"+e);
    } finally {
        try {
            dataProvider.disconnect();
        } catch (Exception e) {
            ServletOutputStream out = response.getOutputStream();
            out.println("Erreur dans doGet: " + e);
            out.close();
        }
    }
}

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

/**
 * Return the XML with the results/*from   w  w w  .j av a 2 s.co m*/
 * @param request
 * @param response
 * @param species
 * @param matchesByPolygon
 * @return
 * @throws java.lang.Exception
 */
private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response,
        List<String> species, List<Node> matchesByPolygon) throws Exception {

    response.setCharacterEncoding("ISO-8859-1");
    response.setContentType("text/xml");
    ServletOutputStream out = response.getOutputStream();
    StringBuilder result = new StringBuilder();

    if (matchesByPolygon == null) { //If there is not geographical criteria
        result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response><speciesList>");
        for (String s : species) {
            result.append("<species>" + s + "</species>");
        }
        result.append("</speciesList><polygons></polygons></response>");
        out.println(result.toString());
    } else { //If there is gegraphical criteria
        result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response>");
        result.append("<speciesList></speciesList>");
        result.append("<polygons>");
        for (Node node : matchesByPolygon) {

            result.append("<polygon>");
            result.append("<abs>" + node.getValue1() + "</abs>");
            result.append("<per>" + node.getValue2() + "</per>");
            for (String sp : node.getValue3()) {
                result.append("<sp>" + sp + "</sp>");
            }
            result.append("</polygon>");
        }
        result.append("</polygons></response>");
        out.println(result.toString());
    }

    out.flush();
    out.close();

    return null;
}

From source file:org.apache.wookie.WidgetAdminServlet.java

private void doDownload(HttpServletRequest req, HttpServletResponse resp, File f, String original_filename)
        throws IOException {
    int BUFSIZE = 1024;

    // File f = new File(filename);
    int length = 0;
    ServletOutputStream op = resp.getOutputStream();
    ServletContext context = getServletConfig().getServletContext();
    String mimetype = context.getMimeType(f.getAbsolutePath());

    ///* w  w  w .j ava2 s . c o  m*/
    // Set the response and go!
    //
    //
    resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
    resp.setContentLength((int) f.length());
    resp.setHeader("Content-Disposition", "attachment; filename=\"" + original_filename + "\"");

    //
    // Stream to the requester.
    //
    byte[] bbuf = new byte[BUFSIZE];
    DataInputStream in = new DataInputStream(new FileInputStream(f));

    while ((in != null) && ((length = in.read(bbuf)) != -1)) {
        op.write(bbuf, 0, length);
    }

    in.close();
    op.flush();
    op.close();
}

From source file:pt.ist.expenditureTrackingSystem.presentationTier.actions.organization.OrganizationAction.java

public ActionForward listSuppliers(final ActionMapping mapping, final ActionForm form,
        final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    Spreadsheet suppliersSheet = getSuppliersSheet();
    response.setContentType("application/xls ");
    response.setHeader("Content-disposition", "attachment; filename=fornecedores.xls");

    ServletOutputStream outputStream = response.getOutputStream();

    suppliersSheet.exportToXLSSheet(outputStream);
    outputStream.flush();//ww  w  . j  ava2s . c o  m
    outputStream.close();

    return null;
}

From source file:pt.ist.expenditureTrackingSystem.presentationTier.actions.organization.OrganizationAction.java

public final ActionForward downloadSupplierAcquisitionInformation(final ActionMapping mapping,
        final ActionForm form, final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {

    final Supplier supplier = getDomainObject(request, "supplierOid");
    final Spreadsheet suppliersSheet = getSupplierAcquisitionInformationSheet(supplier);
    response.setContentType("application/xls ");
    response.setHeader("Content-disposition", "attachment; filename=fornecedor.xls");

    final ServletOutputStream outputStream = response.getOutputStream();

    suppliersSheet.exportToXLSSheet(outputStream);
    outputStream.flush();//from   w ww.j a  v  a2s  .co m
    outputStream.close();

    return null;
}

From source file:com.wyp.module.controller.LicenseController.java

/**
 * /*from w  w  w  .j  a  v a2  s.  com*/
 * @param response
 * @param responseJson
 * @param type
 */
private void repsonseJsonResult(HttpServletResponse response, String responseJson, String type) {
    BufferedOutputStream buff = null;
    StringBuffer write = new StringBuffer();
    ServletOutputStream outStr = null;
    try {
        outStr = response.getOutputStream();// 
        buff = new BufferedOutputStream(outStr);
        // ?json?text
        if ("json".equals(type)) {
            response.setContentType("application/json");// 
            write.append(responseJson);
        } else {
            // ** 
            response.setContentType("text/plain");// 
            response.addHeader("Content-Disposition", "attachment;filename=license.asc");// filename??O
            String enter = "\r\n";
            // json?
            List<Object> list = parseLicenses(responseJson);
            for (int i = 0; i < list.size(); i++) {
                write.append(list.get(i));
                write.append(enter);
            }
        }
        buff.write(write.toString().getBytes("UTF-8"));
        buff.flush();
        buff.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            buff.close();
            outStr.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.mskcc.pathdb.action.web_api.NeighborhoodMapRetriever.java

/**
 * Writes html code that constructs frameset for map/legend.
 *
 * @param response HttpServletResponse/* w  w  w .j av  a2 s  .  com*/
 * @throws IOException
 */
private void writeFramesetToResponse(HttpServletResponse response) throws IOException {

    log.info("NeighborhoodMapRetriever.writeFramesetToResponse");

    // set content type
    response.setContentType("text/html");
    CONTENT_TYPE_SET = true;
    ServletOutputStream stream = response.getOutputStream();

    // write out html to define frameset
    stream.println("<html>");
    stream.println("<head>");
    stream.println("<title>Neighborhood Map</title>");
    stream.println("</head>");
    stream.println("<frameset cols=\"60%,40%\">");
    stream.println("<frame src=\"webservice.do?" + ProtocolRequest.ARG_VERSION + "="
            + ProtocolConstantsVersion3.VERSION_3 + "&" + ProtocolRequest.ARG_COMMAND + "="
            + ProtocolConstantsVersion2.COMMAND_GET_NEIGHBORS + "&" + ProtocolRequest.ARG_QUERY + "="
            + Long.toString(PHYSICAL_ENTITY_RECORD_ID) + "&" + ProtocolRequest.ARG_DATA_SOURCE + "="
            + PROTOCOL_REQUEST.getDataSource() + "&" + ProtocolRequest.ARG_OUTPUT + "="
            + ProtocolConstantsVersion2.FORMAT_IMAGE_MAP + "\">");
    stream.println("<frame src=\"sif_legend.do\">");
    stream.println("</frameset>");
    stream.println("</html>");

    // outta here
    stream.flush();
    stream.close();
}