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:MyServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    Locale locale;//from  w w  w.  j  a  v  a  2  s  .  c  o  m
    DateFormat full;

    try {
        res.setContentType("text/plain; charset=UTF-8");
        //PrintWriter out = res.getWriter();
        PrintWriter out = new PrintWriter(new OutputStreamWriter(res.getOutputStream(), "UTF8"), true);

        locale = new Locale("en", "US");
        full = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        out.println("In English appropriate for the US:");
        out.println("Hello World!");
        out.println(full.format(new Date()));
        out.println();

        locale = new Locale("es", "");
        full = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        out.println("En Espa\u00f1ol:");
        out.println("\u00a1Hola Mundo!");
        out.println(full.format(new Date()));
        out.println();

        locale = new Locale("ja", "");
        full = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        out.println("In Japanese:");
        out.println("\u4eca\u65e5\u306f\u4e16\u754c");
        out.println(full.format(new Date()));
        out.println();

        locale = new Locale("zh", "");
        full = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        out.println("In Chinese:");
        out.println("\u4f60\u597d\u4e16\u754c");
        out.println(full.format(new Date()));
        out.println();

        locale = new Locale("ko", "");
        full = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        out.println("In Korean:");
        out.println("\uc548\ub155\ud558\uc138\uc694\uc138\uacc4");
        out.println(full.format(new Date()));
        out.println();

        locale = new Locale("ru", "");
        full = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        out.println("In Russian (Cyrillic):");
        out.print("\u0417\u0434\u0440\u0430\u0432\u0441\u0442");
        out.println("\u0432\u0443\u0439, \u041c\u0438\u0440");
        out.println(full.format(new Date()));
        out.println();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.springside.modules.security.jcaptcha.JCaptchaFilter.java

/**
 * ???.//ww w.  ja v  a 2s .  c  o m
 */
protected void genernateCaptchaImage(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {

    ServletUtils.setDisableCacheHeader(response);
    response.setContentType("image/jpeg");

    ServletOutputStream out = response.getOutputStream();
    try {
        String captchaId = request.getSession(true).getId();
        BufferedImage challenge = (BufferedImage) captchaService.getChallengeForID(captchaId,
                request.getLocale());
        ImageIO.write(challenge, "jpg", out);
        out.flush();
    } catch (CaptchaServiceException e) {
        logger.error(e.getMessage(), e);
    } finally {
        out.close();
    }
}

From source file:com.gsr.myschool.server.reporting.convocation.ConvocationController.java

@RequestMapping(value = "test", method = RequestMethod.GET, produces = "application/pdf")
@ResponseStatus(HttpStatus.OK)//  ww w .  j  av a2  s. c om
public void generateReportTest(@RequestParam String niveauId, @RequestParam String sessionId,
        HttpServletResponse response) {
    ReportDTO dto = convocationService.generateConvocationTest(Long.valueOf(niveauId), Long.valueOf(sessionId));
    try {
        response.addHeader("Content-Disposition", "attachment; filename=convocation.pdf");

        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        byte[] result = reportService.generatePdf(dto);

        outputStream.write(result, 0, result.length);
        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:de.iew.raspimotion.controllers.MotionJpegController.java

@RequestMapping(value = "stream/{imagename:.+}")
public void streamAction(HttpServletResponse response, @PathVariable String imagename) throws Exception {
    Assert.isTrue(validateImagename(imagename));

    OutputStream out = response.getOutputStream();
    try {//from  w w w. j a v a2s.  co m
        FileDescriptor file = this.fileDao.getFileLastCreated(imagename);

        if (file == null) {
            throw new NoSuchElementException("Image was not found");
        }

        sendCachingHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("multipart/x-mixed-replace;boundary=BOUNDARY");

        writeFrameBoundary(out);
        writeFrame(out, file);

        long processingTime;
        long startTs;

        double fpsTime = 1000 / this.fps;
        long sleepTime;

        while (true) {
            startTs = System.currentTimeMillis();
            file = this.fileDao.getFileLastCreated(imagename);

            writeFrame(out, file);

            processingTime = System.currentTimeMillis() - startTs;

            if (log.isDebugEnabled()) {
                log.debug("Zeitdauer fr gesamten Vorgang: " + processingTime);
            }

            sleepTime = (long) (fpsTime - processingTime);

            if (log.isDebugEnabled()) {
                log.debug("Schlafe " + sleepTime);
            }

            if (sleepTime > 0) {
                Thread.sleep(sleepTime);
            }
        }
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Motion JPEG handling aborted", e);
        }
        try {
            out.flush();
            out.close();
        } catch (Exception ex) {
            if (log.isDebugEnabled()) {
                log.debug("Closing failed", ex);
            }
        }
    }
}

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

@RequestMapping(value = VIDEO_DATA_PATH, method = RequestMethod.GET)
public void getData(@PathVariable(ID_PARAMETER) long id, HttpServletResponse response) throws IOException {
    VideoFileManager videoDataMgr = VideoFileManager.get();
    Video v = getVideoById(id);//from   ww  w  . ja va  2s.  c o  m

    if (v != null) {
        if (videoDataMgr.hasVideoData(v)) {
            videoDataMgr.copyVideoData(v, response.getOutputStream());
        }
    } else {
        response.setStatus(404);
    }
}

From source file:org.openxdata.designer.server.FileOpenServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", -1);
    response.setHeader("Cache-Control", "no-store");

    response.setContentType("text/xml; charset=utf-8");
    response.getOutputStream().print((String) request.getSession().getAttribute(KEY_FILE_CONTENTS));
}

From source file:org.eclipse.jgit.lfs.server.LfsProtocolServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    Writer w = new BufferedWriter(new OutputStreamWriter(res.getOutputStream(), UTF_8));

    Reader r = new BufferedReader(new InputStreamReader(req.getInputStream(), UTF_8));
    LfsRequest request = gson.fromJson(r, LfsRequest.class);
    String path = req.getPathInfo();

    res.setContentType(CONTENTTYPE_VND_GIT_LFS_JSON);
    LargeFileRepository repo = null;/*  w  w w .  j  a va2 s  . c o  m*/
    try {
        repo = getLargeFileRepository(request, path);
        if (repo == null) {
            String error = MessageFormat.format(LfsText.get().lfsFailedToGetRepository, path);
            LOG.error(error);
            throw new LfsException(error);
        }
        res.setStatus(SC_OK);
        TransferHandler handler = TransferHandler.forOperation(request.operation, repo, request.objects);
        gson.toJson(handler.process(), w);
    } catch (LfsValidationError e) {
        sendError(res, w, SC_UNPROCESSABLE_ENTITY, e.getMessage());
    } catch (LfsRepositoryNotFound e) {
        sendError(res, w, SC_NOT_FOUND, e.getMessage());
    } catch (LfsRepositoryReadOnly e) {
        sendError(res, w, SC_FORBIDDEN, e.getMessage());
    } catch (LfsRateLimitExceeded e) {
        sendError(res, w, SC_RATE_LIMIT_EXCEEDED, e.getMessage());
    } catch (LfsBandwidthLimitExceeded e) {
        sendError(res, w, SC_BANDWIDTH_LIMIT_EXCEEDED, e.getMessage());
    } catch (LfsInsufficientStorage e) {
        sendError(res, w, SC_INSUFFICIENT_STORAGE, e.getMessage());
    } catch (LfsUnavailable e) {
        sendError(res, w, SC_SERVICE_UNAVAILABLE, e.getMessage());
    } catch (LfsUnauthorized e) {
        sendError(res, w, SC_UNAUTHORIZED, e.getMessage());
    } catch (LfsException e) {
        sendError(res, w, SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        w.flush();
    }
}

From source file:net.mindengine.blogix.web.BlogixServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) {
    String uri = req.getRequestURI();
    try {/* ww  w  . j a  va  2 s .c o m*/
        res.setStatus(200);
        String contentType = findContentTypeFor(uri);
        if (contentType != null) {
            res.setContentType(contentType);
        }
        blogix.processUri(uri, res.getOutputStream());
    } catch (Throwable e) {
        res.setStatus(400);
        printResponseText(res, ExceptionUtils.getMessage(e) + "\n" + ExceptionUtils.getStackTrace(e));
    }
}

From source file:PDFServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String presentationtype = request.getParameter("presentationtype");
    Document document = new Document();
    try {//from ww  w.  j  ava 2  s  . c  o  m
        if ("pdf".equals(presentationtype)) {
            response.setContentType("application/pdf");
            PdfWriter.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:uk.org.iay.mdq.server.ResultTextView.java

@Override
public void render(final Map<String, ?> model, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {

    log.debug("rendering as {}", getContentType());
    final Result result = (Result) model.get("result");

    if (result.isNotFound()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*from   w  w  w.  java2 s.com*/
    }

    OutputStream out = response.getOutputStream();

    response.setContentType(new MediaType("text", "plain", Charset.forName("UTF-8")).toString());
    final Writer w = new OutputStreamWriter(out, Charset.forName("UTF-8"));

    final Representation norm = result.getRepresentation();
    final byte[] bytes = norm.getBytes();
    w.write("Query result is:\n");
    w.write("   " + bytes.length + " bytes\n");
    w.write("   ETag is " + norm.getETag() + "\n");
    w.write("\n");
    w.write(new String(bytes, Charset.forName("UTF-8")));
}