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:com.hp.security.jauth.admin.controller.BaseController.java

@RequestMapping("login")
public void login(HttpServletRequest request, HttpServletResponse response)
        throws IOException, TemplateException {
    String error = null;/*  ww  w  . j a  va  2  s .  c om*/
    if (null != request.getAttribute("error")) {
        error = request.getAttribute("error").toString();
    }
    Map<String, Object> root = new HashMap<String, Object>();
    root.put("error", error);
    String view = freemarkerUtil.buildView(root, "login");
    response.setContentType("text/html");
    ServletOutputStream out = response.getOutputStream();
    out.write(view.getBytes());
    out.flush();
    out.close();
}

From source file:org.appverse.web.framework.backend.api.controllers.FileRetrievalController.java

private void processCall(HttpServletResponse response, Map<String, String> parameters) throws Exception {
    Object presentationService = applicationContext.getBean(serviceName.get());
    if (!(presentationService instanceof IFileRetrievalPresentationService)) {
        throw new IllegalArgumentException(
                "Requested Spring Bean is not a File Retrieval Presentation Service: (" + presentationService
                        + ")");
    }/*from  w w w.  ja  v  a2  s .co m*/

    FileVO fileVO = ((IFileRetrievalPresentationService) presentationService).retrievalFile(parameters);
    final ServletOutputStream output = response.getOutputStream();
    response.setContentType(fileVO.getMimeType());
    response.setHeader("Content-disposition", "attachment; filename=\"" + fileVO.getFilename() + "\"");
    output.write(fileVO.getBytes());
    output.close();

}

From source file:com.hp.security.jauth.admin.controller.BaseController.java

@RequestMapping("exception")
public void exception(HttpServletRequest request, HttpServletResponse response)
        throws IOException, TemplateException {
    Map<String, Object> root = new HashMap<String, Object>();
    String code = "";
    Exception ex = (Exception) request.getAttribute("ex");
    if (null != ex && ex instanceof AuthException) {
        AuthException aex = (AuthException) ex;
        code = aex.getCode();/* w w w .  j av  a  2  s  .  c om*/
    }
    root.put("code", code);
    root.put("ex", ex);
    String view = freemarkerUtil.buildView(root, "exception");
    response.setContentType("text/html");
    ServletOutputStream out = response.getOutputStream();
    out.write(view.getBytes());
    out.flush();
    out.close();
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.epfl.ExportPhdIndividualProgramProcessInformation.java

private void writeResponse(HttpServletResponse response, final byte[] presentationPage,
        final String contentType) throws IOException {
    final ServletOutputStream outputStream = response.getOutputStream();
    response.setContentType(contentType);
    outputStream.write(presentationPage);
    outputStream.close();
}

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

@RequestMapping(value = "/addlistener", method = RequestMethod.POST)
public String createListenerAction(@ModelAttribute("listenerAttribute") AddListener listenerAttribute,
        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 {/*  w w w.  j a  va  2 s . c o m*/
        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;
            }
        }

    }

    logger.debug("Received request to action an event for add listener");

    logger.debug("Listener ID = " + listenerAttribute.getId());

    // perform some action here with what we have
    String submit = request.getParameter("pSubmit");

    if (submit != null) {
        // build create HDFS Store SQL
        StringBuffer addListener = new StringBuffer();

        addListener.append("CALL SYS.ADD_LISTENER ('" + listenerAttribute.getId() + "', \n");
        addListener.append("'" + listenerAttribute.getSchemaName() + "', \n");
        addListener.append("'" + listenerAttribute.getTableName() + "', \n");
        addListener.append("'" + listenerAttribute.getFunctionName() + "', \n");

        if (!checkIfParameterEmpty(request, "initString")) {
            addListener.append("'" + listenerAttribute.getInitString() + "', \n");
        } else {
            addListener.append("'', \n");
        }

        if (!checkIfParameterEmpty(request, "serverGroups")) {
            addListener.append("'" + listenerAttribute.getServerGroups() + "')");
        } else {
            addListener.append("''), \n");
        }

        if (submit.equalsIgnoreCase("create")) {
            Result result = new Result();

            logger.debug("Creating Listener as -> " + addListener.toString());

            result = GemFireXDWebDAOUtil.runStoredCommand(addListener.toString(),
                    (String) session.getAttribute("user_key"));

            model.addAttribute("result", result);
            model.addAttribute("tableName", listenerAttribute.getTableName());

        } else if (submit.equalsIgnoreCase("Show SQL")) {
            logger.debug("Create Listener SQL as follows as -> " + addListener.toString());
            model.addAttribute("sql", addListener.toString());
            model.addAttribute("tableName", listenerAttribute.getTableName());
        } else if (submit.equalsIgnoreCase("Save to File")) {
            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + String.format(FILENAME, listenerAttribute.getId()));

            ServletOutputStream out = response.getOutputStream();
            out.println(addListener.toString());
            out.close();
            return null;
        }

    }

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

From source file:com.ningpai.common.util.CaptchaController.java

@RequestMapping("/captcha")
public void writeCaptcha(HttpServletRequest request, HttpServletResponse response) {
    byte[] captchaChallengeAsJpeg = null;
    // the output stream to render the captcha image as jpeg into
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {/*  ww  w.  ja va  2 s.  com*/
        // get the session id that will identify the generated captcha.
        // the same id must be used to validate the response, the session id is a good candidate!
        String captchaId = request.getSession().getId();
        BufferedImage challenge = captchaService.getImageChallengeForID(captchaId, request.getLocale());
        try {
            ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream);
        } catch (IOException e) {
        }
    } catch (IllegalArgumentException e) {
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (IOException e1) {
        }
        return;
    } catch (CaptchaServiceException e) {
        try {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (IOException e1) {
        }
        return;
    }

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // flush it in the response
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/" + CAPTCHA_IMAGE_FORMAT);

    ServletOutputStream responseOutputStream;
    try {
        responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    } catch (IOException e) {
    }

}

From source file:eu.annocultor.tagger.server.controllers.SolrTaggerController.java

@RequestMapping("/doc/**/*.*")
public void report(HttpServletRequest request, HttpServletResponse response) throws Exception {

    String path = merge(request.getServletPath(), request.getPathInfo());
    path = path.substring("/doc".length());
    response.setCharacterEncoding("UTF-8");
    ServletOutputStream outputStream = response.getOutputStream();
    try {/*from   w w w .  j  a  va2s  .c om*/
        IOUtils.copy(new FileInputStream(new File(fetchDoc(), path)), outputStream);
    } finally {
        outputStream.close();
    }
}

From source file:it.jugpadova.controllers.ServiceController.java

@RequestMapping
public ModelAndView kml(HttpServletRequest req, HttpServletResponse res) throws Exception {
    logger.info("Requested kml from " + req.getRemoteAddr());
    Document doc = jugBo.buildKml();
    res.setHeader("Cache-Control", "no-store");
    res.setHeader("Pragma", "no-cache");
    res.setDateHeader("Expires", 0);
    res.setContentType("text/xml");
    ServletOutputStream resOutputStream = res.getOutputStream();
    Serializer serializer = new Serializer(resOutputStream);
    serializer.setIndent(4);/*from  w  w w . j  ava2 s .  com*/
    serializer.setMaxLength(64);
    serializer.setLineSeparator("\n");
    serializer.write(doc);
    resOutputStream.flush();
    resOutputStream.close();
    return null;
}

From source file:org.red5.server.net.servlet.AMFGatewayServlet.java

/**
 * Sends response to client/*www . j  ava 2s  .com*/
 * @param resp             Response
 * @param packet           Remoting packet
 * @throws Exception       General exception
 */
protected void sendResponse(HttpServletResponse resp, RemotingPacket packet) throws Exception {
    ByteBuffer respBuffer = codecFactory.getSimpleEncoder().encode(null, packet);
    final ServletOutputStream out = resp.getOutputStream();
    resp.setContentLength(respBuffer.limit());
    ServletUtils.copy(respBuffer.asInputStream(), out);
    out.flush();
    out.close();
    respBuffer.release();
    respBuffer = null;
}

From source file:edu.umd.cs.submitServer.servlets.DownloadBestSubmissions.java

/**
 * The doGet method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to get.
 *
 * @param request/*from  www  .jav a2 s . c  om*/
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Connection conn = null;
    File tempfile = null;
    FileOutputStream fileOutputStream = null;
    FileInputStream fis = null;
    try {
        conn = getConnection();

        // get the project and all the student registrations
        Map<Integer, Submission> bestSubmissionMap = (Map<Integer, Submission>) request
                .getAttribute("bestSubmissionMap");

        Project project = (Project) request.getAttribute("project");
        Set<StudentRegistration> registrationSet = (Set<StudentRegistration>) request
                .getAttribute("studentRegistrationSet");

        // write everything to a tempfile, then send the tempfile
        tempfile = File.createTempFile("temp", "zipfile");
        fileOutputStream = new FileOutputStream(tempfile);

        // zip aggregator
        ZipFileAggregator zipAggregator = new ZipFileAggregator(fileOutputStream);

        for (StudentRegistration registration : registrationSet) {

            Submission submission = bestSubmissionMap.get(registration.getStudentRegistrationPK());
            if (submission != null) {
                try {
                    byte[] bytes = submission.downloadArchive(conn);
                    zipAggregator.addFileFromBytes(
                            registration.getClassAccount() + "-" + submission.getStatus() + "__"
                                    + submission.getSubmissionNumber(),
                            submission.getSubmissionTimestamp().getTime(), bytes);
                } catch (ZipFileAggregator.BadInputZipFileException ignore) {
                    // ignore, since students could submit things that
                    // aren't zipfiles
                    getSubmitServerServletLog().warn(ignore.getMessage(), ignore);
                }
            }
        }

        zipAggregator.close();

        // write the zipfile to the client
        response.setContentType("application/zip");
        response.setContentLength((int) tempfile.length());

        // take into account the inability of certain browsers to download
        // zipfiles
        String filename = "p" + project.getProjectNumber() + ".zip";
        Util.setAttachmentHeaders(response, filename);

        ServletOutputStream out = response.getOutputStream();
        fis = new FileInputStream(tempfile);

        IO.copyStream(fis, out);

        out.flush();
        out.close();
    } catch (SQLException e) {
        handleSQLException(e);
        throw new ServletException(e);
    } finally {
        releaseConnection(conn);
        if (tempfile != null && !tempfile.delete())
            getSubmitServerServletLog().warn("Unable to delete temporary file " + tempfile.getAbsolutePath());
        IOUtils.closeQuietly(fileOutputStream);
        IOUtils.closeQuietly(fis);
    }
}