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:com.aboutdata.web.controller.AvatarsController.java

/**
 * Get download from file-system//from  w  ww. j av  a2s  .  co m
 *
 * @param avatar
 * @param t type png jpg
 * @param v ? v=1
 * @param s
 * @param response {@link HttpServletResponse}
 */
@RequestMapping(value = "/{avatar}", method = RequestMethod.GET)
public void download(@PathVariable("avatar") String avatar, String t, String v, String s,
        HttpServletResponse response) {
    if (StringUtils.isEmpty(s)) {
        File file = new File("/var/avatars/" + avatar + "." + t);
        try {
            FileUtils.copyFile(file, response.getOutputStream());
        } catch (IOException ex) {
            logger.error("error {}", ex);
            response.setHeader("message", "?");
            response.setStatus(404);
        }
    } else {
        File file = new File("/var/avatars/" + avatar + "-" + s + "." + t);
        try {
            FileUtils.copyFile(file, response.getOutputStream());
        } catch (IOException ex) {
            logger.error("error {}", ex);
            response.setHeader("message", "?");
            response.setStatus(404);
        }
    }

}

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

@RequestMapping(value = DATA_PATH, method = RequestMethod.GET)
public void getData(@PathVariable("id") long id, HttpServletResponse response) throws IOException {
    if (videos.containsKey(id)) {
        Video v = videos.get(id);/* w ww .j  ava 2  s . c  o  m*/
        manager.copyVideoData(v, response.getOutputStream());
    } else {
        response.sendError(404, "No video with id=" + id + " exists.");
    }
}

From source file:org.apache.hadoop.gateway.ha.dispatch.DefaultHaDispatchTest.java

@Test
public void testConnectivityFailover() throws Exception {
    String serviceName = "OOZIE";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(//  w ww.j a  v a  2  s.  co  m
            HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
    HaProvider provider = new DefaultHaProvider(descriptor);
    URI uri1 = new URI("http://unreachable-host");
    URI uri2 = new URI("http://reachable-host");
    ArrayList<String> urlList = new ArrayList<String>();
    urlList.add(uri1.toString());
    urlList.add(uri2.toString());
    provider.addHaService(serviceName, urlList);
    FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class);
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);

    EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME))
            .andReturn(provider).anyTimes();

    BasicHttpParams params = new BasicHttpParams();

    HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class);
    EasyMock.expect(outboundRequest.getMethod()).andReturn("GET").anyTimes();
    EasyMock.expect(outboundRequest.getURI()).andReturn(uri1).anyTimes();
    EasyMock.expect(outboundRequest.getParams()).andReturn(params).anyTimes();

    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getRequestURL()).andReturn(new StringBuffer(uri2.toString())).once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0))
            .once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1))
            .once();

    HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.expect(outboundResponse.getOutputStream())
            .andAnswer(new IAnswer<SynchronousServletOutputStreamAdapter>() {
                @Override
                public SynchronousServletOutputStreamAdapter answer() throws Throwable {
                    return new SynchronousServletOutputStreamAdapter() {
                        @Override
                        public void write(int b) throws IOException {
                            throw new IOException("unreachable-host");
                        }
                    };
                }
            }).once();
    EasyMock.replay(filterConfig, servletContext, outboundRequest, inboundRequest, outboundResponse);
    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
    DefaultHaDispatch dispatch = new DefaultHaDispatch();
    dispatch.setHttpClient(new DefaultHttpClient());
    dispatch.setHaProvider(provider);
    dispatch.setServiceRole(serviceName);
    dispatch.init();
    long startTime = System.currentTimeMillis();
    try {
        dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } catch (IOException e) {
        //this is expected after the failover limit is reached
    }
    long elapsedTime = System.currentTimeMillis() - startTime;
    Assert.assertEquals(uri2.toString(), provider.getActiveURL(serviceName));
    //test to make sure the sleep took place
    Assert.assertTrue(elapsedTime > 1000);
}

From source file:com.sun.portal.os.portlets.ChartServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    OutputStream out = response.getOutputStream();

    try {// w w  w .  jav  a2s  .  c  o  m
        JFreeChart chart = createChart(request);
        if (chart != null) {
            response.setContentType(CONTENT_TYPE_IMG_PNG);
            ChartUtilities.writeChartAsPNG(out, chart, 400, 300);
        }
    } catch (Exception e) {
        System.err.println(e.toString());
    } finally {
        out.close();
    }
}

From source file:net.mindengine.oculus.frontend.web.controllers.trm.tasks.AjaxTaskSearchController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    verifyPermissions(request);//  w w  w. j  a  v  a 2 s. c  om

    OutputStream os = response.getOutputStream();
    response.setContentType("text/xml");

    String rId = request.getParameter("id");

    OutputStreamWriter w = new OutputStreamWriter(os);

    w.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    w.write("<tree id=\"" + rId + "\" >");

    if (rId.equals("0")) {
        w.write("<item text=\"My Tasks\" " + "id=\"mytasks\" "
                + "im0=\"tombs.gif\" im1=\"tombs_open.gif\" im2=\"tombs.gif\" child=\"1\" "
                + " nocheckbox=\"1\" >");
        w.write("</item>");
        w.write("<item text=\"Shared Tasks\" " + "id=\"shared\" "
                + "im0=\"tombs.gif\" im1=\"tombs_open.gif\" im2=\"tombs.gif\" child=\"1\" "
                + " nocheckbox=\"1\" >");
        w.write("</item>");
    } else {
        User user = getUser(request);

        Collection<TrmTask> tasks = null;
        Long projectId = null;
        String strProject = request.getParameter("projectId");
        if (strProject != null) {
            projectId = Long.parseLong(strProject);
        }

        if (rId.equals("mytasks")) {
            tasks = trmDAO.getUserTasks(user.getId(), projectId);

        } else if (rId.equals("shared")) {
            Collection<User> users = trmDAO.getUsersWithSharedTasks(user.getId(), projectId);
            for (User u : users) {
                w.write("<item text=\"" + XmlUtils.escapeXml(u.getName()) + "\" " + "id=\"u" + u.getId() + "\" "
                        + "im0=\"workflow-icon-user.png\" im1=\"workflow-icon-user.png\" im2=\"workflow-icon-user.png\" child=\"1\" "
                        + " nocheckbox=\"1\" >");
                w.write("</item>");
            }
        } else if (rId.startsWith("u")) {
            Long userId = Long.parseLong(rId.substring(1));
            tasks = trmDAO.getUserSharedTasks(userId, projectId);
        }

        if (tasks != null) {
            for (TrmTask task : tasks) {
                w.write("<item text=\"" + XmlUtils.escapeXml(task.getName()) + "\" " + "id=\"t" + task.getId()
                        + "\" " + "im0=\"iconTask.png\" im1=\"iconTask.png\" im2=\"iconTask.png\" child=\"0\" "
                        + " >");
                w.write("</item>");
            }
        }

    }

    w.write("</tree>");
    w.flush();
    os.flush();
    os.close();
    return null;
}

From source file:se.vgregion.mobile.qr.QrController.java

@RequestMapping("/qr")
public void image(@RequestParam("url") String url,
        @RequestParam(value = "width", defaultValue = "300") int width,
        @RequestParam(value = "height", defaultValue = "300") int height, HttpServletResponse response)
        throws ServletException {

    OutputStream out = null;/*w ww.j a  v  a 2  s  .  co m*/
    try {
        response.setContentType("image/png");
        out = response.getOutputStream();
        Writer writer = new QRCodeWriter();
        BitMatrix matrix = writer.encode(url, BarcodeFormat.QR_CODE, width, height);
        MatrixToImageWriter.writeToStream(matrix, "png", out);
        out.flush();
    } catch (WriterException e) {
        throw new ServletException("Failed writing QR", e);
    } catch (IOException e) {
        throw new ServletException("Failed writing QR", e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

}

From source file:com.climate.oada.security.oauth.LogoutImpl.java

@Override
public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        Authentication authentication) throws IOException, ServletException {

    this.removeAccess(httpServletRequest);
    httpServletResponse.getOutputStream().write("Logged Out".getBytes());
}

From source file:company.gonapps.loghut.controller.BackupController.java

@RequestMapping(value = "/backup.do", method = RequestMethod.GET)
public void backup(HttpServletResponse response) throws Exception {
    response.setHeader("Content-Type", "application/x-gzip");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + "BACKUP.tar.gz" + "\"");
    postService.backup(response.getOutputStream());
}

From source file:eionet.cr.web.action.VoIDActionBean.java

/**
 * Handles the request for viewing VoID.
 *
 * @return//from  w  ww .  j a  v a 2 s.co m
 */
@DefaultHandler
public Resolution getVoID() {
    contextRoot = StringUtils.substringBeforeLast(getContext().getRequest().getRequestURL().toString(), "/");

    StreamingResolution result = new StreamingResolution("application/xml") {
        public void stream(HttpServletResponse response) throws Exception {
            List<UploadDTO> uploads = DAOFactory.get().getDao(HelperDAO.class).getAllRdfUploads();
            VoIDXmlWriter xmlWriter = new VoIDXmlWriter(response.getOutputStream(), contextRoot);
            xmlWriter.writeVoIDXml(uploads);
        }
    };
    return result;
}

From source file:authentication.DefaultAuthenticationFailureHandler.java

/** {@inheritDoc} */
@Override//from  w ww.  j  a v  a2 s  .  c o m
public void onAuthenticationFailure(final HttpServletRequest request, final HttpServletResponse response,
        final AuthenticationException exception) throws IOException {
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.setStatus(HttpStatus.UNAUTHORIZED.value());
    response.getOutputStream()
            .print(String.format(JSON, HttpStatus.UNAUTHORIZED.value(), exception.getMessage()));
}