Example usage for javax.servlet.http HttpServletResponse getOutputStream

List of usage examples for javax.servlet.http HttpServletResponse getOutputStream

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse getOutputStream.

Prototype

public ServletOutputStream getOutputStream() throws IOException;

Source Link

Document

Returns a ServletOutputStream suitable for writing binary data in the response.

Usage

From source file:ee.ria.xroad.proxy.testsuite.testcases.ServiceReturnsFault.java

@Override
public AbstractHandler getServiceHandler() {
    return new AbstractHandler() {
        @Override/*  ww  w. j  a v a 2  s  .  c  om*/
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException {
            response.setContentType(MimeTypes.TEXT_XML);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

            try (FileInputStream in = new FileInputStream(QUERIES_DIR + "/fault.query")) {
                IOUtils.copy(in, response.getOutputStream());
            }

            baseRequest.setHandled(true);
        }
    };
}

From source file:ke.co.tawi.babblesms.server.servlet.export.csv.ExportCsv.java

/**
 * Returns a zipped MS Excel file of the data specified for exporting.
 *
 * @param request// ww w . j av a  2s .  com
 * @param response
 * @throws ServletException, IOException
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ServletOutputStream out = response.getOutputStream();
    response.setContentType("application/zip");
    response.setHeader("Cache-Control", "cache, must-revalidate");
    response.setHeader("Pragma", "public");

    HttpSession session = request.getSession(false);
    Account account;
    String fileName;

    String exportExcelOption = request.getParameter("exportExcel");

    String sessionEmail = (String) session.getAttribute(SessionConstants.ACCOUNT_SIGN_IN_KEY);

    Element element = accountsCache.get(sessionEmail);
    account = (Account) element.getObjectValue();

    fileName = new StringBuffer(account.getUsername()).append(" ").append(SPREADSHEET_NAME).toString();

    response.setHeader("Content-Disposition",
            "attachment; filename=\"" + StringUtils.replace(fileName, ".xlsx", ".zip") + "\"");

    File excelFile = new File(FileUtils.getTempDirectoryPath() + File.separator + fileName);
    File csvFile = new File(StringUtils.replace(excelFile.getCanonicalPath(), ".xlsx", ".csv"));
    File zippedFile = new File(StringUtils.replace(excelFile.getCanonicalPath(), ".xlsx", ".zip"));

    // These are to determine whether or not we have created a CSV & Excel file on disk
    boolean successCSVFile = true, successExcelFile = true;

    if (StringUtils.equalsIgnoreCase(exportExcelOption, "Export All")) { //export all pages
        successCSVFile = dbFileUtils.sqlResultToCSV(getExportTopupsSqlQuery(account), csvFile.toString(), '|');

        if (successCSVFile) {
            successExcelFile = AllTopupsExportUtil.createExcelExport(csvFile.toString(), "|",
                    excelFile.toString());
        }

    } else if (StringUtils.equalsIgnoreCase(exportExcelOption, "Export Page")) { //export a single page

        InboxPage inboxPage = (InboxPage) session.getAttribute("currentInboxPage");

        successExcelFile = AllTopupsExportUtil.createExcelExport(inboxPage.getContents(), networkHash,
                networkHash, "|", excelFile.toString());

    } else { //export search results

        InboxPage topupPage = (InboxPage) session.getAttribute("currentSearchPage");

        successExcelFile = AllTopupsExportUtil.createExcelExport(topupPage.getContents(), networkHash,
                networkHash, "|", excelFile.toString());
    }

    if (successExcelFile) { // If we successfully created the MS Excel File on disk  
        // Zip the Excel file
        List<File> filesToZip = new ArrayList<>();
        filesToZip.add(excelFile);
        ZipUtil.compressFiles(filesToZip, zippedFile.toString());

        // Push the file to the request
        FileInputStream input = FileUtils.openInputStream(zippedFile);
        IOUtils.copy(input, out);
    }

    out.close();

    FileUtils.deleteQuietly(excelFile);
    FileUtils.deleteQuietly(csvFile);
    FileUtils.deleteQuietly(zippedFile);
}

From source file:org.magnum.dataup.MainController.java

public void serveSomeVideo(Video v, HttpServletResponse response) throws IOException {
    // Of course, you would need to send some headers, etc. to the
    // client too!
    //  ...//from w w w.jav a  2s. co  m
    response.setContentType("application/json");
    videoDataMgr.copyVideoData(v, response.getOutputStream());
}

From source file:com.meltmedia.cadmium.servlets.AbstractSecureRedirectStrategy.java

/**
 * Sends a moved perminately redirect to the secure form of the request URL.
 * //from w  w w  .  j  a v  a 2  s .co m
 * @request the request to make secure.
 * @response the response for the request.
 */
@Override
public void makeSecure(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.setHeader("Location", secureUrl(request, response));
    response.getOutputStream().flush();
    response.getOutputStream().close();
}

From source file:org.coursera.cmbrehm.kewlvideo.server.VideoController.java

@RequestMapping(value = "/video/{id}/data", method = RequestMethod.GET)
public void retrieveVideoData(@PathVariable("id") long id, HttpServletResponse response) {
    try {/*from   w  w w .j  a va2 s  .  c  o m*/
        VideoFileManager vfmgr = VideoFileManager.get();
        Video video = videoList.get(id);
        if (video != null && vfmgr.hasVideoData(video)) {
            OutputStream outStream = response.getOutputStream();
            response.setContentType(video.getContentType());
            vfmgr.copyVideoData(video, outStream);
        } else {
            response.setStatus(HttpStatus.NOT_FOUND.value());
        }
    } catch (IOException iox) {
        try {
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), iox.getMessage());
        } catch (Throwable t) {
        }
    }

}

From source file:org.attribyte.api.pubsub.impl.server.APIServlet.java

/**
 * Sends a JSON response./*from  w  ww  .j av a2 s .  c  o m*/
 * @param response The HTTP response.
 * @param responseNode The JSON node to send.
 * @throws IOException on write error.
 */
private void sendJSONResponse(HttpServletResponse response, ObjectNode responseNode) throws IOException {
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType(JSON_CONTENT_TYPE);
    response.getOutputStream().write(responseNode.toString().getBytes(Charsets.UTF_8));
}

From source file:HelloWorldServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String presentationtype = request.getParameter("presentationtype");
    Document document = new Document();
    try {//from   w  ww.  j  a v a2  s.com
        if ("rtf".equals(presentationtype)) {
            response.setContentType("text/rtf");
            RtfWriter2.getInstance(document, response.getOutputStream());
        }
        document.open();
        document.add(new Paragraph("Hello World"));
        document.add(new Paragraph(new Date().toString()));
    } catch (DocumentException de) {
        de.printStackTrace();
        System.err.println("document: " + de.getMessage());
    }
    document.close();
}

From source file:com.meltmedia.cadmium.servlets.AbstractSecureRedirectStrategy.java

/**
 * Sends a moved perminately redirect to the insecure form of the request URL.
 * //www .  ja va2 s. c om
 * @request the request to make secure.
 * @response the response for the request.
 */
@Override
public void makeInsecure(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.setHeader("Location", insecureUrl(request, response));
    response.getOutputStream().flush();
    response.getOutputStream().close();
}

From source file:org.endeavour.mgmt.controller.servlet.CreateProjectPlan.java

public void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse) throws IOException {
    try {/*from   ww  w .j ava 2s.  co  m*/

        Document theDocument = new Document(PageSize.A4.rotate());
        aResponse.setContentType("application/pdf");
        PdfWriter.getInstance(theDocument, aResponse.getOutputStream());
        theDocument.open();

        String theProjectIdValue = aRequest.getParameter(ProjectPlanMaintenance.PROJECT_ID);
        StringTokenizer theId = new StringTokenizer(theProjectIdValue, ":");
        Integer theProjectId = new Integer(theId.nextToken());
        ProjectPlanMaintenance thePlanMaintenance = new ProjectPlanMaintenance(null);
        List<IPlanElement> thePlanElements = thePlanMaintenance.getProjectPlanReportingData(theProjectId);

        Task theTask = null;
        IPlanElement thePlanElement = null;
        TaskSeries theSeries = new TaskSeries(SCHEDULED);
        int theDataSetIndex = 0;

        Date theStartDate = null;
        Date theEndDate = null;
        String theDescription = null;

        for (int i = 0; i < thePlanElements.size(); i++) {
            thePlanElement = thePlanElements.get(i);

            theTask = new Task(thePlanElement.getElementType() + " : " + thePlanElement.getName(),
                    thePlanElement.getStartDate(), thePlanElement.getEndDate());
            theTask.setPercentComplete(thePlanElement.getProgress() * 0.01);
            theSeries.add(theTask);

            if (i == 0) {
                theStartDate = thePlanElement.getStartDate();
                theEndDate = thePlanElement.getEndDate();
                theDescription = thePlanElement.getElementType() + " : " + thePlanElement.getName();
            }

            theDataSetIndex++;
            // Each page displays up to 25 tasks before creating a new one.
            if (theDataSetIndex == 25) {
                theDataSetIndex = 0;
                this.createReportPage(theDocument, theSeries, theStartDate, theEndDate, theDescription);
                theSeries = new TaskSeries(SCHEDULED);
            }
        }
        this.createReportPage(theDocument, theSeries, theStartDate, theEndDate, theDescription);

        theDocument.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.wisc.web.filter.ShallowEtagHeaderFilter.java

private void copyBodyToResponse(byte[] body, HttpServletResponse response) throws IOException {
    response.setContentLength(body.length);
    if (body.length > 0) {
        FileCopyUtils.copy(body, response.getOutputStream());
    }//from   w ww .jav  a 2 s . c om
}