Example usage for javax.servlet ServletOutputStream write

List of usage examples for javax.servlet ServletOutputStream write

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream write.

Prototype

public abstract void write(int b) throws IOException;

Source Link

Document

Writes the specified byte to this output stream.

Usage

From source file:be.fedict.eid.applet.service.KmlServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");

    HttpSession httpSession = request.getSession();
    EIdData eIdData = (EIdData) httpSession.getAttribute("eid");

    byte[] document;
    try {//from w  w w  .  j  a  va  2s  .c  o m
        document = this.kmlGenerator.generateKml(eIdData);
    } catch (IOException e) {
        throw new ServletException("KML generator error: " + e.getMessage(), e);
    }

    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    if (false == request.getScheme().equals("https")) {
        // else the download fails in IE
        response.setHeader("Pragma", "no-cache"); // http 1.0
    } else {
        response.setHeader("Pragma", "public");
    }
    response.setDateHeader("Expires", -1);
    response.setHeader("Content-disposition", "attachment");
    response.setContentLength(document.length);

    response.setContentType(KmlLight.MIME_TYPE);
    response.setContentLength(document.length);
    ServletOutputStream out = response.getOutputStream();
    out.write(document);
    out.flush();
}

From source file:ru.ksu.niimm.cll.mocassin.frontend.server.PdfDownloadServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    String requestURI = req.getRequestURI();
    logger.info("The requested URI: {}", requestURI);
    String parameter = requestURI.substring(requestURI.lastIndexOf(ARXIVID_ENTRY) + ARXIVID_ENTRY_LENGTH);
    int signIndex = parameter.indexOf(StringUtil.ARXIVID_SEGMENTID_DELIMITER);
    String arxivId = signIndex != -1 ? parameter.substring(0, signIndex) : parameter;
    String segmentId = signIndex != -1 ? parameter.substring(signIndex + 1) : null;

    if (arxivId == null) {
        logger.error("The request with an empty arxiv id parameter");
        return;//from  w ww.  ja  v  a  2s .c o  m
    }
    String filePath = segmentId == null
            ? format("/opt/mocassin/aux-pdf/%s", StringUtil.arxivid2filename(arxivId, "pdf"))
            : "/opt/mocassin/pdf/" + StringUtil.segmentid2filename(arxivId, Integer.parseInt(segmentId), "pdf");
    if (!new File(filePath).exists()) {
        filePath = format("/opt/mocassin/aux-pdf/%s", StringUtil.arxivid2filename(arxivId, "pdf"));
    }
    try {
        FileInputStream fileInputStream = new FileInputStream(filePath);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        IOUtils.copy(fileInputStream, byteArrayOutputStream);
        resp.setContentType("application/pdf");
        resp.setHeader("Content-disposition",
                String.format("attachment; filename=%s", StringUtil.arxivid2filename(arxivId, "pdf")));
        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write(byteArrayOutputStream.toByteArray());
        outputStream.close();
    } catch (FileNotFoundException e) {
        logger.error("Error while downloading: PDF file= '{}' not found", filePath);
    } catch (IOException e) {
        logger.error("Error while downloading the PDF file", e);
    }
}

From source file:com.octo.captcha.module.acegi.JCaptchaSoundController.java

public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse response)
        throws Exception {
    byte[] captchaChallengeAsWav = null;

    ByteArrayOutputStream wavOutputStream = new ByteArrayOutputStream();

    //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();

    AudioInputStream challenge = soundCaptchaService.getSoundChallengeForID(captchaId,
            httpServletRequest.getLocale());

    // a jpeg encoder
    AudioInputStream stream = (AudioInputStream) challenge;

    // call the ImageCaptchaService method to retrieve a captcha
    AudioSystem.write(stream, AudioFileFormat.Type.WAVE, wavOutputStream);

    captchaChallengeAsWav = wavOutputStream.toByteArray();

    // configure cache  directives
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    //flush content in the response
    response.setContentType("audio/x-wav");
    ServletOutputStream responseOutputStream = response.getOutputStream();
    responseOutputStream.write(captchaChallengeAsWav);
    responseOutputStream.flush();//from www  . j ava  2s  .c  om
    responseOutputStream.close();
    return null;
}

From source file:de.fau.amos4.web.PrintDataController.java

@RequestMapping("/employee/download/text")
public ModelAndView EmployeeDownloadText(HttpServletResponse response,
        @RequestParam(value = "id", required = true) long employeeId) throws IOException {
    // Use the service to get the Employee in the LODAS format
    final String employeeAsLodas = employeeService.getLodasRepresentation(employeeId);

    if (employeeAsLodas == null) {
        return new ModelAndView("redirect:/client/dashboard");
    }/* www .  j a  v  a2  s  . co m*/

    // We want to have a txt file download
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition", "attachment;filename=employee_as_lodas.txt");
    response.setCharacterEncoding("UTF-8");

    // Write the data out
    ServletOutputStream out = response.getOutputStream();
    out.write(employeeAsLodas.getBytes());
    out.flush();
    out.close();
    return null;
}

From source file:de.knurt.fam.template.controller.letter.LetterGeneratorShowLetter.java

private void processIntern(HttpServletResponse response, PostMethod post, String customid) {
    //  forward response got
    //  force "save as" in browser
    String downloadFilename = this.df.format(new Date()) + "-" + customid + ".pdf";
    response.setHeader("Content-Disposition", "attachment; filename=" + downloadFilename);
    //  it is a pdf
    response.setContentType("application/pdf");
    try {//from w w  w . j  a  va 2s.  c om
        ServletOutputStream ouputStream = response.getOutputStream();
        ouputStream.write(post.getResponseBody());
        ouputStream.flush();
        ouputStream.close();
    } catch (IOException e) {
        FamLog.exception(e, 201106131408l);
    }
}

From source file:org.teiid.olingo.web.gzip.TestGzipMessageResponse.java

@Test
public void testWriteToOutputStream() throws Exception {
    ServletOutputStream sos = response.getOutputStream();
    sos.write(TEST_STRING.getBytes());
    sos.close();//w  w  w  . j a va2s.  com
    Assert.assertArrayEquals("Expected output in GZIP.", TEST_STRING_IN_GZIP,
            ArrayUtils.toPrimitive(streamBytes.toArray(new Byte[streamBytes.size()])));
}

From source file:ca.uhn.fhir.rest.server.servlet.ServletRestfulResponse.java

@Override
public Object sendAttachmentResponse(IBaseBinary bin, int stausCode, String contentType) throws IOException {
    addHeaders();//from w  ww  .  ja va2  s .  c  om
    HttpServletResponse theHttpResponse = getRequestDetails().getServletResponse();
    theHttpResponse.setStatus(stausCode);
    theHttpResponse.setContentType(contentType);
    if (bin.getContent() == null || bin.getContent().length == 0) {
        return null;
    } else {
        theHttpResponse.setContentLength(bin.getContent().length);
        ServletOutputStream oos = theHttpResponse.getOutputStream();
        oos.write(bin.getContent());
        oos.close();
        return null;
    }
}

From source file:com.google.appinventor.server.WebAppLaunchServlet.java

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

    String userId = userInfoProvider.getUserId();
    String launchFile;/*from w w w.  j  a  v a  2 s  .c o  m*/

    try {
        String uri = req.getRequestURI();
        // First, call split with no limit parameter.
        String[] uriComponents = uri.split("/");
        String launchKind = uriComponents[REQUEST_INDEX];

        if (launchKind.equals(ServerLayout.WEBAPP_FILE)) {
            uriComponents = uri.split("/", SPLIT_LIMIT_FILE);
            if (FILE_PATH_INDEX > uriComponents.length) {
                throw CrashReport.createAndLogError(LOG, req, null,
                        new IllegalArgumentException("Missing web app file path."));
            }
            String fileName = uriComponents[FILE_PATH_INDEX];
            launchFile = storageIo.downloadUserFile(userId, fileName, "UTF-8");

        } else {
            throw CrashReport.createAndLogError(LOG, req, null,
                    new IllegalArgumentException("Unknown launch kind: " + launchKind));
        }

    } catch (IllegalArgumentException e) {
        throw CrashReport.createAndLogError(LOG, req, null, e);
    }

    byte[] content = launchFile.getBytes();
    // Set http response information
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.setContentType("text/html");
    resp.setContentLength(launchFile.length());

    // Attach download data
    ServletOutputStream out = resp.getOutputStream();
    out.write(content);
    out.close();
}

From source file:com.tapas.evidence.fe.controller.CaptchaController.java

@RequestMapping("/captcha.jpg")
public void showForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
    byte[] captchaChallengeAsJpeg = null;
    // the output stream to render the captcha image as jpeg into
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {/*from   w w  w .  j av a  2  s  . c o m*/
        // 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());

        ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream);
    } catch (IllegalArgumentException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (CaptchaServiceException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        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 = response.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
}

From source file:org.fenixedu.parking.ui.Action.externalServices.ExportParkingData.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    final String password = request.getParameter("password");
    final String username = request.getParameter("username");
    checkPermissions(username, password);

    ParkingDataReportFile parkingDataReportFile = getLastParkingDataReportJob();
    if (parkingDataReportFile != null && parkingDataReportFile.getFile() != null) {
        final byte[] data = parkingDataReportFile.getFile().getContent();
        response.setContentLength(data.length);
        response.setContentType("application/vnd.ms-access");
        response.setHeader("Content-disposition",
                "attachment; filename=" + parkingDataReportFile.getFilename());
        final ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(data);
        outputStream.flush();/*from  w  w  w  .j  av  a2  s .  c o m*/
        outputStream.close();
    }
    return null;
}