Java Code Examples for javax.servlet.ServletOutputStream

Original Post: http://www.programcreek.com/java-api-examples/index.php?api=javax.servlet.ServletOutputStream

The following code examples are extracted from open source projects. You can click  up the examples you like. Your votes will be used in an intelligent system to get more and better code examples.

Code Example 1:

From project accumulo, under directory /server/src/main/java/org/apache/accumulo/server/monitor/servlets/.

Source DefaultServlet.java

private void getResource(HttpServletRequest req,HttpServletResponse resp) throws IOException {
  try {
    String path=req.getRequestURI();
    if (path.endsWith(".jpg"))     resp.setContentType("image/jpeg");
    if (path.endsWith(".html"))     resp.setContentType("text/html");
    path=path.substring(1);
    InputStream data=BasicServlet.class.getClassLoader().getResourceAsStream(path);
    ServletOutputStream out=resp.getOutputStream();
    try {
      if (data != null) {
        byte[] buffer=new byte[1024];
        int n;
        while ((n=data.read(buffer)) > 0)         out.write(buffer,0,n);
      }
 else {
        out.write(("could not get resource " + path + "").getBytes());
      }
    }
  finally {
      data.close();
    }
  }
 catch (  Throwable t) {
    log.error(t,t);
    throw new IOException(t);
  }
}

Code Example 2:

From project aether-core, under directory /aether-connector-asynchttpclient/src/test/java/org/eclipse/aether/connector/async/.

Source Generate.java

public boolean execute(HttpServletRequest request,HttpServletResponse response,Map<Object,Object> ctx) throws Exception {
  if ("GET".equals(request.getMethod())) {
    String path=request.getPathInfo();
    Long length=lengths.get(path);
    if (length != null) {
      response.setContentType("application/octet-stream");
      response.setContentLength(length.intValue());
      ServletOutputStream out=response.getOutputStream();
      for (int i=length.intValue(); i > 0; ) {
        int n=Math.min(i,bytes.length);
        i-=n;
        out.write(bytes,0,n);
      }
      out.close();
      return false;
    }
  }
  return true;
}

Code Example 3:

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/servlets/.

Source ReportDownloader.java

private void serveTemplate(HttpServletRequest request,HttpServletResponse response,BaseReportInfo report,String templateName) throws ServletException {
  String rinsedTemplateName=templateName.replaceAll("\\..*$","").replaceAll("\\W","") + ".vm";
  try {
    AuthManagerInfo authManager=this.databaseDefn.getAuthManager();
    if (!authManager.getAuthenticator().loggedInUserAllowedTo(request,PrivilegeType.MANAGE_TABLE,report.getParentTable())) {
      throw new DisallowedException(authManager.getLoggedInUser(request),PrivilegeType.MANAGE_TABLE,report.getParentTable());
    }
    CompanyInfo company=this.databaseDefn.getAuthManager().getCompanyForLoggedInUser(request);
    String pathString=this.databaseDefn.getDataManagement().getWebAppRoot() + "WEB-INF/templates/uploads/" + company.getInternalCompanyName()+ "/"+ report.getInternalReportName()+ "/"+ rinsedTemplateName;
    FileReader fr=new FileReader(pathString);
    BufferedReader br=new BufferedReader(fr);
    List<String> lines=new LinkedList<String>();
    String s;
    while ((s=br.readLine()) != null) {
      lines.add(s);
    }
    fr.close();
    response.setHeader("Content-disposition","attachment; filename=" + rinsedTemplateName);
    response.setHeader("Cache-Control","no-cache");
    response.setContentType("text/html");
    ServletOutputStream sos=response.getOutputStream();
    for (    String line : lines) {
      sos.println(line);
    }
    sos.flush();
  }
 catch (  AgileBaseException abex) {
    logger.error("Problem serving template: " + abex);
    throw new ServletException("Problem serving template: " + abex);
  }
catch (  IOException ioex) {
    logger.error("Problem serving template: " + ioex);
    throw new ServletException("Problem serving template: " + ioex);
  }
}

Code Example 4:

From project airlift, under directory /rack/src/test/java/io/airlift/rack/.

Source TestRackServlet.java

private String performRequest(String queryString,String path,final String postBody,String method) throws IOException, ServletException {
  HttpServletRequest request=mock(HttpServletRequest.class);
  when(request.getInputStream()).thenReturn(new ServletInputStream(){
    int index=0;
    @Override public int read() throws IOException {
      if (index < postBody.length())       return postBody.charAt(index++);
      return -1;
    }
    @Override public void reset(){
      index=0;
    }
  }
);
  when(request.getScheme()).thenReturn("http");
  when(request.getMethod()).thenReturn(method);
  when(request.getRequestURI()).thenReturn(path);
  when(request.getQueryString()).thenReturn(queryString);
  when(request.getServerName()).thenReturn("TestServer");
  when(request.getServerPort()).thenReturn(new Random().nextInt());
  when(request.getHeaderNames()).thenReturn(Collections.enumeration(ImmutableList.<String>of()));
  final StringBuilder outputBuilder=new StringBuilder();
  ServletOutputStream outputStream=new ServletOutputStream(){
    @Override public void write(    int i) throws IOException {
      outputBuilder.append(new String(new int[]{i},0,1));
    }
  }
;
  HttpServletResponse response=mock(HttpServletResponse.class);
  when(response.getOutputStream()).thenReturn(outputStream);
  servlet.service(request,response);
  return outputBuilder.toString();
}

Code Example 5:

From project akvo-flow, under directory /GAE/src/org/waterforpeople/mapping/app/web/.

Source TestHarnessServlet.java

private void writeImageToResponse(HttpServletResponse resp,String urlString){
  resp.setContentType("image/jpeg");
  try {
    ServletOutputStream out=resp.getOutputStream();
    URL url=new URL(urlString);
    InputStream in=url.openStream();
    byte[] buffer=new byte[2048];
    int size;
    while ((size=in.read(buffer,0,buffer.length)) != -1) {
      out.write(buffer,0,size);
    }
    in.close();
    out.flush();
  }
 catch (  Exception ex) {
  }
}

Code Example 6:

From project alfresco, under directory /root/modules/wcmquickstart/wcmquickstartwebsite/source/java/org/alfresco/wcm/client/view/.

Source StreamedAssetView.java

/** 
 * @see org.springframework.web.servlet.view.AbstractView#renderMergedOutputModel(java.util.Map,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
 */
@Override protected void renderMergedOutputModel(Map<String,Object> model,HttpServletRequest request,HttpServletResponse response) throws Exception {
  boolean render=headerHelper.setHeaders(asset,attach,request,response);
  ServletOutputStream out=null;
  if (render) {
    ContentStream contentStream=null;
    if (renditionName != null) {
      Map<String,Rendition> renditions=asset.getRenditions();
      contentStream=renditions.get(renditionName);
    }
 else {
      contentStream=asset.getContentAsInputStream();
    }
    if (contentStream != null) {
      String mimeType=contentStream.getMimeType();
      response.setContentType(mimeType == null ? "application/octet-stream" : mimeType);
      response.setContentLength((int)contentStream.getLength());
      out=response.getOutputStream();
      contentStream.output(out);
    }
  }
}

Code Example 7:

From project alfresco, under directory /root/projects/remote-api/source/java/org/alfresco/repo/web/util/.

Source HttpRangeProcessor.java

/** 
 * Process a single range request.
 * @param res        HttpServletResponse
 * @param reader     ContentReader to retrieve content
 * @param range      Range header value
 * @param mimetype   Content mimetype
 * @return true if processed range, false otherwise
 */
private boolean processSingleRange(HttpServletResponse res,ContentReader reader,String range,String mimetype) throws IOException {
  boolean processedRange=false;
  Range r=null;
  try {
    r=Range.constructRange(range,mimetype,reader.getSize());
  }
 catch (  IllegalArgumentException err) {
    if (getLogger().isDebugEnabled())     getLogger().debug("Failed to parse range header - returning 416 status code: " + err.getMessage());
    res.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
    res.setHeader(HEADER_CONTENT_RANGE,"\"*\"");
    res.getOutputStream().close();
    return true;
  }
  res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
  res.setContentType(mimetype);
  String contentRange="bytes " + Long.toString(r.start) + "-"+ Long.toString(r.end)+ "/"+ Long.toString(reader.getSize());
  res.setHeader(HEADER_CONTENT_RANGE,contentRange);
  res.setHeader(HEADER_CONTENT_LENGTH,Long.toString((r.end - r.start) + 1L));
  if (getLogger().isDebugEnabled())   getLogger().debug("Processing: Content-Range: " + contentRange);
  InputStream is=null;
  try {
    ServletOutputStream os=res.getOutputStream();
    is=reader.getContentInputStream();
    streamRangeBytes(r,is,os,0L);
    os.close();
    processedRange=true;
  }
 catch (  IOException err) {
    if (getLogger().isDebugEnabled())     getLogger().debug("Unable to process single range due to IO Exception: " + err.getMessage());
    throw err;
  }
 finally {
    if (is != null)     is.close();
  }
  return processedRange;
}

Code Example 8:

From project Alitheia-Core, under directory /alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/.

Source AdminServlet.java

/** 
 * Sends a resource (stored in the jar file) as a response. The mime-type is set to @p mimeType . The @p path to the resource should start with a / . Test cases: - null mimetype, null path, bad path, relative path, path not found, - null response TODO: How to simulate conditions that will cause IOException
 */
protected void sendResource(HttpServletResponse response,Pair<String,String> source) throws ServletException, IOException {
  InputStream istream=getClass().getResourceAsStream(source.first);
  if (istream == null) {
    throw new IOException("Path not found: " + source.first);
  }
  byte[] buffer=new byte[1024];
  int bytesRead=0;
  int totalBytes=0;
  response.setContentType(source.second);
  ServletOutputStream ostream=response.getOutputStream();
  while ((bytesRead=istream.read(buffer)) > 0) {
    ostream.write(buffer,0,bytesRead);
    totalBytes+=bytesRead;
  }
}

Code Example 9:

From project alkacon-oamp, under directory /com.alkacon.opencms.formgenerator/src/com/alkacon/opencms/formgenerator/dialog/.

Source CmsFormRfsFileDownloadDialog.java

/** 
 * Generates the output of the file.<p>
 * @throws IOException if something goes wrong 
 */
public void generateOutput() throws IOException {
  HttpServletResponse res=CmsFlexController.getController(getJsp().getRequest()).getTopResponse();
  File downloadFile=getDownloadFile(getParamResource());
  String mimeType=OpenCms.getResourceManager().getMimeType(downloadFile.getName(),null,"application/octet-stream");
  res.setContentType(mimeType);
  res.setHeader("Content-Disposition",new StringBuffer("attachment; filename=\"").append(downloadFile.getName()).append("\"").toString());
  res.setContentLength((int)downloadFile.length());
  ServletOutputStream outStream=res.getOutputStream();
  InputStream in=new BufferedInputStream(new FileInputStream(downloadFile));
  try {
    int bit=in.read();
    while ((bit) >= 0) {
      outStream.write(bit);
      bit=in.read();
    }
  }
  finally {
    if (outStream != null) {
      try {
        outStream.flush();
        outStream.close();
      }
 catch (      SocketException soe) {
      }
    }
    in.close();
  }
}

Code Example 10:

From project alkacon-oamp, under directory /com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/dialog/.

Source CmsFormRfsFileDownloadDialog.java

/** 
 * Generates the output of the file.<p>
 * @throws IOException if something goes wrong 
 */
public void generateOutput() throws IOException {
  HttpServletResponse res=CmsFlexController.getController(getJsp().getRequest()).getTopResponse();
  File downloadFile=getDownloadFile(getParamResource());
  String mimeType=OpenCms.getResourceManager().getMimeType(downloadFile.getName(),null,"application/octet-stream");
  res.setContentType(mimeType);
  res.setHeader("Content-Disposition",new StringBuffer("attachment; filename=\"").append(downloadFile.getName()).append("\"").toString());
  res.setContentLength((int)downloadFile.length());
  ServletOutputStream outStream=res.getOutputStream();
  InputStream in=new BufferedInputStream(new FileInputStream(downloadFile));
  try {
    int bit=in.read();
    while ((bit) >= 0) {
      outStream.write(bit);
      bit=in.read();
    }
  }
  finally {
    if (outStream != null) {
      try {
        outStream.flush();
        outStream.close();
      }
 catch (      SocketException soe) {
      }
    }
    in.close();
  }
}

Code Example 11:

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/www/http/.

Source Webserver.java

public ServletOutputStream getOutputStream(){
synchronized (out) {
    if (rout == null) {
      if (pw != null)       throw new IllegalStateException("Already returned as a writer");
      rout=out;
    }
  }
  return rout;
}

Code Example 12:

From project accumulo, under directory /server/src/main/java/org/apache/accumulo/server/monitor/servlets/.

Source DefaultServlet.java

private void getDocResource(HttpServletRequest req,final HttpServletResponse resp) throws IOException {
  final String path=req.getRequestURI();
  if (path.endsWith(".html"))   resp.setContentType("text/html");
  final String aHome=System.getenv("ACCUMULO_HOME");
  PermissionCollection pc=new Permissions();
  pc.add(new FilePermission(aHome + "/docs/-","read"));
  AccessControlContext acc=new AccessControlContext(new ProtectionDomain[]{new ProtectionDomain(null,pc)});
  IOException e=AccessController.doPrivileged(new PrivilegedAction<IOException>(){
    @Override public IOException run(){
      InputStream data=null;
      try {
        File file=new File(aHome + path);
        data=new FileInputStream(file.getAbsolutePath());
        byte[] buffer=new byte[1024];
        int n;
        ServletOutputStream out=resp.getOutputStream();
        while ((n=data.read(buffer)) > 0)         out.write(buffer,0,n);
        return null;
      }
 catch (      IOException e) {
        return e;
      }
 finally {
        if (data != null) {
          try {
            data.close();
          }
 catch (          IOException ex) {
            log.error(ex,ex);
          }
        }
      }
    }
  }
,acc);
  if (e != null)   throw e;
}

Code Example 13:

From project agile, under directory /agile-framework/src/main/java/org/apache/catalina/servlets/.

Source DefaultServlet.java

/** 
 * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
 * @param resourceInfo The resource information
 * @param ostream The output stream to write to
 * @exception IOException if an input/output error occurs
 */
protected void copy(CacheEntry cacheEntry,InputStream is,ServletOutputStream ostream) throws IOException {
  IOException exception=null;
  InputStream resourceInputStream=null;
  if (cacheEntry.resource != null) {
    byte buffer[]=cacheEntry.resource.getContent();
    if (buffer != null) {
      ostream.write(buffer,0,buffer.length);
      return;
    }
    resourceInputStream=cacheEntry.resource.streamContent();
  }
 else {
    resourceInputStream=is;
  }
  InputStream istream=new BufferedInputStream(resourceInputStream,input);
  exception=copyRange(istream,ostream);
  istream.close();
  if (exception != null)   throw exception;
}

Code Example 14:

From project agile, under directory /agile-framework/src/main/java/org/apache/catalina/servlets/.

Source DefaultServlet.java

/** 
 * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
 * @param resourceInfo The ResourceInfo object
 * @param ostream The output stream to write to
 * @param range Range the client wanted to retrieve
 * @exception IOException if an input/output error occurs
 */
protected void copy(CacheEntry cacheEntry,ServletOutputStream ostream,Range range) throws IOException {
  IOException exception=null;
  InputStream resourceInputStream=cacheEntry.resource.streamContent();
  InputStream istream=new BufferedInputStream(resourceInputStream,input);
  exception=copyRange(istream,ostream,range.start,range.end);
  istream.close();
  if (exception != null)   throw exception;
}

Code Example 15:

From project agile, under directory /agile-framework/src/main/java/org/apache/catalina/servlets/.

Source DefaultServlet.java

/** 
 * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
 * @param resourceInfo The ResourceInfo object
 * @param ostream The output stream to write to
 * @param ranges Enumeration of the ranges the client wanted to retrieve
 * @param contentType Content type of the resource
 * @exception IOException if an input/output error occurs
 */
protected void copy(CacheEntry cacheEntry,ServletOutputStream ostream,Iterator ranges,String contentType) throws IOException {
  IOException exception=null;
  while ((exception == null) && (ranges.hasNext())) {
    InputStream resourceInputStream=cacheEntry.resource.streamContent();
    InputStream istream=new BufferedInputStream(resourceInputStream,input);
    Range currentRange=(Range)ranges.next();
    ostream.println();
    ostream.println("--" + mimeSeparation);
    if (contentType != null)     ostream.println("Content-Type: " + contentType);
    ostream.println("Content-Range: bytes " + currentRange.start + "-"+ currentRange.end+ "/"+ currentRange.length);
    ostream.println();
    exception=copyRange(istream,ostream,currentRange.start,currentRange.end);
    istream.close();
  }
  ostream.println();
  ostream.print("--" + mimeSeparation + "--");
  if (exception != null)   throw exception;
}

Code Example 16:

From project agile, under directory /agile-framework/src/main/java/org/apache/catalina/servlets/.

Source DefaultServlet.java

/** 
 * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
 * @param istream The input stream to read from
 * @param ostream The output stream to write to
 * @return Exception which occurred during processing
 */
protected IOException copyRange(InputStream istream,ServletOutputStream ostream){
  IOException exception=null;
  byte buffer[]=new byte[input];
  int len=buffer.length;
  while (true) {
    try {
      len=istream.read(buffer);
      if (len == -1)       break;
      ostream.write(buffer,0,len);
    }
 catch (    IOException e) {
      exception=e;
      len=-1;
      break;
    }
  }
  return exception;
}

Code Example 17:

From project agile, under directory /agile-framework/src/main/java/org/apache/catalina/servlets/.

Source DefaultServlet.java

/** 
 * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
 * @param istream The input stream to read from
 * @param ostream The output stream to write to
 * @param start Start of the range which will be copied
 * @param end End of the range which will be copied
 * @return Exception which occurred during processing
 */
protected IOException copyRange(InputStream istream,ServletOutputStream ostream,long start,long end){
  if (debug > 10)   log("Serving bytes:" + start + "-"+ end);
  try {
    istream.skip(start);
  }
 catch (  IOException e) {
    return e;
  }
  IOException exception=null;
  long bytesToRead=end - start + 1;
  byte buffer[]=new byte[input];
  int len=buffer.length;
  while ((bytesToRead > 0) && (len >= buffer.length)) {
    try {
      len=istream.read(buffer);
      if (bytesToRead >= len) {
        ostream.write(buffer,0,len);
        bytesToRead-=len;
      }
 else {
        ostream.write(buffer,0,(int)bytesToRead);
        bytesToRead=0;
      }
    }
 catch (    IOException e) {
      exception=e;
      len=-1;
    }
    if (len < buffer.length)     break;
  }
  return exception;
}

Code Example 18:

From project airlift, under directory /http-server/src/main/java/io/airlift/http/server/.

Source TimingFilter.java

@Override public ServletOutputStream getOutputStream() throws IOException {
  Preconditions.checkState(printWriter == null,"getWriter() has already been called");
  if (outputStream == null) {
    outputStream=new TimedServletOutputStream(super.getOutputStream());
  }
  return outputStream;
}

Code Example 19:

From project alfresco, under directory /root/projects/jndi-client/source/java/org/alfresco/filter/.

Source ByteResponseWrapper.java

public ServletOutputStream getOutputStream() throws java.io.IOException {
  if (print_writer_ == null) {
    if (servlet_output_ == null) {
      servlet_output_=captured_output_;
    }
    return servlet_output_;
  }
  throw new IllegalStateException();
}

Code Example 20:

From project alfresco, under directory /root/projects/remote-api/source/java/org/alfresco/repo/web/util/.

Source HttpRangeProcessor.java

/** 
 * Stream a range of bytes from the given InputStream to the ServletOutputStream
 * @param r       Byte Range to process
 * @param is      InputStream
 * @param os      ServletOutputStream
 * @param offset  Assumed InputStream position - to calculate skip bytes from
 * @return current InputStream position - so the stream can be reused if required 
 */
private void streamRangeBytes(final Range r,final InputStream is,final ServletOutputStream os,long offset) throws IOException {
  final Log logger=getLogger();
  final boolean trace=logger.isTraceEnabled();
  if (r.start != 0L && r.start > offset) {
    long skipped=offset + is.skip(r.start - offset);
    if (skipped < r.start) {
      return;
    }
  }
  long span=(r.end - r.start) + 1L;
  long bytesLeft=span;
  int read=0;
  byte[] buf=new byte[((int)bytesLeft) < CHUNKSIZE ? (int)bytesLeft : CHUNKSIZE];
  while ((read=is.read(buf)) > 0 && bytesLeft != 0L) {
    os.write(buf,0,read);
    bytesLeft-=(long)read;
    if (bytesLeft != 0L) {
      int resize=((int)bytesLeft) < CHUNKSIZE ? (int)bytesLeft : CHUNKSIZE;
      if (resize != buf.length) {
        buf=new byte[resize];
      }
    }
    if (trace)     logger.trace("...wrote " + read + " bytes, with "+ bytesLeft+ " to go...");
  }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s