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.seer.datacruncher.spring.SchemasUpdateController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String json = request.getReader().readLine();
    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    SchemaEntity schemaEntity = mapper.readValue(json, SchemaEntity.class);

    if (schemaEntity.getIdDatabase() > 0) {
        schemaEntity.setPublishToDb(true);
    }// w w  w  .  j a  v a 2  s. co m
    if (schemaEntity.getIdValidationDatabase() > 0) {
        schemaEntity.setInputToDb(true);
    }

    SchemaTriggerStatusEntity newSchemaTriggerStatusEntity = schemaEntity.getSchemaEvents();
    Create createTrigger = new Create();
    createTrigger.setSuccess(true);
    createTrigger.setMessage("");
    Update update;

    ReadList readTriggersList = schemaTriggerStatusDao.findByIdSchema(schemaEntity.getIdSchema());
    if (CollectionUtils.isNotEmpty(readTriggersList.getResults())) {
        if (schemaEntity.getIsEventTrigger()) {
            SchemaTriggerStatusEntity schemaTriggerStatusEntity = (SchemaTriggerStatusEntity) readTriggersList
                    .getResults().get(0);
            if (schemaTriggerStatusEntity.getIdEventTrigger() != newSchemaTriggerStatusEntity
                    .getIdEventTrigger()
                    || schemaTriggerStatusEntity.getIdStatus() != newSchemaTriggerStatusEntity.getIdStatus()) {
                schemaTriggerStatusEntity.setIdEventTrigger(newSchemaTriggerStatusEntity.getIdEventTrigger());
                schemaTriggerStatusEntity.setIdStatus(newSchemaTriggerStatusEntity.getIdStatus());
                update = schemaTriggerStatusDao.update(schemaTriggerStatusEntity);
                if (update.isSuccess()) {
                    schemaEntity.setSchemaEvents(schemaTriggerStatusEntity);
                } else {
                    createTrigger.setSuccess(false);
                    createTrigger.setMessage("Event update error:" + update.getMessage());
                }
            }

        } else {
            Destroy destroy = schemaTriggerStatusDao.destroyEventsBySchema(schemaEntity.getIdSchema());
            if (!destroy.isSuccess()) {
                createTrigger.setSuccess(false);
                createTrigger.setMessage("Event delete error:" + destroy.getMessage());
            }
        }
    } else {
        if (schemaEntity.getIsEventTrigger()) {
            newSchemaTriggerStatusEntity.setIdSchema(schemaEntity.getIdSchema());
            createTrigger = schemaTriggerStatusDao.create(newSchemaTriggerStatusEntity);
            if (createTrigger.getSuccess())
                schemaEntity.setSchemaEvents(newSchemaTriggerStatusEntity);
        }
    }

    if (createTrigger.getSuccess()) {
        update = schemasDao.update(schemaEntity);
    } else {
        update = new Update();
        update.setSuccess(createTrigger.getSuccess());
        update.setMessage("Event " + createTrigger.getMessage());
    }

    response.setContentType("application/json");
    ServletOutputStream out = response.getOutputStream();
    out.write(mapper.writeValueAsBytes(update));
    out.flush();
    out.close();
    return null;
}

From source file:com.octo.captcha.module.struts.image.RenderImageCaptchaAction.java

public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

    ImageCaptchaService service = (ImageCaptchaService) CaptchaServicePlugin.getInstance().getService();
    String captchaID = CaptchaModuleConfigHelper.getId(httpServletRequest);
    //(String) theRequest.getParameter(captchaIDParameterName);

    // call the ManageableImageCaptchaService methods
    byte[] captchaChallengeAsJpeg = null;
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {//  ww w .  java  2s.c o m
        BufferedImage challenge = service.getImageChallengeForID(captchaID, httpServletRequest.getLocale());
        // the output stream to render the captcha image as jpeg into

        // a jpeg encoder
        JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
        jpegEncoder.encode(challenge);
    } catch (IllegalArgumentException e) {
        // log a security warning and return a 404...
        if (log.isWarnEnabled()) {
            log.warn("There was a try from " + httpServletRequest.getRemoteAddr()
                    + " to render an URL without ID" + " or with a too long one");
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            log.error("should never pass here!");
            return actionMapping.findForward("error");
        }
    } catch (CaptchaServiceException e) {
        // log and return a 404 instead of an image...
        log.warn("Error trying to generate a captcha and " + "render its challenge as JPEG", e);
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        // log.error("should never pass here!");
        return actionMapping.findForward("error");
    }

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // render the captcha challenge as a JPEG image in the response
    httpServletResponse.setHeader("Cache-Control", "no-store");
    httpServletResponse.setHeader("Pragma", "no-cache");
    httpServletResponse.setDateHeader("Expires", 0);
    httpServletResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
    // log.error("should never pass here!");
    return null;
}

From source file:org.efs.openreports.actions.admin.DataExportAction.java

public String execute() {
    try {//from   w  w w.  ja  v a2 s.  co  m
        if (!submitOk) {
            reports = reportProvider.getReports();
            return SUCCESS;
        }

        XStream xStream = new XStream();
        xStream.omitField(BasicDataSource.class, "logWriter");
        xStream.omitField(Report.class, "id");
        xStream.omitField(ReportAlert.class, "id");
        xStream.omitField(ReportChart.class, "id");
        xStream.omitField(ReportParameter.class, "id");
        xStream.omitField(ReportExportOption.class, "id");

        List<Report> selectedReports = new ArrayList<Report>();

        for (int i = 0; i < reportIds.length; i++) {
            Report report = reportProvider.getReport(new Integer(reportIds[i]));
            selectedReports.add(report);
        }

        HttpServletResponse response = ServletActionContext.getResponse();
        response.setHeader("Content-disposition", "inline; filename=or-report-export.xml");
        response.setContentType("application/xml");

        ServletOutputStream outputStream = response.getOutputStream();

        xStream.toXML(selectedReports, outputStream);

        outputStream.flush();
        outputStream.close();

        return NONE;
    } catch (Exception e) {
        addActionError(e.toString());
        return INPUT;
    }
}

From source file:hudson.util.Graph.java

/**
 * Renders a graph.//from  w  ww . j  a  va  2 s.  co  m
 */
public void doPng(StaplerRequest req, StaplerResponse rsp) throws IOException {
    if (req.checkIfModified(timestamp, rsp))
        return;

    try {
        BufferedImage image = render(req, null);
        rsp.setContentType("image/png");
        ServletOutputStream os = rsp.getOutputStream();
        ImageIO.write(image, "PNG", os);
        os.close();
    } catch (Error e) {
        /* OpenJDK on ARM produces an error like this in case of headless error
        Caused by: java.lang.Error: Probable fatal error:No fonts found.
                at sun.font.FontManager.getDefaultPhysicalFont(FontManager.java:1088)
                at sun.font.FontManager.initialiseDeferredFont(FontManager.java:967)
                at sun.font.CompositeFont.doDeferredInitialisation(CompositeFont.java:254)
                at sun.font.CompositeFont.getSlotFont(CompositeFont.java:334)
                at sun.font.CompositeStrike.getStrikeForSlot(CompositeStrike.java:77)
                at sun.font.CompositeStrike.getFontMetrics(CompositeStrike.java:93)
                at sun.font.Font2D.getFontMetrics(Font2D.java:387)
                at java.awt.Font.defaultLineMetrics(Font.java:2082)
                at java.awt.Font.getLineMetrics(Font.java:2152)
                at org.jfree.chart.axis.NumberAxis.estimateMaximumTickLabelHeight(NumberAxis.java:974)
                at org.jfree.chart.axis.NumberAxis.selectVerticalAutoTickUnit(NumberAxis.java:1104)
                at org.jfree.chart.axis.NumberAxis.selectAutoTickUnit(NumberAxis.java:1048)
                at org.jfree.chart.axis.NumberAxis.refreshTicksVertical(NumberAxis.java:1249)
                at org.jfree.chart.axis.NumberAxis.refreshTicks(NumberAxis.java:1149)
                at org.jfree.chart.axis.ValueAxis.reserveSpace(ValueAxis.java:788)
                at org.jfree.chart.plot.CategoryPlot.calculateRangeAxisSpace(CategoryPlot.java:2650)
                at org.jfree.chart.plot.CategoryPlot.calculateAxisSpace(CategoryPlot.java:2669)
                at org.jfree.chart.plot.CategoryPlot.draw(CategoryPlot.java:2716)
                at org.jfree.chart.JFreeChart.draw(JFreeChart.java:1222)
                at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1396)
                at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1376)
                at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1361)
                at hudson.util.ChartUtil.generateGraph(ChartUtil.java:116)
                at hudson.util.ChartUtil.generateGraph(ChartUtil.java:99)
                at hudson.tasks.test.AbstractTestResultAction.doPng(AbstractTestResultAction.java:196)
                at hudson.tasks.test.TestResultProjectAction.doTrend(TestResultProjectAction.java:97)
                ... 37 more
         */
        if (e.getMessage().contains("Probable fatal error:No fonts found")) {
            rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
            return;
        }
        throw e; // otherwise let the caller deal with it
    } catch (HeadlessException e) {
        // not available. send out error message
        rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
    }
}

From source file:org.shept.services.jcaptcha.ImageCaptchaServlet.java

@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {
    BufferedImage challenge = null;
    try {//from   www  .  j a  v  a2  s.  c  om
        // 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 = httpServletRequest.getSession().getId();

        // If we have an explicit configuration for an ImageService we use this
        // else we use the predefined default
        ImageCaptchaService captchaService = CaptchaServiceSingleton.getInstance();
        Map services = ctx.getBeansOfType(ImageCaptchaService.class);
        // there must be exactly on service configured
        if (services.size() == 1) {
            for (Iterator iterator = services.values().iterator(); iterator.hasNext();) {
                captchaService = (ImageCaptchaService) iterator.next();
            }
        }

        // call the ImageCaptchaService getChallenge method
        challenge = captchaService.getImageChallengeForID(captchaId, httpServletRequest.getLocale());

    } catch (IllegalArgumentException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (CaptchaServiceException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    // flush it in the response
    httpServletResponse.setHeader("Cache-Control", "no-store");
    httpServletResponse.setHeader("Pragma", "no-cache");
    httpServletResponse.setDateHeader("Expires", 0);
    httpServletResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
    ImageIO.write(challenge, "jpeg", responseOutputStream);
    responseOutputStream.flush();
    responseOutputStream.close();
}

From source file:com.jaspersoft.jasperserver.war.themes.ThemeResolverServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // Check if we can find a resource in the current theme
    //String resPath = req.getRequestURI().substring((req.getContextPath() + req.getServletPath()).length());
    String resPath = req.getRequestURI().substring(req.getContextPath().length() + 1);
    ThemeResource themeResource = themeCache.getThemeResource(resPath);
    if (themeResource == null) {
        resp.sendError(404);/*from   www . ja v a  2 s.  co m*/
        return;
    }

    // Set contentType
    String filename = resPath;
    if (filename.indexOf("/") >= 0) {
        filename = filename.substring(filename.lastIndexOf("/") + 1);
    }
    String contentType = servletContext.getMimeType(filename);
    if (contentType == null) {
        log.error("Cannot detect a response content type for the file : " + filename);
        resp.sendError(404);
        return;
    }
    resp.setContentType(contentType);

    // Get Last Modified date
    Date lastModified = themeResource.getLastModified();
    // Get rid of ms
    lastModified.setTime(lastModified.getTime() / 1000 * 1000);

    // Set cache controlling HTTP Response Headers
    DateFormat df = getFormat(req.getLocale());
    resp.setHeader("Cache-Control", "max-age=" + expiresInSecs + ", public");
    resp.setHeader("Pragma", "");
    resp.setHeader("Last-Modified", df.format(lastModified));
    resp.setHeader("Expires", df.format(new Date(new Date().getTime() + expiresInSecs * 1000)));

    // Send 304 if resource has not been modified since last time requested
    String ifModSince = req.getHeader("If-Modified-Since");
    try {
        Date modDate = df.parse(ifModSince);
        if (!lastModified.after(modDate)) {
            resp.setStatus(304);
            return;
        }
    } catch (Exception e) {
    }

    // Send the full content
    resp.setContentLength(themeResource.getContent().length);
    ServletOutputStream os = resp.getOutputStream();
    os.write(themeResource.getContent());
    os.flush();
    os.close();
}

From source file:sf.net.experimaestro.server.JsonRPCServlet.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    try {/*w w w .j  av a2 s.  co  m*/
        ServletInputStream inputStream = req.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream);

        JSONParser parser = new JSONParser();
        JsonStreamHandler handler = new JsonStreamHandler(new JsonCallHandler(req, resp));

        try {
            parser.parse(reader, handler, true);
        } catch (ParseException e) {
            LOGGER.error(e);
        }

    } finally {
        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.flush();
        outputStream.close();

    }
}

From source file:be.fedict.eid.pkira.blm.model.reporting.ReportConfigurationHandler.java

public void generateReport() {
    if (StringUtils.isBlank(startMonth) || StringUtils.isBlank(endMonth)) {
        return;/* www . java 2 s  .c  o  m*/
    }

    if (startMonth.compareTo(endMonth) > 0) {
        facesMessages.addFromResourceBundle(Severity.ERROR, "reports.startAfterEnd");
        return;
    }

    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
    response.setContentType("test/xml");
    String fileName = (StringUtils.equals(startMonth, endMonth) ? startMonth : startMonth + " - " + endMonth)
            + ".xml\"";
    response.addHeader("Content-disposition", "attachment; filename=\"" + fileName);

    String report = reportManager.generateReport(startMonth, endMonth, includeCertificateAuthorityReport,
            includeCertificateDomainReport);

    try {
        ServletOutputStream servletOutputStream = response.getOutputStream();
        servletOutputStream.write(report.getBytes());
        servletOutputStream.flush();
        servletOutputStream.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    facesContext.responseComplete();
}

From source file:org.efs.openreports.dispatcher.FileDispatcher.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String fileName = "";

    try {//from  w ww  .j  a v  a2  s  .co  m
        fileName = StringUtils.substringAfterLast(request.getRequestURI(), "/");

        File file = new File(imageDirectory + fileName);
        if (!file.exists()) {
            file = new File(imageTempDirectory + fileName);
        }
        if (!file.exists()) {
            fileName = request.getParameter("fileName");

            // report file delivery validates the filename against the username 
            // of the user in session for security purposes.
            ReportUser user = (ReportUser) request.getSession().getAttribute(ORStatics.REPORT_USER);
            if (user == null || fileName.indexOf(user.getName()) < 0) {
                String message = "Not Authorized...";
                response.getOutputStream().write(message.getBytes());

                return;
            }

            file = new File(reportGenerationDirectory + fileName);
        }

        byte[] fileDate = FileUtils.readFileToByteArray(file);

        response.setContentLength(fileDate.length);
        ServletOutputStream ouputStream = response.getOutputStream();

        ouputStream.write(fileDate, 0, fileDate.length);
        ouputStream.flush();
        ouputStream.close();
    } catch (Exception e) {
        log.warn(e);

        String message = "Error Loading File...";
        response.getOutputStream().write(message.getBytes());
    }
}

From source file:com.buession.cas.web.controller.CaptchaController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    response.setContentType("image/jpg");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.setDateHeader("Expires", 0);

    String text = producer.createText();
    captchaService.add(request, text);// ww  w. j a  v a2s  .c o m

    BufferedImage im = producer.createImage(text);
    ServletOutputStream out = response.getOutputStream();
    ImageIO.write(im, "jpg", out);

    try {
        out.flush();
    } finally {
        out.close();
    }

    return null;
}