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:org.apache.hadoop.gateway.rm.dispatch.RMHaDispatchTest.java

@Test
public void testConnectivityFailover() throws Exception {
    String serviceName = "RESOURCEMANAGER";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(//  w ww  . j  a  va  2s . c o  m
            HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
    HaProvider provider = new DefaultHaProvider(descriptor);
    URI uri1 = new URI("http://passive-host");
    URI uri2 = new URI("http://other-host");
    URI uri3 = new URI("http://active-host");
    ArrayList<String> urlList = new ArrayList<>();
    urlList.add(uri1.toString());
    urlList.add(uri2.toString());
    urlList.add(uri3.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();

    BasicHttpResponse inboundResponse = EasyMock.createNiceMock(BasicHttpResponse.class);
    EasyMock.expect(inboundResponse.getStatusLine()).andReturn(getStatusLine()).anyTimes();
    EasyMock.expect(inboundResponse.getEntity()).andReturn(getResponseEntity()).anyTimes();
    EasyMock.expect(inboundResponse.getFirstHeader(LOCATION)).andReturn(getFirstHeader(uri3.toString()))
            .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<ServletOutputStream>() {
        @Override
        public ServletOutputStream answer() throws Throwable {
            return new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                    throw new IOException("unreachable-host");
                }

                @Override
                public void setWriteListener(WriteListener arg0) {
                }

                @Override
                public boolean isReady() {
                    return false;
                }
            };
        }
    }).once();
    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
    EasyMock.replay(filterConfig, servletContext, inboundResponse, outboundRequest, inboundRequest,
            outboundResponse);

    RMHaDispatch dispatch = new RMHaDispatch();
    dispatch.setHttpClient(new DefaultHttpClient());
    dispatch.setHaProvider(provider);
    dispatch.init();
    long startTime = System.currentTimeMillis();
    try {
        dispatch.setInboundResponse(inboundResponse);
        dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } catch (IOException e) {
        //this is expected after the failover limit is reached
    }
    Assert.assertEquals(uri3.toString(),
            dispatch.getUriFromInbound(inboundRequest, inboundResponse, null).toString());
    long elapsedTime = System.currentTimeMillis() - startTime;
    Assert.assertEquals(uri3.toString(), provider.getActiveURL(serviceName));
    //test to make sure the sleep took place
    Assert.assertTrue(elapsedTime > 1000);
}

From source file:com.ephesoft.gxt.foldermanager.server.UploadDownloadFilesServlet.java

private void downloadFile(HttpServletRequest req, HttpServletResponse response,
        String currentFileDownloadPath) {
    DataInputStream in = null;/*from w w w .j  a v  a  2s.  c  o m*/
    ServletOutputStream outStream = null;
    try {
        outStream = response.getOutputStream();
        File file = new File(currentFileDownloadPath);
        int length = 0;
        String mimetype = "application/octet-stream";
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());
        String fileName = file.getName();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        byte[] byteBuffer = new byte[1024];
        in = new DataInputStream(new FileInputStream(file));
        while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
            outStream.write(byteBuffer, 0, length);
        }
    } catch (IOException e) {
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        if (outStream != null) {
            try {
                outStream.flush();
            } catch (IOException e) {
            }
            try {
                outStream.close();
            } catch (IOException e) {
            }

        }
    }
}

From source file:it.cineca.pst.huborcid.web.rest.UploadOrcidEntityFileResource.java

@RequestMapping(value = "/uploadOrcidEntity/downloadExcelResult/{id}", method = RequestMethod.GET)
@Timed/*from   w  w w  . jav  a2s.c  om*/
public void getExcelResultUploadOrcidEntity(@PathVariable Long id, HttpServletResponse response) {
    try {
        ResultUploadOrcidEntity resultUploadOrcid = resultUploadOrcidEntityRepository.findOne(id);
        byte[] fileBytesResult = resultUploadOrcid.getFileResult();
        response.setContentType("application/data");
        OutputStream outs = response.getOutputStream();
        outs.write(fileBytesResult);
        outs.flush();
        outs.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:br.com.munif.personalsecurity.aplicacao.autorizacao.Autorizador.java

protected void methodNotAllowed(HttpServletRequest request, HttpServletResponse response) throws IOException {
    System.out.println("---->methodNotAllowed from " + request.getRemoteHost());
    response.setStatus(HttpStatus.SC_METHOD_NOT_ALLOWED);
    response.setContentType("application/json;charset=UTF-8");
    mapper.writeValue(response.getOutputStream(), "Mtodo no permitido");
}

From source file:cz.muni.fi.pb138.cvmanager.controller.PDFcontroller.java

/**
 * Http Get request for "/auth/download"
 * Converts cv from xml format to latex and uploads pdf to users pc
 *
 * @param lang     language of  cv in downloaded pdf
 * @param response http server response/*w  ww  .j  a v a  2 s.c  o  m*/
 */
@RequestMapping(value = "/auth/download", method = RequestMethod.GET)
public void downloadPDF(@RequestParam("l") String lang, HttpServletResponse response) {
    try {
        //uncomment the calling of method when login finished
        pdfGenerator.xmlToLatex(getPrincipalUsername(), lang);
        InputStream pdf = pdfGenerator.latexToPdf(getPrincipalUsername());

        response.setContentType("application/pdf");
        FileCopyUtils.copy(pdf, response.getOutputStream());
        response.flushBuffer();
    } catch (Exception ex) {
        System.out.print(ex.toString());
        try {
            PrintWriter out = response.getWriter();
            out.println("Sorry, generating of CV to PDF failed");
            out.close();
        } catch (Exception e) {
            System.out.print("not able to print on web site");
        }
    }
}

From source file:net.acesinc.convergentui.BaseFilter.java

protected void writeResponse(String responseBody, MimeType contentType) throws Exception {
    RequestContext context = RequestContext.getCurrentContext();
    // there is no body to send
    if (responseBody == null || responseBody.isEmpty()) {
        return;// ww  w . j  a v  a  2 s.c o m
    }
    HttpServletResponse servletResponse = context.getResponse();
    servletResponse.setCharacterEncoding("UTF-8");
    servletResponse.setContentType(contentType.toString());
    OutputStream outStream = servletResponse.getOutputStream();
    InputStream is = null;
    try {
        writeResponse(new ByteArrayInputStream(responseBody.getBytes()), outStream);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            outStream.flush();
            outStream.close();
        } catch (IOException ex) {
        }
    }
}

From source file:nl.b3p.viewer.stripes.ProxyActionBean.java

private Resolution proxyArcIMS() throws Exception {

    HttpServletRequest request = getContext().getRequest();

    if (!"POST".equals(request.getMethod())) {
        return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN);
    }/*w w  w  . j  a va 2 s.  com*/

    Map params = new HashMap(getContext().getRequest().getParameterMap());
    // Only allow these parameters in proxy request
    params.keySet().retainAll(Arrays.asList("ClientVersion", "Encode", "Form", "ServiceName"));
    URL theUrl = new URL(url);
    // Must not allow file / jar etc protocols, only HTTP:
    String path = theUrl.getPath();
    for (Map.Entry<String, String[]> param : (Set<Map.Entry<String, String[]>>) params.entrySet()) {
        if (path.length() == theUrl.getPath().length()) {
            path += "?";
        } else {
            path += "&";
        }
        path += URLEncoder.encode(param.getKey(), "UTF-8") + "="
                + URLEncoder.encode(param.getValue()[0], "UTF-8");
    }
    theUrl = new URL("http", theUrl.getHost(), theUrl.getPort(), path);

    // TODO logging for inspecting malicious proxy use

    ByteArrayOutputStream post = new ByteArrayOutputStream();
    IOUtils.copy(request.getInputStream(), post);

    // This check makes some assumptions on how browsers serialize XML
    // created by OpenLayers' ArcXML.js write() function (whitespace etc.),
    // but all major browsers pass this check
    if (!post.toString("US-ASCII").startsWith("<ARCXML version=\"1.1\"><REQUEST><GET_IMAGE")) {
        return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN);
    }

    final HttpURLConnection connection = (HttpURLConnection) theUrl.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("X-Forwarded-For", request.getRemoteAddr());

    connection.connect();
    try {
        IOUtils.copy(new ByteArrayInputStream(post.toByteArray()), connection.getOutputStream());
    } finally {
        connection.getOutputStream().flush();
        connection.getOutputStream().close();
    }

    return new StreamingResolution(connection.getContentType()) {
        @Override
        protected void stream(HttpServletResponse response) throws IOException {
            try {
                IOUtils.copy(connection.getInputStream(), response.getOutputStream());
            } finally {
                connection.disconnect();
            }

        }
    };
}

From source file:br.com.caelum.vraptor.mustache.interceptor.download.MustacheDownload.java

public void write(HttpServletResponse response) throws IOException {
    this.writeDetails(response);

    String fileContent = this.fileContent(this.template);
    Reader reader = new StringReader(fileContent);
    Mustache compile = new DefaultMustacheFactory().compile(reader, this.fileName);

    OutputStream out = response.getOutputStream();
    Writer writer = new OutputStreamWriter(out);

    compile.execute(writer, this.scope).flush();
}

From source file:com.krawler.common.util.LocaleJsController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    OutputStream out = response.getOutputStream();
    response.setContentType("text/javascript");
    byte[] buffer = getContents(RequestContextUtils.getLocale(request));
    out.write(buffer);/*from  www. j a  v  a2s .  c o  m*/
    out.close();
    return null;
}

From source file:edu.lafayette.metadb.web.controlledvocab.ShowVocab.java

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*///  w  w w .  j  a  va2s  . co  m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    String vocabName = request.getParameter("vocab-name");
    //MetaDbHelper.note("Vocab Name in Servlet: "+vocabName);
    PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
    response.setCharacterEncoding("utf-8");
    request.setCharacterEncoding("utf-8");
    JSONArray vocab = new JSONArray();
    try {
        Set<String> vocabList = ControlledVocabDAO.getControlledVocab(vocabName);
        Iterator<String> itr = vocabList.iterator();
        String[] term = request.getParameterValues("term");

        boolean autocomplete = term != null && !(term[0].equals(""));
        while (itr.hasNext()) {
            String entry = itr.next();
            if (autocomplete) {
                //MetaDbHelper.note("Entry: "+entry+", query: "+term[0]);
                if (entry.toLowerCase().startsWith(term[0].toLowerCase()))
                    vocab.put(entry);
            } else
                vocab.put(entry);
        }
        out.print(vocab);
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }
    out.flush();
}