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:net.sourceforge.fenixedu.presentationTier.Action.manager.enrolments.CurriculumLineLogsDA.java

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

    final ExecutionSemester executionSemester = getDomainObject(request, "executionSemesterId");

    if (executionSemester != null) {
        final CurriculumLineLogStatisticsCalculator curriculumLineLogStatisticsCalculator = new CurriculumLineLogStatisticsCalculator(
                executionSemester);//from   w  w w. ja  va2 s  . c o  m

        ServletOutputStream writer = null;
        try {
            writer = response.getOutputStream();
            response.setContentType("image/jpeg");
            writer.write(curriculumLineLogStatisticsCalculator.getOperationsChart());
            writer.flush();
        } finally {
            writer.close();
            response.flushBuffer();
        }

    }

    return null;
}

From source file:org.flowable.app.rest.idm.IdmProfileResource.java

@RequestMapping(value = "/profile-picture", method = RequestMethod.GET)
public void getProfilePicture(HttpServletResponse response) {
    try {/*from  www .ja  v a 2 s. c  o  m*/
        Pair<String, InputStream> picture = profileService.getProfilePicture();
        if (picture == null) {
            throw new NotFoundException();
        }
        response.setContentType(picture.getLeft());
        ServletOutputStream servletOutputStream = response.getOutputStream();

        byte[] buffer = new byte[32384];
        while (true) {
            int count = picture.getRight().read(buffer);
            if (count == -1)
                break;
            servletOutputStream.write(buffer, 0, count);
        }

        // Flush and close stream
        servletOutputStream.flush();
        servletOutputStream.close();
    } catch (Exception e) {
        throw new InternalServerErrorException("Could not get profile picture", e);
    }
}

From source file:dijalmasilva.controllers.ControladorUser.java

@RequestMapping("/image/{id}")
public void carregaImagem(@PathVariable Long id, HttpServletResponse resp) {
    ServletOutputStream out = null;
    try {//w w w. j ava2s . c  om
        Usuario usuario = serviceUser.findById(id);
        out = resp.getOutputStream();
        out.write(usuario.getFoto());
        out.flush();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            out.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:org.gcaldaemon.core.servlet.ServletListener.java

private final void processRequest(HttpServletRequest req, HttpServletResponse rsp, boolean getMethod)
        throws ServletException, IOException {
    try {/* w  ww.  j a v  a2 s .  c  o  m*/

        // Transform HttpServletRequest to Request
        Request request = new Request();
        request.method = getMethod ? GET_METHOD : PUT_METHOD;

        // Transform URL
        request.url = req.getPathInfo();
        int i = request.url.indexOf('@');
        if (i != -1) {
            request.url = request.url.substring(0, i) + "%40" + request.url.substring(i + 1);
        }

        // Get the properties of the request
        HashMap properties = new HashMap();
        Enumeration names = req.getHeaderNames();
        String header;
        while (names.hasMoreElements()) {
            header = (String) names.nextElement();
            properties.put(formatString(header.toCharArray()), req.getHeader(header));
        }

        // Transform username and password
        header = (String) properties.get(AUTHORIZATION);
        if (header != null && header.startsWith(BASIC)) {
            header = StringUtils.decodeBASE64(header.substring(6));
            int n = header.indexOf(COLON);
            if (n != 0) {
                request.username = header.substring(0, n);
            }
            if (n != header.length() - 1) {
                request.password = header.substring(n + 1);
            }
        }

        // Get Content-Length header
        int contentLength = 0;
        header = (String) properties.get(CONTENT_LENGTH);
        if (header != null && header.length() != 0) {
            contentLength = Integer.parseInt(header);
        }

        // Read body
        if (contentLength != 0) {
            int packet, readed = 0;
            request.body = new byte[contentLength];
            ServletInputStream in = req.getInputStream();
            while (readed != contentLength) {
                packet = in.read(request.body, readed, contentLength - readed);
                if (packet == -1) {
                    throw new EOFException();
                }
                readed += packet;
            }
        }

        // Redirect request to superclass
        Response response;
        if (getMethod) {
            response = doGet(request);
        } else {
            response = doPut(request);
        }

        // Set response status
        rsp.setStatus(response.status);

        // Add unauthorized header and realm
        if (response.status == STATUS_UNAUTHORIZED) {
            String realm = null;
            int s, e = request.url.indexOf("%40");
            if (e != -1) {
                s = request.url.lastIndexOf('/', e);
                if (s != -1) {
                    realm = request.url.substring(s + 1, e).replace('.', ' ');
                }
            }
            if (realm == null) {
                s = request.url.indexOf("private");
                if (s != -1) {
                    e = request.url.indexOf('/', s + 7);
                    if (e != -1) {
                        realm = request.url.substring(s + 8, e);
                    }
                }
            }
            if (realm == null || realm.length() == 0) {
                realm = "Google Account";
            }
            rsp.addHeader("WWW-Authenticate", "Basic realm=\"" + realm + '\"');
        }

        // Write body
        ServletOutputStream out = null;
        try {
            out = rsp.getOutputStream();
            out.write(response.body);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception ignored) {
                }
            }
        }

    } catch (Exception processingError) {
        throw new ServletException("Unable to process " + req.getMethod() + " request!", processingError);
    }
}

From source file:org.dataconservancy.ui.api.CollectionController.java

@RequestMapping(value = "/{idpart}", method = RequestMethod.GET)
public void handleCollectionGetRequest(@RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestHeader(value = "If-Match", required = false) String ifMatch,
        @RequestHeader(value = "If-None-Match", required = false) String ifNoneMatch,
        @RequestHeader(value = "If-Modified-Since", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date modifiedSince,
        HttpServletRequest request, HttpServletResponse response)
        throws IOException, ArchiveServiceException, BizPolicyException, BizInternalException {

    // Check to see if the user is authenticated (TODO: Spring Security should be responsible for this)
    // Note that the fact that the user has to be authenticated, and further authorized, is a policy decision,
    // but the pattern for the Project and Person controllers is that the Controller has handled this.
    final Person authenticatedUser = getAuthenticatedUser();

    // Rudimentary Accept Header handling; accepted values are */*, application/*, application/xml,
    // application/octet-stream
    if (mimeType != null && !(mimeType.contains(APPLICATION_XML) || mimeType.contains(ACCEPT_WILDCARD)
            || mimeType.contains(ACCEPT_APPLICATION_WILDCARD) || mimeType.contains(ACCEPT_OCTET_STREAM))) {
        response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                "Unacceptable value for 'Accept' header: '" + mimeType + "'");
        return;//from   w  w w .j av  a  2s  .c  om
    }

    // Resolve the Request URL to the ID of the Collection (in this case URL == ID)
    String collectionId = requestUtil.buildRequestUrl(request);

    if (collectionId == null || collectionId.trim().isEmpty()) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // Get the Collection
    final Collection collection = getCollection(collectionId);

    // Calculate the ETag for the Collection, may be null.
    final String etag;
    if (collection != null) {
        etag = calculateEtag(collection);
    } else {
        etag = null;
    }

    // Handle the 'If-Match' header first; RFC 2616 14.24
    if (this.responseHeaderUtil.handleIfMatch(request, response, this.requestUtil, ifMatch, collection, etag,
            collectionId, "Collection")) {
        return;
    }

    final DateTime lastModified;
    if (collection != null) {
        lastModified = getLastModified(collection.getId());
    } else {
        lastModified = null;
    }

    // Handle the 'If-None-Match' header; RFC 2616 14.26
    if (this.responseHeaderUtil.handleIfNoneMatch(request, response, ifNoneMatch, collection, etag,
            collectionId, lastModified, modifiedSince)) {
        return;
    }

    if (collection == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Handle the 'If-Modified-Since' header; RFC 2616 14.26
    if (this.responseHeaderUtil.handleIfModifiedSince(request, response, modifiedSince, lastModified)) {
        return;
    }

    // Check to see if the user is authorized
    if (!authzService.canRetrieveCollection(authenticatedUser, collection)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Compose the Business Object Package
    Bop businessPackage = new Bop();
    businessPackage.addCollection(collection);

    // Serialize the package to an output stream
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    bob.buildBusinessObjectPackage(businessPackage, out);
    out.close();

    this.responseHeaderUtil.setResponseHeaderFields(response, etag, out, lastModified);

    // Send the Response
    final ServletOutputStream servletOutputStream = response.getOutputStream();
    IOUtils.copy(new ByteArrayInputStream(out.toByteArray()), servletOutputStream);
    servletOutputStream.flush();
    servletOutputStream.close();
}

From source file:com.concursive.connect.web.modules.documents.beans.FileDownload.java

/**
 * Description of the Method//from  www .j  ava2  s.  co  m
 *
 * @param context     Description of the Parameter
 * @param bytes       Description of the Parameter
 * @param contentType Description of the Parameter
 * @throws Exception Description of the Exception
 */
public void sendFile(ActionContext context, byte[] bytes, String contentType) throws Exception {
    context.getResponse().setContentType(contentType);
    if (contentType.startsWith("application")) {
        context.getResponse().setHeader("Content-Disposition", "attachment; filename=\"" + displayName + "\";");
        context.getResponse().setContentLength(bytes.length);
    }
    ServletOutputStream outputStream = context.getResponse().getOutputStream();
    outputStream.write(bytes, 0, bytes.length);
    outputStream.flush();
    outputStream.close();
}

From source file:pl.psnc.synat.wrdz.zmkd.plan.MigrationPlansBean.java

/**
 * XML migration plan file download action. Sets request response as XML stream.
 * //from ww w .j  a v  a 2s. c om
 * @param plan
 *            plan from which XML file is taken
 */
public void downloadXML(MigrationPlan plan) {
    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext()
            .getResponse();
    response.setContentType("text/xml");
    response.setHeader("Content-Disposition", "attachment; filename=migration_plan_" + plan.getId() + ".xml");
    response.setContentLength(plan.getXmlFile().length());
    try {
        ServletOutputStream ouputStream = response.getOutputStream();
        ouputStream.write(plan.getXmlFile().getBytes(), 0, plan.getXmlFile().getBytes().length);
        ouputStream.flush();
        ouputStream.close();
    } catch (Exception ex) {
        LOGGER.error(ex);
    }
}

From source file:pivotal.au.se.gemfirexdweb.controller.TypeController.java

@RequestMapping(value = "/types", method = RequestMethod.POST)
public String performTypeAction(Model model, HttpServletResponse response, HttpServletRequest request,
        HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {/*from   w ww.j a  v a2  s.  c  om*/
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    int startAtIndex = 0, endAtIndex = 0;
    String schema = null;
    Result result = new Result();
    List<Type> types = null;
    String ddlString = null;

    logger.debug("Received request to perform an action on the types");

    TypeDAO typeDAO = GemFireXDWebDAOFactory.getTypeDAO();

    String selectedSchema = request.getParameter("selectedSchema");
    logger.debug("selectedSchema = " + selectedSchema);

    if (selectedSchema != null) {
        schema = selectedSchema;
    } else {
        schema = (String) session.getAttribute("schema");
    }

    logger.debug("schema = " + schema);

    if (request.getParameter("search") != null) {
        types = typeDAO.retrieveTypeList(schema, (String) request.getParameter("search"),
                (String) session.getAttribute("user_key"));

        model.addAttribute("search", (String) request.getParameter("search"));
    } else {
        String[] tableList = request.getParameterValues("selected_type[]");
        String commandStr = request.getParameter("submit_mult");

        logger.debug("tableList = " + Arrays.toString(tableList));
        logger.debug("command = " + commandStr);

        // start actions now if tableList is not null

        if (tableList != null) {
            List al = new ArrayList<Result>();
            List<String> al2 = new ArrayList<String>();

            for (String type : tableList) {
                if (commandStr.equalsIgnoreCase("DDL") || commandStr.equalsIgnoreCase("DDL_FILE")) {
                    ddlString = typeDAO.generateDDL(schema, type, (String) session.getAttribute("user_key"));
                    al2.add(ddlString);
                } else {
                    result = null;
                    result = typeDAO.simpletypeCommand(schema, type, commandStr,
                            (String) session.getAttribute("user_key"));
                    al.add(result);
                }
            }

            if (commandStr.equalsIgnoreCase("DDL")) {
                request.setAttribute("arrayresultddl", al2);
            } else if (commandStr.equalsIgnoreCase("DDL_FILE")) {
                response.setContentType(SAVE_CONTENT_TYPE);
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + String.format(FILENAME, "TypeDDL"));

                ServletOutputStream out = response.getOutputStream();
                for (String ddl : al2) {
                    out.println(ddl);
                }

                out.close();
                return null;
            } else {
                model.addAttribute("arrayresult", al);
            }
        }

        types = typeDAO.retrieveTypeList(schema, null, (String) session.getAttribute("user_key"));
    }

    model.addAttribute("records", types.size());
    model.addAttribute("estimatedrecords", types.size());

    UserPref userPref = (UserPref) session.getAttribute("prefs");

    if (types.size() <= userPref.getRecordsToDisplay()) {
        model.addAttribute("types", types);
    } else {
        if (request.getParameter("startAtIndex") != null) {
            startAtIndex = Integer.parseInt(request.getParameter("startAtIndex"));
        }

        if (request.getParameter("endAtIndex") != null) {
            endAtIndex = Integer.parseInt(request.getParameter("endAtIndex"));
            if (endAtIndex > types.size()) {
                endAtIndex = types.size();
            }
        } else {
            endAtIndex = userPref.getRecordsToDisplay();
        }

        List subList = types.subList(startAtIndex, endAtIndex);
        model.addAttribute("types", subList);
    }

    model.addAttribute("startAtIndex", startAtIndex);
    model.addAttribute("endAtIndex", endAtIndex);

    model.addAttribute("schemas", GemFireXDWebDAOUtil.getAllSchemas((String) session.getAttribute("user_key")));

    model.addAttribute("chosenSchema", schema);

    // This will resolve to /WEB-INF/jsp/types.jsp
    return "types";
}

From source file:com.indoqa.httpproxy.HttpClientProxy.java

private void writeResponseBody(InputStream responseBody, ServletOutputStream outputStream) throws IOException {
    try {/* w  w w  .ja  va  2  s  .  com*/
        byte[] buffer = new byte[STREAMCOPY_BUFFER_SIZE];
        int n;

        while ((n = responseBody.read(buffer)) > STREAMCOPY_EOF) {
            outputStream.write(buffer, 0, n);
        }
    } finally {
        responseBody.close();
        outputStream.close();
    }
}

From source file:com.yanbang.portal.controller.PortalController.java

/**
 * ???/*from   w ww. j av  a2 s .  com*/
 * 
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(params = "action=handleRnd")
public void handleRnd(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0L);
    response.setContentType("image/jpeg");
    BufferedImage image = new BufferedImage(65, 25, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();
    g.setColor(Color.GRAY);
    g.fillRect(0, 0, 65, 25);
    g.setColor(Color.yellow);
    Font font = new Font("", Font.BOLD, 20);
    g.setFont(font);
    Random r = new Random();
    String rnd = "";
    int ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 5, 18);
    g.setColor(Color.red);
    ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 20, 18);
    g.setColor(Color.blue);
    ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 35, 18);
    g.setColor(Color.green);
    ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 50, 18);
    request.getSession().setAttribute("RND", rnd);
    ServletOutputStream out = response.getOutputStream();
    out.write(ImageUtil.imageToBytes(image, "gif"));
    out.flush();
    out.close();
}