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.galenframework.storage.controllers.api.PageApiController.java

private void initElementImages() {
    get("/api/projects/:projectName/pages/:pageName/objects/:elementName/images", (req, res) -> {
        String projectName = req.params("projectName");
        String pageName = req.params("projectName");
        String elementName = req.params("elementName");

        Long projectId = obtainProjectId(projectName);
        Optional<Page> page = pageRepository.findPage(projectId, pageName);
        if (page.isPresent()) {
            Optional<PageObject> pageObject = objectRepository.findObject(page.get().getPageId(), elementName);
            if (pageObject.isPresent()) {
                return objectRepository.findAllObjectImages(pageObject.get().getObjectId());
            }/*from   w  ww.j  av  a 2  s  . co  m*/
        }
        return emptyList();
    }, toJson());

    get("/api/projects/:projectName/pages/:pageName/objects/:elementName/images/:imageId", (req, res) -> {
        Long imageId = Long.parseLong(req.params("imageId"));
        Optional<ObjectImage> objectImage = objectRepository.findObjectImageById(imageId);
        if (objectImage.isPresent()) {
            byte[] imageBytes = fileStorage.readFile(objectImage.get().getImagePath());
            BufferedInputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(imageBytes));
            ServletOutputStream os = res.raw().getOutputStream();
            IOUtils.copy(inputStream, os);
            os.flush();
            os.close();
            return os;
        } else {
            throw new RuntimeException("Can't find image");
        }
    });
}

From source file:springapp.web.controller.theme.ResourceController.java

public ModelAndView handleRequest(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws Exception {
    String thisControllerUrl = httpServletResponse.encodeURL(httpServletRequest.getRequestURI());
    HttpSession session = httpServletRequest.getSession();

    ServletContext servletContext = session.getServletContext();
    WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    //String resourcesPath = (String)context.getBean("resourcesPath");

    ResourcesHolder currentSchema = (ResourcesHolder) session
            .getAttribute(ApplicationConstants.CURRENT_SCHEMA_ATTRIBUTE_NAME);

    String resourcesPath = currentSchema.getResourcesPath();
    String resourcePath = httpServletRequest.getParameter("resourcePath");
    boolean b = null != resourcePath;
    Integer hashCode = null;//from   w  ww . j ava  2  s .co  m
    if (b)
        try {
            hashCode = new Integer(Integer.parseInt(resourcePath));
        } catch (NumberFormatException e) {
            hashCode = new Integer(resourcePath.hashCode());
        }
    //ResourcesHolder resource = currentSchema.findResourceByPath(resourcePath);
    ResourcesHolder resource = currentSchema.findResourceByPathHashCode(hashCode);

    ResourcesLoader loader = loaderFactory.getResourcesLoader(resource, context);
    OutputStream outputStream = loader.outForWeb(resource, thisControllerUrl, resourcesPath);

    if (outputStream instanceof ByteArrayOutputStream) {
        ByteArrayOutputStream byteArrayOutputStream = (ByteArrayOutputStream) outputStream;
        if (resource instanceof CSSHolderImpl)
            httpServletResponse.setContentType("text/css");
        else if (resource instanceof GIFHolderImpl)
            httpServletResponse.setContentType("image/gif");
        else if (resource instanceof PNGHolderImpl)
            httpServletResponse.setContentType("image/png");

        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setHeader("Cache-Control", "no-cache");
        httpServletResponse.setHeader("Expires", "-1");
        httpServletResponse.setContentLength(byteArrayOutputStream.size());

        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        byteArrayOutputStream.writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();
    }
    logger.info("ResourceController ! ");

    return null;
}

From source file:net.gplatform.sudoor.server.captcha.model.CaptchaEngine.java

public void renderCapcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // Set to expire far in the past.
    response.setDateHeader("Expires", 0);
    // Set standard HTTP/1.1 no-cache headers.
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    // Set standard HTTP/1.0 no-cache header.
    response.setHeader("Pragma", "no-cache");

    // return a jpeg
    response.setContentType("image/jpeg");

    // create the text for the image
    String capText = captchaProducer.createText();

    // store the text in the session
    request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
    logger.debug("Save Captcha: {} in Session:{}", capText, request.getSession().getId());

    // create the image with the text
    BufferedImage bi = captchaProducer.createImage(capText);

    ServletOutputStream out = response.getOutputStream();

    // write the data out
    ImageIO.write(bi, "jpg", out);
    try {//from ww w .  j  a v a  2  s.c  o m
        out.flush();
    } finally {
        out.close();
    }
}

From source file:io.logspace.hq.rest.EventStreamResource.java

private Object postEventStream(Request req, Response res) throws IOException {
    EventFilter eventFilter = this.readFilter(req.body());
    int offset = getQueryParam(req, PARAMETER_OFFSET, DEFAULT_STREAM_OFFSET, MIN_OFFSET, MAX_OFFSET);
    int count = getQueryParam(req, PARAMETER_COUNT, DEFAULT_COUNT, MIN_COUNT, MAX_STREAM_COUNT);

    res.raw().setContentType("application/json;charset=UTF-8");

    ServletOutputStream outputStream = res.raw().getOutputStream();
    outputStream.print('[');
    this.eventService.stream(eventFilter, count, offset, new JsonEventStreamer(outputStream));
    outputStream.print(']');
    outputStream.close();

    return "";
}

From source file:org.efs.openreports.actions.JXLSReportAction.java

public String execute() {
    ReportUser user = (ReportUser) ActionContext.getContext().getSession().get(ORStatics.REPORT_USER);

    report = (Report) ActionContext.getContext().getSession().get(ORStatics.REPORT);

    Map parameters = getReportParameterMap(user);

    ReportLog reportLog = new ReportLog(user, report, new Date());

    Connection conn = null;/*  ww w  . j av a 2 s. c  o  m*/

    try {
        log.debug("Starting JXLS Report: " + report.getName());

        reportLogProvider.insertReportLog(reportLog);

        ReportEngineInput input = new ReportEngineInput(report, parameters);

        JXLSReportEngine reportEngine = new JXLSReportEngine(dataSourceProvider, directoryProvider,
                propertiesProvider);

        ReportEngineOutput output = reportEngine.generateReport(input);

        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition",
                "inline; filename=" + StringUtils.deleteWhitespace(report.getName()) + ".xls");

        ServletOutputStream out = response.getOutputStream();

        out.write(output.getContent(), 0, output.getContent().length);

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

        reportLog.setEndTime(new Date());
        reportLog.setStatus(ReportLog.STATUS_SUCCESS);
        reportLogProvider.updateReportLog(reportLog);

        log.debug("Finished JRXLS Report: " + report.getName());
    } catch (Exception e) {
        addActionError(e.getMessage());

        log.error(e.getMessage());

        reportLog.setMessage(e.getMessage());
        reportLog.setStatus(ReportLog.STATUS_FAILURE);

        reportLog.setEndTime(new Date());

        try {
            reportLogProvider.updateReportLog(reportLog);
        } catch (Exception ex) {
            log.error("Unable to create ReportLog: " + ex.getMessage());
        }

        return ERROR;
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception c) {
            log.error("Error closing");
        }
    }

    return NONE;
}

From source file:org.b5chat.crossfire.web.FaviconServlet.java

/**
 * Writes out a <code>byte</code> to the ServletOuputStream.
 *
 * @param bytes the bytes to write to the <code>ServletOutputStream</code>.
 *//* w  w w . j  a va  2s. co m*/
private void writeBytesToStream(byte[] bytes, HttpServletResponse response) {
    response.setContentType(CONTENT_TYPE);

    // Send image
    try {
        ServletOutputStream sos = response.getOutputStream();
        sos.write(bytes);
        sos.flush();
        sos.close();
    } catch (IOException e) {
        // Do nothing
    }
}

From source file:org.efs.openreports.actions.ReportViewerAction.java

public String execute() {
    JasperPrint jasperPrint = (JasperPrint) ActionContext.getContext().getSession().get(ORStatics.JASPERPRINT);

    report = (Report) ActionContext.getContext().getSession().get(ORStatics.REPORT);

    if (jasperPrint != null && jasperPrint.getPages() != null) {
        pageCount = jasperPrint.getPages().size();
    }/* w  w w.j av a 2 s .co m*/

    if (!"image".equals(submitType))
        return SUCCESS;

    byte[] imageData = null;

    if (jasperPrint != null) {
        try {
            BufferedImage image = (BufferedImage) JasperPrintManager.printPageToImage(jasperPrint,
                    pageIndex - 1, zoom);
            imageData = new SunPNGEncoderAdapter().encode(image);
        } catch (Exception e) {
            addActionError(e.getMessage());
            log.error(e.toString());
        }
    }

    if (imageData != null) {

        HttpServletResponse response = ServletActionContext.getResponse();

        try {
            response.setContentLength(imageData.length);
            ServletOutputStream ouputStream = response.getOutputStream();
            ouputStream.write(imageData, 0, imageData.length);
            ouputStream.flush();
            ouputStream.close();
        } catch (IOException ioe) {
            log.warn(ioe.toString());
        }
    }

    return NONE;
}

From source file:com.seer.datacruncher.spring.ValidateFilePopupController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String idSchema = request.getParameter("idSchema");
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("file");
    String resMsg = "";

    if (multipartFile.getOriginalFilename().endsWith(FileExtensionType.ZIP.getAbbreviation())) {
        // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one      
        ZipInputStream inStream = null;
        try {//from  www.  ja va 2  s . c  o  m
            inStream = new ZipInputStream(multipartFile.getInputStream());
            ZipEntry entry;
            while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    DatastreamsInput datastreamsInput = new DatastreamsInput();
                    datastreamsInput.setUploadedFileName(entry.getName());
                    byte[] byteInput = IOUtils.toByteArray(inStream);
                    resMsg += datastreamsInput.datastreamsInput(new String(byteInput), Long.parseLong(idSchema),
                            byteInput);
                }
                inStream.closeEntry();
            }
        } catch (IOException ex) {
            resMsg = "Error occured during fetch records from ZIP file.";
        } finally {
            if (inStream != null)
                inStream.close();
        }
    } else {
        // Case 1: When user upload a single file. In this cae just validate a single stream 
        String datastream = new String(multipartFile.getBytes());
        DatastreamsInput datastreamsInput = new DatastreamsInput();
        datastreamsInput.setUploadedFileName(multipartFile.getOriginalFilename());

        resMsg = datastreamsInput.datastreamsInput(datastream, Long.parseLong(idSchema),
                multipartFile.getBytes());

    }
    String msg = resMsg.replaceAll("'", "\"").replaceAll("\\n", " ");
    msg = msg.trim();
    response.setContentType("text/html");
    ServletOutputStream out = null;
    out = response.getOutputStream();
    out.write(("{success: " + true + " , message:'" + msg + "',   " + "}").getBytes());
    out.flush();
    out.close();
    return null;
}

From source file:io.logspace.hq.rest.event.EventStreamResource.java

private Object postEventStream(Request req, Response res) throws IOException {
    EventFilter eventFilter = this.readFilter(req.body());
    int offset = getQueryParam(req, PARAMETER_OFFSET, DEFAULT_STREAM_OFFSET, MIN_OFFSET, MAX_OFFSET);
    int count = getQueryParam(req, PARAMETER_COUNT, DEFAULT_COUNT, MIN_COUNT, MAX_STREAM_COUNT);

    res.raw().setContentType("application/json;charset=UTF-8");

    ServletOutputStream outputStream = res.raw().getOutputStream();
    outputStream.print('[');
    this.eventStreamService.stream(eventFilter, count, offset, new JsonEventStreamer(outputStream));
    outputStream.print(']');
    outputStream.close();

    return "";
}

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

@RequestMapping(value = "/addloader", method = RequestMethod.POST)
public String createLoaderAction(@ModelAttribute("loaderAttribute") AddLoader loaderAttribute, 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 ww. ja v a 2  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;
            }
        }

    }

    logger.debug("Received request to action an event for Table Loader");

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

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

        addLoader.append("CALL SYS.ATTACH_LOADER ('" + loaderAttribute.getSchemaName() + "', \n");
        addLoader.append("'" + loaderAttribute.getTableName() + "', \n");
        addLoader.append("'" + loaderAttribute.getFunctionName() + "', \n");

        if (!checkIfParameterEmpty(request, "initInfoString")) {
            addLoader.append("'" + loaderAttribute.getInitInfoString() + "') \n");
        } else {
            addLoader.append("NULL) \n");
        }

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

            logger.debug("Creating Table Loader as -> " + addLoader.toString());

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

            model.addAttribute("result", result);

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

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

    }

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