Java Code Examples for javax.servlet.ServletOutputStream

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project eucalyptus, under directory /clc/modules/www/src/edu/ucsb/eucalyptus/admin/server/.

Source file: Registration.java

  23 
vote

@Override protected void doGet(final HttpServletRequest httpServletRequest,final HttpServletResponse httpServletResponse) throws ServletException, IOException {
  String uuid=UUID.randomUUID().toString();
  String registrationId=getRegistrationId();
  ServletOutputStream op=httpServletResponse.getOutputStream();
  LOG.info("Using registrationId: " + registrationId);
  op.write(getMessage(registrationId,UUID.randomUUID().toString()).getBytes());
  op.flush();
}
 

Example 2

From project Socket.IO-Java, under directory /core/src/main/java/com/glines/socketio/server/transport/.

Source file: HTMLFileTransport.java

  22 
vote

protected void startSend(HttpServletResponse response) throws IOException {
  response.setContentType("text/html");
  response.setHeader("Connection","keep-alive");
  response.setHeader("Transfer-Encoding","chunked");
  char[] spaces=new char[244];
  Arrays.fill(spaces,' ');
  ServletOutputStream os=response.getOutputStream();
  os.print("<html><body>" + new String(spaces));
  response.flushBuffer();
}
 

Example 3

From project gxa, under directory /atlas-web/src/main/java/uk/ac/ebi/gxa/spring/view/dsv/.

Source file: AbstractDsvView.java

  21 
vote

@Override protected void renderMergedOutputModel(Map<String,Object> model,HttpServletRequest request,HttpServletResponse response) throws Exception {
  DsvRowIterator<T> doc=buildDsvDocument(model);
  response.setHeader("Content-Disposition","attachment;filename=" + generateFileName(request));
  ServletOutputStream out=response.getOutputStream();
  DsvDocumentWriter writer=new DsvDocumentWriter(getDsvFormat().newWriter(new OutputStreamWriter(out)));
  writer.write(doc);
}
 

Example 4

From project android-joedayz, under directory /Proyectos/spring-rest-cliente/src/main/java/com/mycompany/rest/util/.

Source file: Writer.java

  19 
vote

/** 
 * Writes the report to the output stream
 */
public static void write(HttpServletResponse response,ByteArrayOutputStream bao){
  logger.debug("Writing report to the stream");
  try {
    ServletOutputStream outputStream=response.getOutputStream();
    bao.writeTo(outputStream);
    outputStream.flush();
    outputStream.close();
  }
 catch (  Exception e) {
    logger.error("Unable to write report to the output stream");
  }
}
 

Example 5

From project ANNIS, under directory /annis-gui/src/main/java/annis/gui/servlets/.

Source file: BinaryServlet.java

  19 
vote

@Override public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException {
  Map<String,String[]> binaryParameter=request.getParameterMap();
  toplevelCorpusName=binaryParameter.get("toplevelCorpusName")[0];
  documentName=binaryParameter.get("documentName")[0];
  ServletOutputStream out=null;
  try {
    out=response.getOutputStream();
    String range=request.getHeader("Range");
    String annisServiceURL=getServletContext().getInitParameter("AnnisWebService.URL");
    if (annisServiceURL == null) {
      throw new ServletException("AnnisWebService.URL was not set as init parameter in web.xml");
    }
    WebResource annisRes=client.resource(annisServiceURL);
    WebResource binaryRes=annisRes.path("corpora").path(URLEncoder.encode(toplevelCorpusName,"UTF-8")).path(URLEncoder.encode(documentName,"UTF-8")).path("binary");
    if (range != null) {
      responseStatus206(binaryRes,out,response,range);
    }
 else {
      responseStatus200(binaryRes,out,response);
    }
    out.flush();
  }
 catch (  IOException ex) {
    log.debug("IOException in BinaryServlet",ex);
  }
catch (  ClientHandlerException ex) {
    log.error(null,ex);
    response.setStatus(500);
  }
catch (  UniformInterfaceException ex) {
    log.error(null,ex);
    response.setStatus(500);
  }
}
 

Example 6

From project cloudify, under directory /restful/src/main/java/org/cloudifysource/rest/controllers/.

Source file: ServiceController.java

  19 
vote

/** 
 * Exception handler for all of the internal server's exceptions.
 * @param response The response object to edit, if not committed yet.
 * @param e The exception that occurred, from which data is read for logging and for the response error message.
 * @throws IOException Reporting failure to edit the response object
 */
@ExceptionHandler(Exception.class) @ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR) public void resolveDocumentNotFoundException(final HttpServletResponse response,final Exception e) throws IOException {
  if (response.isCommitted()) {
    logger.log(Level.WARNING,"Caught exception, but response already commited. Not sending error message based on exception",e);
  }
 else {
    final ServletOutputStream outputStream=response.getOutputStream();
    final String message="{\"status\":\"error\", \"error\":\"" + e.getMessage() + "\"}";
    logger.log(Level.SEVERE,"caught exception. Sending response message " + message,e);
    final byte[] messageBytes=message.getBytes();
    outputStream.write(messageBytes);
  }
}
 

Example 7

From project red5-mavenized, under directory /red5_base/src/main/java/org/red5/server/net/rtmpt/.

Source file: RTMPTServlet.java

  19 
vote

/** 
 * Return raw data to the client.
 * @param client RTMP connection
 * @param buffer Raw data as byte buffer
 * @param resp Servlet response
 * @throws IOException I/O exception
 */
protected void returnMessage(RTMPTConnection client,ByteBuffer buffer,HttpServletResponse resp) throws IOException {
  resp.setStatus(HttpServletResponse.SC_OK);
  resp.setHeader("Connection","Keep-Alive");
  resp.setHeader("Cache-Control","no-cache");
  resp.setContentType(CONTENT_TYPE);
  log.debug("Sending {} bytes",buffer.limit());
  resp.setContentLength(buffer.limit() + 1);
  ServletOutputStream output=resp.getOutputStream();
  output.write(client.getPollingDelay());
  ServletUtils.copy(buffer.asInputStream(),output);
  buffer.release();
  buffer=null;
}
 

Example 8

From project codjo-webservices, under directory /codjo-webservices-common/src/main/java/com/tilab/wsig/servlet/.

Source file: WSIGServlet.java

  18 
vote

/** 
 * Fill http response
 * @param soapResponse
 * @param httpResponse
 * @return
 */
private void fillHttpResponse(SOAPMessage soapResponse,HttpServletResponse httpResponse) throws Exception {
  byte[] content=null;
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  soapResponse.writeTo(baos);
  content=baos.toByteArray();
  httpResponse.setHeader("Cache-Control","no-store");
  httpResponse.setHeader("Pragma","no-cache");
  httpResponse.setDateHeader("Expires",0);
  httpResponse.setContentType("soap+xml; charset=utf-8");
  ServletOutputStream responseOutputStream=httpResponse.getOutputStream();
  responseOutputStream.write(content);
  responseOutputStream.flush();
  responseOutputStream.close();
}
 

Example 9

From project iJetty, under directory /example-webapps/hello/src/main/java/org/mortbay/ijetty/hello/.

Source file: HelloWorld.java

  18 
vote

public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html");
  ServletOutputStream out=response.getOutputStream();
  out.println("<html>");
  out.println("<h1>Hello From Servlet Land!</h1>");
  out.println("Brought to you by: " + proofOfLife);
  out.println("</html>");
  out.flush();
}
 

Example 10

From project IPHeatmap, under directory /IPHeatmap/ipheatmap-server/src/main/java/org/trillinux/ipheatmap/server/.

Source file: TileServlet.java

  18 
vote

private void createTile(int z,int x,int y,boolean nocache,HttpServletRequest request,HttpServletResponse response) throws IOException {
  ServletOutputStream output=response.getOutputStream();
  response.setContentType("image/png");
  Tile tile=new Tile(ipDir,labelFile,cacheDir);
  if (cache && !nocache && tile.tileExists(x,y,z)) {
    tile.writeCachedTile(x,y,z,output);
  }
 else {
    tile.generate(x,y,z,output);
  }
}
 

Example 11

From project jbpm-plugin, under directory /jbpm/src/main/java/hudson/jbpm/model/.

Source file: ProcessInstanceAction.java

  18 
vote

public void doImage(StaplerRequest req,StaplerResponse rsp) throws IOException, XPathExpressionException, DocumentException {
  ProcessInstance processInstance=getProcessInstance();
  GPD gpd=getGPD();
  ServletOutputStream output=rsp.getOutputStream();
  ProcessInstanceRenderer panel=new ProcessInstanceRenderer(processInstance,gpd);
  BufferedImage aimg=new BufferedImage(panel.getWidth(),panel.getHeight(),BufferedImage.TYPE_INT_RGB);
  Graphics2D g=aimg.createGraphics();
  panel.paint(g);
  g.dispose();
  ImageIO.write(aimg,"png",output);
  output.flush();
  output.close();
}
 

Example 12

From project jena-fuseki, under directory /src/main/java/org/apache/jena/fuseki/servlets/.

Source file: ResponseResultSet.java

  18 
vote

private static void output(String contentType,String charset,OutputContent proc,HttpServletRequest httpRequest,HttpServletResponse httpResponse){
  try {
    setHttpResponse(httpRequest,httpResponse,contentType,charset);
    httpResponse.setStatus(HttpSC.OK_200);
    ServletOutputStream out=httpResponse.getOutputStream();
    proc.output(out);
    out.flush();
    httpResponse.flushBuffer();
  }
 catch (  IOException ex) {
    SPARQL_ServletBase.errorOccurred(ex);
  }
}
 

Example 13

From project jetty-project, under directory /jetty-reverse-http/reverse-http-gateway/src/main/java/org/mortbay/jetty/rhttp/gateway/.

Source file: ConnectorServlet.java

  18 
vote

private void flush(ClientDelegate client,HttpServletRequest httpRequest,HttpServletResponse httpResponse) throws IOException {
  List<RHTTPRequest> requests=client.process(httpRequest);
  if (requests != null) {
    if (!client.isClosed())     schedule(client);
    ServletOutputStream output=httpResponse.getOutputStream();
    for (    RHTTPRequest request : requests)     output.write(request.getFrameBytes());
    output.flush();
    logger.debug("Delivered to device {} requests {} ",client.getTargetId(),requests);
  }
}
 

Example 14

From project ned, under directory /NEDAdminConsole/src/org/ned/server/nedadminconsole/server/.

Source file: NedStatisticsFileServlet.java

  18 
vote

private void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  ServletOutputStream outputStream=response.getOutputStream();
  ServletContext context=getServletConfig().getServletContext();
  String mimetype=context.getMimeType(filename);
  PrintWriter writer=new PrintWriter(outputStream);
  response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
  response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
  writeStatistics(writer);
  writer.close();
  outputStream.flush();
  outputStream.close();
}
 

Example 15

From project netnumeri, under directory /src/com/netnumeri/server/servlets/.

Source file: QuotesServlet.java

  18 
vote

private void export(HttpServletRequest request,HttpServletResponse response) throws IOException {
  String ticker=request.getParameter("name");
  Calendar cal=Calendar.getInstance();
  cal.add(Calendar.YEAR,-1);
  String s=null;
  try {
    s=YahooUtils.proxyYahooData(ticker,cal.getTime(),new Date());
  }
 catch (  Exception e) {
  }
  ServletOutputStream sos=response.getOutputStream();
  sos.print(s);
}
 

Example 16

From project ning-service-skeleton, under directory /utils/src/main/java/com/ning/jetty/utils/filters/.

Source file: PeepingTomResponseWrapper.java

  18 
vote

@Override public ServletOutputStream getOutputStream() throws IOException {
  if (stream == null) {
    try {
      final ServletOutputStream originalOutputStream=super.getOutputStream();
      stream=new OpenableServletOutputStream(originalOutputStream);
    }
 catch (    IllegalStateException e) {
      final PrintWriter originalWriter=super.getWriter();
      stream=new OpenableServletOutputStream(originalWriter);
    }
  }
  return stream;
}
 

Example 17

From project Pitbull, under directory /pitbull-servlet/src/test/java/org/jboss/pitbull/test/.

Source file: BasicTest.java

  18 
vote

@Override protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  resp.setContentType("text/plain");
  resp.setStatus(200);
  ServletOutputStream os=resp.getOutputStream();
  os.write("1st Chunk ".getBytes());
  os.flush();
  os.write("2nd chunk".getBytes());
}
 

Example 18

From project proxy-servlet, under directory /src/test/java/com/woonoz/proxy/servlet/.

Source file: HttpGetRequestHandlerTest.java

  18 
vote

@Test @Ignore public void testGet() throws IOException {
  URL targetServer=new URL("http://www.google.com/");
  HttpServletRequest request=EasyMock.createMock(HttpServletRequest.class);
  HttpServletResponse response=EasyMock.createControl().createMock(HttpServletResponse.class);
  HttpClient client=EasyMock.createMock(HttpClient.class);
  ServletOutputStream servletOutputStream=EasyMock.createMock(ServletOutputStream.class);
  EasyMock.expect(response.getOutputStream()).andReturn(servletOutputStream).anyTimes();
  EasyMock.replay(response);
  HttpGetRequestHandler httpGetRequestHandler=new HttpGetRequestHandler(request,response,targetServer,client);
  httpGetRequestHandler.execute();
  EasyMock.verify(response);
}
 

Example 19

From project Red5, under directory /src/org/red5/server/net/rtmpt/.

Source file: RTMPTServlet.java

  18 
vote

/** 
 * Return raw data to the client.
 * @param client RTMP connection
 * @param buffer Raw data as byte buffer
 * @param resp Servlet response
 * @throws IOException I/O exception
 */
protected void returnMessage(RTMPTConnection client,IoBuffer buffer,HttpServletResponse resp) throws IOException {
  log.debug("returnMessage {}",buffer);
  resp.setStatus(HttpServletResponse.SC_OK);
  resp.setHeader("Connection","Keep-Alive");
  resp.setHeader("Cache-Control","no-cache");
  resp.setContentType(CONTENT_TYPE);
  log.debug("Sending {} bytes",buffer.limit());
  resp.setContentLength(buffer.limit() + 1);
  ServletOutputStream output=resp.getOutputStream();
  output.write(client.getPollingDelay());
  ServletUtils.copy(buffer.asInputStream(),output);
  buffer.free();
  buffer=null;
}
 

Example 20

From project red5-server, under directory /src/org/red5/server/net/rtmpt/.

Source file: RTMPTServlet.java

  18 
vote

/** 
 * Return raw data to the client.
 * @param client RTMP connection
 * @param buffer Raw data as byte buffer
 * @param resp Servlet response
 * @throws IOException I/O exception
 */
protected void returnMessage(RTMPTConnection client,IoBuffer buffer,HttpServletResponse resp) throws IOException {
  log.debug("returnMessage {}",buffer);
  resp.setStatus(HttpServletResponse.SC_OK);
  resp.setHeader("Connection","Keep-Alive");
  resp.setHeader("Cache-Control","no-cache");
  resp.setContentType(CONTENT_TYPE);
  log.debug("Sending {} bytes",buffer.limit());
  resp.setContentLength(buffer.limit() + 1);
  ServletOutputStream output=resp.getOutputStream();
  output.write(client.getPollingDelay());
  ServletUtils.copy(buffer.asInputStream(),output);
  buffer.free();
  buffer=null;
}
 

Example 21

From project repose, under directory /project-set/commons/utilities/src/test/java/com/rackspace/papi/commons/util/servlet/http/.

Source file: MutableHttpServletResponseTest.java

  18 
vote

@Test public void shouldWriteResponseMessageBody() throws IOException {
  String responseBody="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<versions xmlns:ns2=\"http://www.w3.org/2005/Atom\" xmlns=\"http://docs.openstack.org/common/api/v1.0\" xmlns:ns3=\"http://docs.rackspacecloud.com/repose/versioning/v1.0\">" + "<version xsi:type=\"ns3:ServiceVersionMapping\" pp-host-id=\"service-v1\" name=\"Service Version 1\" status=\"DEPRECATED\" id=\"v1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"+ "<ns2:link href=\"http://localhost:65000/v1/\" rel=\"self\"/>"+ "</version>"+ "<version xsi:type=\"ns3:ServiceVersionMapping\" pp-host-id=\"service-v2\" name=\"Service Version 2\" status=\"CURRENT\" id=\"v2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"+ "<ns2:link href=\"http://localhost:65000/v2/\" rel=\"self\"/>"+ "</version>"+ "</versions>";
  HttpServletResponse original=mock(HttpServletResponse.class);
  ByteBuffer byteBuffer=new CyclicByteBuffer();
  ServletOutputStream outputStream=new ByteBufferServletOutputStream(byteBuffer);
  when(original.getOutputStream()).thenReturn(outputStream);
  MutableHttpServletResponse response=MutableHttpServletResponse.wrap(mock(HttpServletRequest.class),original);
  response.getWriter().write(responseBody);
  response.flushBuffer();
  InputStream inputStream=response.getBufferedOutputAsInputStream();
  InputStreamReader reader=new InputStreamReader(inputStream);
  BufferedReader bufReader=new BufferedReader(reader);
  assertNotNull(bufReader.readLine());
}
 

Example 22

From project reverse-proxy, under directory /project/src/main/java/com/tek271/reverseProxy/servlet/.

Source file: ContentUtils.java

  18 
vote

public static void copyBinary(HttpEntity entity,ServletResponse response){
  try {
    InputStream content=entity.getContent();
    ServletOutputStream outputStream=response.getOutputStream();
    IOUtils.copy(content,outputStream);
  }
 catch (  IOException e) {
    Throwables.propagate(e);
  }
}
 

Example 23

From project spring-security, under directory /web/src/test/java/org/springframework/security/web/context/.

Source file: HttpSessionSecurityContextRepositoryTests.java

  18 
vote

@Test public void outputStreamCloseDelegate() throws Exception {
  HttpSessionSecurityContextRepository repo=new HttpSessionSecurityContextRepository();
  repo.setSpringSecurityContextKey("imTheContext");
  MockHttpServletRequest request=new MockHttpServletRequest();
  HttpServletResponse response=mock(HttpServletResponse.class);
  ServletOutputStream outputstream=mock(ServletOutputStream.class);
  when(response.getOutputStream()).thenReturn(outputstream);
  HttpRequestResponseHolder holder=new HttpRequestResponseHolder(request,response);
  SecurityContextHolder.setContext(repo.loadContext(holder));
  SecurityContextHolder.getContext().setAuthentication(testToken);
  holder.getResponse().getOutputStream().close();
  verify(outputstream).close();
}
 

Example 24

From project tiles-request, under directory /tiles-request-portlet/src/test/java/org/apache/tiles/request/portlet/.

Source file: PortletRequestTest.java

  18 
vote

/** 
 * Test method for  {@link org.apache.tiles.request.portlet.PortletRequest#getOutputStream()}.
 * @throws IOException If something goes wrong.
 */
@Test public void testGetOutputStream() throws IOException {
  ServletOutputStream os=createMock(ServletOutputStream.class);
  expect(responseDelegate.getOutputStream()).andReturn(os);
  replay(applicationContext,request,response,os,portletContext,requestDelegate,responseDelegate);
  assertEquals(req.getOutputStream(),os);
  verify(applicationContext,request,response,os,portletContext,requestDelegate,responseDelegate);
}
 

Example 25

From project tocollege.net, under directory /src/main/java/com/apress/progwt/server/util/.

Source file: GearsManifestFilter.java

  18 
vote

public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse,FilterChain filterChain) throws IOException, ServletException {
  HttpServletRequest request=((HttpServletRequest)servletRequest);
  String userAgentString=request.getHeader("user-agent");
  System.out.println("UserAgent: " + userAgentString);
  String userAgent=getUserAgent(userAgentString);
  ServletOutputStream out=servletResponse.getOutputStream();
  HttpServletResponse response=(HttpServletResponse)servletResponse;
  response.setContentType("application/jsonrequest");
  out.println((String)_manifestMap.get(userAgent));
}
 

Example 26

From project Weave, under directory /WeaveServices/src/weave/servlets/.

Source file: GenericServlet.java

  18 
vote

private void sendError(HttpServletResponse response,Throwable exception,String moreInfo) throws IOException {
  String message=exception.getMessage();
  if (moreInfo != null)   message+="\n" + moreInfo;
  System.out.println("Serializing ErrorMessage: " + message);
  ServletOutputStream servletOutputStream=response.getOutputStream();
  ErrorMessage errorMessage=new ErrorMessage(new MessageException(message));
  errorMessage.faultCode=exception.getClass().getSimpleName();
  seriaizeCompressedAmf3(errorMessage,servletOutputStream);
}
 

Example 27

From project winstone, under directory /src/test/winstone/testApplication/servlets/.

Source file: CountRequestsServlet.java

  18 
vote

/** 
 * Get implementation - increments and shows the access count
 */
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  numberOfGets++;
  ServletOutputStream out=response.getOutputStream();
  out.println("<html><body>This servlet has been accessed via GET " + numberOfGets + " times</body></html>");
  out.flush();
}
 

Example 28

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

Source file: Generate.java

  17 
vote

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;
}
 

Example 29

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

Source file: ReportDownloader.java

  17 
vote

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);
  }
}
 

Example 30

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

Source file: TestRackServlet.java

  17 
vote

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

Example 31

From project aws-tvm-anonymous, under directory /src/com/amazonaws/tvm/.

Source file: RootServlet.java

  17 
vote

public static void sendErrorResponse(int httpResponseCode,HttpServletResponse response) throws Exception {
  ServletOutputStream out=null;
  try {
    response.setStatus(httpResponseCode);
    response.setContentType("text/plain; charset=UTF-8");
    response.setDateHeader("Expires",System.currentTimeMillis());
    out=response.getOutputStream();
    out.println(Constants.getMsg(httpResponseCode) + "");
  }
  finally {
    if (null != out) {
      try {
        out.flush();
        out.close();
      }
 catch (      IOException e) {
        log.warning("Error closing ServletOutputStream");
      }
    }
  }
}
 

Example 32

From project aws-tvm-identity, under directory /src/com/amazonaws/tvm/.

Source file: RootServlet.java

  17 
vote

public static void sendErrorResponse(int httpResponseCode,HttpServletResponse response) throws Exception {
  ServletOutputStream out=null;
  try {
    response.setStatus(httpResponseCode);
    response.setContentType("text/plain; charset=UTF-8");
    response.setDateHeader("Expires",System.currentTimeMillis());
    out=response.getOutputStream();
    out.println(Constants.getMsg(httpResponseCode) + "");
  }
  finally {
    if (null != out) {
      try {
        out.flush();
        out.close();
      }
 catch (      IOException e) {
        log.warning("Error closing ServletOutputStream");
      }
    }
  }
}
 

Example 33

From project BeeQueue, under directory /src/org/beequeue/buzz/.

Source file: QueryResourceController.java

  17 
vote

@Override public boolean process(BuzzContext ctx){
  try {
    TransactionContext.push();
    Coordiantor c=Singletons.getCoordinator();
    ServletOutputStream out=ctx.res.getOutputStream();
    ctx.res.setContentType("text/plain");
    String prefix=ctx.ancestor.toString();
    BuzzPath relativePath=ctx.relativePath();
    if (prefix.equals("db")) {
      out.println(c.selectAnyTable(relativePath.toString()));
    }
 else {
      String queryTemplate=queries.get(ctx.resoursePath.elementAt(0));
      HashMap<String,String> context=new HashMap<String,String>();
      for (int i=1; i < relativePath.size; i++) {
        context.put("v" + i,relativePath.elementAt(i));
      }
      String q=new GroovyTemplate(queryTemplate).generate(context);
      out.println(c.query(q));
    }
    return ctx.setHandled();
  }
 catch (  Exception e) {
    throw new BuzzException(500,e);
  }
 finally {
    TransactionContext.pop();
  }
}
 

Example 34

From project candlepin, under directory /src/main/java/org/candlepin/servlet/filter/logging/.

Source file: LoggingResponseWrapper.java

  17 
vote

public ServletOutputStream getOutputStream() throws java.io.IOException {
  if (outputStream == null) {
    outputStream=new ServletOutputStream(){
      @Override public void write(      int b) throws IOException {
        buffer.append((char)b);
        realResponse.getOutputStream().write(b);
      }
    }
;
  }
  return outputStream;
}
 

Example 35

From project conf4j, under directory /conf4j-webapp/src/main/java/org/conf4j/webapp/servlet/.

Source file: CheckScopeServlet.java

  17 
vote

@Override protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  resp.setContentType("text/plain");
  resp.setCharacterEncoding("UTF-8");
  final ServletOutputStream os=resp.getOutputStream();
  try {
    final PrintStream ps=new PrintStream(os);
    ps.println("----------------------------------------------------------------------------------------");
    ps.println("------------------------------------- CHECK SCOPE --------------------------------------");
    ps.println("----------------------------------------------------------------------------------------");
    CONF.checkScope(ps);
    ps.println("----------------------------------------------------------------------------------------");
  }
  finally {
    os.close();
  }
}
 

Example 36

From project dolphin, under directory /dolphinmaple/src/com/tan/servlet/.

Source file: WikiServlet.java

  17 
vote

@Override protected final void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  String uri=req.getRequestURI();
  String type=req.getParameter("type");
  ServletOutputStream out=resp.getOutputStream();
  if (type != null && type.charAt(0) == '0') {
    for (int i=0; i < KEYS.length; i++) {
      out.print(KEYS[i]);
    }
  }
 else   if (uri != null && uri.trim().length() > 0) {
    String wikiKey="wiki/";
    String url;
    int len=wikiKey.length();
    int idx=uri.indexOf("wiki/");
    if (idx >= 0) {
      idx+=len;
      url=uri.substring(idx);
      if (url != null) {
        url=URLEncoder.encode("http://zh.m.wikipedia.org/wiki?search=" + url.trim(),"utf-8");
        resp.sendRedirect("http://dolphinmaple.appspot.com/show.do?url=" + url);
      }
    }
  }
 else {
    out.println("No wiki information!");
  }
}
 

Example 37

From project EasySOA, under directory /easysoa-registry/easysoa-registry-api/easysoa-registry-api-messaging/src/main/java/org/easysoa/servlet/http/.

Source file: CopyHttpServletResponse.java

  17 
vote

public ServletOutputStream getOutputStream() throws IOException {
  copyOut=new CopyOutputStream(this.getResponse().getOutputStream());
  writer=new PrintWriter(new OutputStreamWriter(copyOut,this.getCharacterEncoding()));
  return new ServletOutputStream(){
    @Override public void write(    int b) throws IOException {
      copyOut.write(b);
    }
  }
;
}
 

Example 38

From project elasticsearch-jetty, under directory /src/main/java/com/sonian/elasticsearch/http/jetty/.

Source file: JettyHttpServerRestChannel.java

  17 
vote

@Override public void sendResponse(RestResponse response){
  resp.setContentType(response.contentType());
  resp.addHeader("Access-Control-Allow-Origin","*");
  if (response.status() != null) {
    resp.setStatus(response.status().getStatus());
  }
 else {
    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
  }
  if (restRequest.method() == RestRequest.Method.OPTIONS) {
    resp.addHeader("Access-Control-Max-Age","1728000");
    resp.addHeader("Access-Control-Allow-Methods","PUT, DELETE");
    resp.addHeader("Access-Control-Allow-Headers","X-Requested-With");
  }
  try {
    int contentLength=response.contentLength();
    if (response.prefixContentLength() > 0) {
      contentLength+=response.prefixContentLength();
    }
    if (response.suffixContentLength() > 0) {
      contentLength+=response.suffixContentLength();
    }
    resp.setContentLength(contentLength);
    ServletOutputStream out=resp.getOutputStream();
    if (response.prefixContent() != null) {
      out.write(response.prefixContent(),0,response.prefixContentLength());
    }
    out.write(response.content(),0,response.contentLength());
    if (response.suffixContent() != null) {
      out.write(response.suffixContent(),0,response.suffixContentLength());
    }
    out.close();
  }
 catch (  IOException e) {
    sendFailure=e;
  }
 finally {
    latch.countDown();
  }
}
 

Example 39

From project entando-core-engine, under directory /src/main/java/com/agiletec/plugins/jacms/aps/servlet/.

Source file: ResourceWardenServlet.java

  17 
vote

private void createResponse(HttpServletResponse resp,ResourceInterface resource,ResourceInstance instance) throws IOException, ServletException {
  resp.setContentType(instance.getMimeType());
  resp.setHeader("Content-Disposition","inline; filename=" + instance.getFileName());
  ServletOutputStream out=resp.getOutputStream();
  try {
    File fileTemp=new File(resource.getDiskFolder() + instance.getFileName());
    if (fileTemp.exists()) {
      InputStream is=new FileInputStream(fileTemp);
      byte[] buffer=new byte[8789];
      int length=-1;
      while ((length=is.read(buffer)) != -1) {
        out.write(buffer,0,length);
        out.flush();
      }
      is.close();
    }
  }
 catch (  Throwable t) {
    throw new ServletException("Errore in erogazione risorsa protetta",t);
  }
 finally {
    out.close();
  }
}
 

Example 40

From project framework, under directory /impl/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/implementation/.

Source file: FileRendererImplTest.java

  17 
vote

@Test public void testRenderBytesSuccess(){
  byte[] bytes="Test".getBytes();
  String fileName="fileName.pdf";
  logger.debug(EasyMock.anyObject(String.class));
  EasyMock.expectLastCall().anyTimes();
  facesContext.responseComplete();
  EasyMock.expectLastCall().times(1);
  response.setContentType(ContentType.PDF.getContentType());
  EasyMock.expectLastCall().times(1);
  response.setContentLength(bytes.length);
  EasyMock.expectLastCall().times(1);
  response.setHeader("Content-Disposition","filename=\"" + fileName + "\"");
  EasyMock.expectLastCall().times(1);
  ServletOutputStream stream=PowerMock.createMock(ServletOutputStream.class);
  try {
    stream.write(bytes,0,bytes.length);
    EasyMock.expectLastCall().times(1);
    stream.flush();
    EasyMock.expectLastCall().times(1);
    stream.close();
    EasyMock.expectLastCall().times(1);
    EasyMock.expect(response.getOutputStream()).andReturn(stream).times(3);
  }
 catch (  IOException e) {
    Assert.fail();
  }
  PowerMock.replayAll();
  renderer.render(bytes,ContentType.PDF,fileName);
  PowerMock.verifyAll();
}
 

Example 41

From project GeoBI, under directory /webapp/src/main/java/com/c2c/controller/.

Source file: GetBaseLayer.java

  17 
vote

private void renderMap(HttpServletResponse response,FeatureCollection feat,ReferencedEnvelope bounds,Rectangle imageSize,String format) throws IOException {
  MapLayer[] layers={new MapLayer(feat,baseStyle)};
  MapContext map=new DefaultMapContext(layers,bounds.getCoordinateReferenceSystem());
  try {
    GTRenderer renderer=new StreamingRenderer();
    renderer.setContext(map);
    BufferedImage image=new BufferedImage(imageSize.width,imageSize.height,BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics=image.createGraphics();
    graphics.setBackground(new Color(0xd6e4f1));
    graphics.clearRect(0,0,imageSize.width,imageSize.height);
    try {
      if (feat.getSchema().getGeometryDescriptor() == null) {
        graphics.setColor(Color.BLACK);
        int y=imageSize.height / 2;
        Font font=new Font(Font.SERIF,Font.BOLD,14);
        graphics.setFont(font);
        graphics.drawString("Results have no geometries",10,y - 14);
      }
 else {
        renderer.paint(graphics,imageSize,bounds);
      }
      ServletOutputStream output=response.getOutputStream();
      try {
        ImageIO.write(image,format,output);
      }
  finally {
        output.close();
      }
    }
  finally {
      graphics.dispose();
    }
  }
  finally {
    map.dispose();
  }
}
 

Example 42

From project Guit, under directory /src/main/java/com/guit/server/crawling/.

Source file: CrawlingFilter.java

  17 
vote

@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  HttpServletRequest r=(HttpServletRequest)request;
  String query=r.getQueryString();
  if (query == null || !query.contains("_escaped_fragment_=")) {
    chain.doFilter(request,response);
  }
 else {
    String reqUrl=r.getRequestURL().toString();
    String queryString=r.getQueryString();
    if (queryString != null) {
      reqUrl+="?" + queryString;
    }
    URL fetchUrl=new URL(snapshootService + "/ajaxcrawler?url=" + URLEncoder.encode(reqUrl,"UTF-8"));
    response.setContentType("text/html");
    response.setCharacterEncoding("ISO-8859-1");
    ServletOutputStream out=response.getOutputStream();
    InputStream in=fetchUrl(fetchUrl);
    if (in == null) {
      out.print("<html><head></head><body></body></html>");
      return;
    }
    final byte[] bytes=new byte[4096];
    int bytesRead=in.read(bytes);
    while (bytesRead > -1) {
      out.write(bytes,0,bytesRead);
      bytesRead=in.read(bytes);
    }
  }
}
 

Example 43

From project http-testing-harness, under directory /server-provider/src/main/java/org/sonatype/tests/http/server/jetty/behaviour/.

Source file: Deliver.java

  17 
vote

public boolean execute(HttpServletRequest request,HttpServletResponse response,Map<Object,Object> ctx) throws Exception {
  if (file == null) {
    String path=BehaviourHelper.content(request.getPathInfo());
    file=new File(path);
  }
  ServletOutputStream out=response.getOutputStream();
  FileInputStream in=null;
  try {
    response.setContentLength((int)file.length());
    in=new FileInputStream(file);
    int read=-1;
    byte[] buf=new byte[16000];
    while ((read=in.read(buf)) != -1) {
      out.write(buf,0,read);
    }
  }
  finally {
    if (in != null) {
      in.close();
    }
    out.close();
  }
  return false;
}
 

Example 44

From project iserve, under directory /iserve-parent/iserve-sal-gwt/src/main/java/uk/ac/open/kmi/iserve/sal/gwt/server/servlets/.

Source file: DownloadFileServlet.java

  17 
vote

protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  String format=request.getParameter("format");
  String uri=request.getParameter("uri");
  String content="";
  try {
    if (format.equalsIgnoreCase("xml")) {
      content=serviceManager.getService(uri,Syntax.RdfXml);
    }
 else     if (format.equalsIgnoreCase("nt")) {
      content=serviceManager.getService(uri,Syntax.Ntriples);
    }
 else     if (format.equalsIgnoreCase("trig")) {
      content=serviceManager.getService(uri,Syntax.Trig);
    }
 else     if (format.equalsIgnoreCase("trix")) {
      content=serviceManager.getService(uri,Syntax.Trix);
    }
 else     if (format.equalsIgnoreCase("ttl")) {
      content=serviceManager.getService(uri,Syntax.Turtle);
    }
  }
 catch (  ServiceException e) {
    throw new ServletException(e);
  }
  ServletOutputStream op=response.getOutputStream();
  response.setContentType("application/octet-stream");
  response.setHeader("Pragma","public");
  response.setHeader("Cache-Control","must-revalidate");
  response.setHeader("Content-Disposition","Attachment;Filename=\"" + "export." + format.toLowerCase() + "\"");
  op.write(content.getBytes(),0,content.getBytes().length);
  op.flush();
  op.close();
}
 

Example 45

From project jagger, under directory /chassis/coordinator.http/src/main/java/com/griddynamics/jagger/coordinator/http/server/.

Source file: ServletUtil.java

  17 
vote

public static void sendResponse(HttpServletResponse response,String body){
  BufferedWriter bufferedWriter=null;
  try {
    ServletOutputStream outputStream=response.getOutputStream();
    bufferedWriter=new BufferedWriter(new OutputStreamWriter(outputStream));
    bufferedWriter.write(body);
  }
 catch (  IOException e) {
    throw Throwables.propagate(e);
  }
 finally {
    if (bufferedWriter != null) {
      try {
        bufferedWriter.close();
      }
 catch (      IOException e) {
      }
    }
  }
}
 

Example 46

From project jahspotify, under directory /web/src/main/java/jahspotify/web/api/.

Source file: HistoryController.java

  17 
vote

public void serializeHistoryCursor(Collection<TrackHistory> historyCursor,HttpServletResponse httpServletResponse){
  try {
    final ServletOutputStream httpOutputStream=httpServletResponse.getOutputStream();
    final BufferedWriter outputStream=new BufferedWriter(new OutputStreamWriter(httpOutputStream));
    outputStream.write("{");
    outputStream.write("\"count\":");
    outputStream.write("" + historyCursor.size());
    if (historyCursor.size() > 0) {
      Gson gson=new Gson();
      outputStream.write(",");
      outputStream.write("\"tracks\":[");
      for (Iterator<TrackHistory> iterator=historyCursor.iterator(); iterator.hasNext(); ) {
        TrackHistory next=iterator.next();
        outputStream.write(gson.toJson(toWebTrack(next)));
        if (iterator.hasNext()) {
          outputStream.write(",");
        }
        outputStream.flush();
      }
      outputStream.write("]");
    }
    outputStream.write("}");
    outputStream.flush();
    outputStream.close();
    httpOutputStream.close();
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 47

From project jAPS2, under directory /src/com/agiletec/plugins/jacms/aps/servlet/.

Source file: ResourceWardenServlet.java

  17 
vote

private void createResponse(HttpServletResponse resp,ResourceInterface resource,ResourceInstance instance) throws IOException, ServletException {
  resp.setContentType(instance.getMimeType());
  resp.setHeader("Content-Disposition","inline; filename=" + instance.getFileName());
  ServletOutputStream out=resp.getOutputStream();
  try {
    File fileTemp=new File(resource.getDiskFolder() + instance.getFileName());
    if (fileTemp.exists()) {
      InputStream is=new FileInputStream(fileTemp);
      byte[] buffer=new byte[8789];
      int length=-1;
      while ((length=is.read(buffer)) != -1) {
        out.write(buffer,0,length);
        out.flush();
      }
      is.close();
    }
  }
 catch (  Throwable t) {
    throw new ServletException("Errore in erogazione risorsa protetta",t);
  }
 finally {
    out.close();
  }
}
 

Example 48

From project jboss-servlet-api_spec, under directory /src/main/java/javax/servlet/http/.

Source file: HttpServlet.java

  17 
vote

/** 
 * Called by the server (via the <code>service</code> method) to allow a servlet to handle a TRACE request. A TRACE returns the headers sent with the TRACE request to the client, so that they can be used in debugging. There's no need to override this method. 
 * @param req	the {@link HttpServletRequest} object thatcontains the request the client made of the servlet
 * @param resp	the {@link HttpServletResponse} object thatcontains the response the servlet returns to the client				
 * @exception IOException	if an input or output error occurswhile the servlet is handling the TRACE request
 * @exception ServletException	if the request for theTRACE cannot be handled
 */
protected void doTrace(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  int responseLength;
  String CRLF="\r\n";
  String responseString="TRACE " + req.getRequestURI() + " "+ req.getProtocol();
  Enumeration<String> reqHeaderEnum=req.getHeaderNames();
  while (reqHeaderEnum.hasMoreElements()) {
    String headerName=reqHeaderEnum.nextElement();
    responseString+=CRLF + headerName + ": "+ req.getHeader(headerName);
  }
  responseString+=CRLF;
  responseLength=responseString.length();
  resp.setContentType("message/http");
  resp.setContentLength(responseLength);
  ServletOutputStream out=resp.getOutputStream();
  out.print(responseString);
}
 

Example 49

From project jbossportletbridge, under directory /core/portletbridge-impl/src/main/java/org/jboss/portletbridge/context/flash/.

Source file: FlashHttpServletAdapter.java

  17 
vote

@Override public ServletOutputStream getOutputStream() throws IOException {
  return new ServletOutputStream(){
    @Override public void write(    int bytes) throws IOException {
      if (wrapped instanceof MimeResponse) {
        ((MimeResponse)wrapped).getPortletOutputStream().write(bytes);
      }
    }
  }
;
}
 

Example 50

From project jfreechart-plugin, under directory /src/main/java/hudson/util/.

Source file: Graph.java

  17 
vote

/** 
 * Renders a graph.
 */
public void doPng(StaplerRequest req,StaplerResponse rsp) throws IOException {
  if (req.checkIfModified(timestamp,rsp))   return;
  try {
    BufferedImage image=render(req,null);
    rsp.setContentType("image/png");
    ServletOutputStream os=rsp.getOutputStream();
    ImageIO.write(image,"PNG",os);
    os.close();
  }
 catch (  Error e) {
    if (e.getMessage().contains("Probable fatal error:No fonts found")) {
      rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
      return;
    }
    throw e;
  }
catch (  HeadlessException e) {
    rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
  }
}
 

Example 51

From project jsf-test, under directory /stage/src/main/java/org/jboss/test/faces/staging/.

Source file: StaticServlet.java

  17 
vote

@Override protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  InputStream inputStream=getServletContext().getResourceAsStream(req.getPathInfo());
  if (null != inputStream) {
    String fileName=req.getServletPath();
    String mimeType=getServletContext().getMimeType(fileName);
    if (null == mimeType) {
      mimeType="text/plain";
    }
    resp.setContentType(mimeType);
    ServletOutputStream outputStream=resp.getOutputStream();
    int c;
    while ((c=inputStream.read()) > 0) {
      outputStream.write(c);
    }
    inputStream.close();
    outputStream.close();
  }
 else {
    resp.sendError(404,"not found");
  }
}
 

Example 52

From project Karaf-Tutorial, under directory /cxf/personservice/webui/src/main/java/net/lr/tutorial/karaf/cxf/personservice/webui/.

Source file: PersonServlet.java

  17 
vote

@Override protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  ServletOutputStream os=resp.getOutputStream();
  Person[] persons=personService.getAll();
  os.println("<html><body>");
  os.println("<h2>Persons</h2>");
  os.println("<table>");
  os.println("<tr><th>Id</th><th>Name</th><th>URL</th></tr>");
  for (  Person person : persons) {
    String url=(person.getUrl() == null) ? "" : person.getUrl();
    os.println(String.format("<tr><td>%s</td><td>%s</td><td>%s</td></tr>",person.getId(),person.getName(),url));
  }
  os.println("</table>");
  os.println("<h2>Add Person</h2>");
  os.println("<form name='input' action='/personui' method='post'>");
  os.println("<table>");
  os.println("<tr><td>Id</td><td><input type='text' name='id'/></td></tr>");
  os.println("<tr><td>Name</td><td><input type='text' name='name'/></td></tr>");
  os.println("<tr><td>Homepage URL</td><td><input type='text' name='url'/></td></tr>");
  os.println("<tr><td colspan='2'><input type='submit' value='Add'/></td></tr>");
  os.println("</form>");
  os.println("</table>");
  os.println("</body></html>");
}
 

Example 53

From project logprocessing, under directory /ui/src/java/com/geminimobile/web/.

Source file: DownloadCSVController.java

  17 
vote

@Override protected ModelAndView handleRequestInternal(HttpServletRequest request,HttpServletResponse response) throws Exception {
  String msisdn=(String)request.getParameter("msisdn");
  String startTime=(String)request.getParameter("starttime");
  String endTime=(String)request.getParameter("endtime");
  String market=(String)request.getParameter("market");
  String type=(String)request.getParameter("type");
  Date toDate=SearchCommand.m_sdf.parse(endTime);
  Date fromDate=SearchCommand.m_sdf.parse(startTime);
  CDRDataAccess cdrAccess=new CDRDataAccess();
  Vector<CDREntry> cdrs=cdrAccess.getCDRsByMSISDN(msisdn,fromDate.getTime(),toDate.getTime(),market,type,100000);
  StringBuffer sb=new StringBuffer();
  sb.append("Date/Time,Market,Type,MSISDN,MO IP address,MT IP Address,Sender Domain,Recipient Domain\n");
  for (  CDREntry entry : cdrs) {
    sb.append(entry.getDisplayTimestamp() + "," + entry.getMarket()+ ","+ entry.getType()+ ","+ entry.getMsisdn()+ ","+ entry.getMoIPAddress()+ ","+ entry.getMtIPAddress()+ ","+ entry.getSenderDomain()+ ","+ entry.getRecipientDomain()+ "\n");
  }
  String csvString=sb.toString();
  response.setBufferSize(sb.length());
  response.setContentLength(sb.length());
  response.setContentType("text/plain; charset=UTF-8");
  response.setHeader("Content-Disposition","attachment; filename=" + "cdrResults.csv" + ";");
  ServletOutputStream os=response.getOutputStream();
  os.write(csvString.getBytes());
  os.flush();
  os.close();
  return null;
}
 

Example 54

From project Mail-Pigeon, under directory /pigeon-web/src/main/java/com/trivago/mail/pigeon/web/.

Source file: TrackingServlet.java

  17 
vote

@Override protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  String userId=req.getParameter("user_id");
  String newsletterId=req.getParameter("newsletter_id");
  if (userId != null && newsletterId != null) {
    final GraphDatabaseService database=ConnectionFactory.getDatabase();
    Node newsletterNode=ConnectionFactory.getNewsletterIndex().get(IndexTypes.NEWSLETTER_ID,newsletterId).getSingle();
    Node userNode=ConnectionFactory.getUserIndex().get(IndexTypes.USER_ID,userId).getSingle();
    if (newsletterNode != null && userNode != null) {
      final Transaction transaction=database.beginTx();
      try {
        if (!userNode.hasRelationship(RelationTypes.OPENED,Direction.OUTGOING)) {
          userNode.createRelationshipTo(newsletterNode,RelationTypes.OPENED);
        }
 else {
          boolean found=false;
          for (          Relationship rel : userNode.getRelationships(RelationTypes.OPENED)) {
            if (rel.getEndNode().equals(newsletterNode)) {
              found=true;
            }
          }
          if (!found) {
            userNode.createRelationshipTo(newsletterNode,RelationTypes.OPENED);
          }
        }
        transaction.success();
      }
 catch (      Exception e) {
        transaction.failure();
      }
 finally {
        transaction.finish();
      }
    }
  }
  resp.setContentType("image/gif");
  byte[] emptyGif=new byte[]{0x47,0x49,0x46,0x38,0x39,0x61,0x01,0x00,0x01,0x00,(byte)0xf0,0x01,0x00,(byte)0xff,(byte)0xff,(byte)0xff,0x00,0x00,0x00,0x21,(byte)0xf9,0x04,0x01,0x0a,0x00,0x00,0x00,0x2c,0x00,0x00,0x00,0x00,0x01,0x00,0x01,0x00,0x00,0x02,0x02,0x44,0x01,0x00,0x3b};
  resp.setContentLength(emptyGif.length);
  ServletOutputStream out=resp.getOutputStream();
  out.write(emptyGif);
}
 

Example 55

From project MEditor, under directory /editor-webapp/src/main/java/cz/mzk/editor/server/.

Source file: DownloadFoxmlServlet.java

  17 
vote

@Override protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  String uuid=req.getParameterValues(Constants.PARAM_UUID)[0];
  String datastream=null;
  if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) {
    resp.addHeader("Content-Disposition","attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_local_version.foxml\"");
  }
 else {
    datastream=req.getParameterValues(Constants.PARAM_DATASTREAM)[0];
    resp.addHeader("Content-Disposition","attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_local_version_"+ datastream+ ".xml\"");
  }
  String xmlContent=URLDecoder.decode(req.getParameterValues(Constants.PARAM_CONTENT)[0],"UTF-8");
  InputStream is=new ByteArrayInputStream(xmlContent.getBytes("UTF-8"));
  ServletOutputStream os=resp.getOutputStream();
  IOUtils.copyStreams(is,os);
  os.flush();
}
 

Example 56

From project mgwt, under directory /src/main/java/com/googlecode/mgwt/linker/server/.

Source file: Html5ManifestServletBase.java

  17 
vote

public void serveStringManifest(HttpServletRequest req,HttpServletResponse resp,String manifest) throws ServletException {
  resp.setHeader("Cache-Control","no-cache");
  resp.setHeader("Pragma","no-cache");
  resp.setDateHeader("Expires",new Date().getTime());
  resp.setContentType("text/cache-manifest");
  try {
    InputStream is=new ByteArrayInputStream(manifest.getBytes("UTF-8"));
    ServletOutputStream os=resp.getOutputStream();
    byte[] buffer=new byte[1024];
    int bytesRead;
    while ((bytesRead=is.read(buffer)) != -1) {
      os.write(buffer,0,bytesRead);
    }
    return;
  }
 catch (  UnsupportedEncodingException e) {
    log("can not write manifest to output stream",e);
    throw new ServletException("can not write manifest to output stream",e);
  }
catch (  IOException e) {
    log("can not write manifest to output stream",e);
    throw new ServletException("can not write manifest to output stream",e);
  }
}
 

Example 57

From project nuxeo-services, under directory /nuxeo-platform-web-common/src/test/java/org/nuxeo/ecm/platform/web/requestcontroller/filter/.

Source file: TestBufferingServletResponse.java

  17 
vote

public ResponseProxy(final OutputStream out){
  sout=new ServletOutputStream(){
    @Override public void write(    int b) throws IOException {
      out.write(b);
    }
  }
;
}
 

Example 58

From project OpenReports, under directory /src/org/efs/openreports/actions/admin/.

Source file: DataExportAction.java

  17 
vote

public String execute(){
  try {
    if (!submitOk) {
      reports=reportProvider.getReports();
      return SUCCESS;
    }
    XStream xStream=new XStream();
    xStream.omitField(BasicDataSource.class,"logWriter");
    xStream.omitField(Report.class,"id");
    xStream.omitField(ReportAlert.class,"id");
    xStream.omitField(ReportChart.class,"id");
    xStream.omitField(ReportParameter.class,"id");
    xStream.omitField(ReportExportOption.class,"id");
    List<Report> selectedReports=new ArrayList<Report>();
    for (int i=0; i < reportIds.length; i++) {
      Report report=reportProvider.getReport(new Integer(reportIds[i]));
      selectedReports.add(report);
    }
    HttpServletResponse response=ServletActionContext.getResponse();
    response.setHeader("Content-disposition","inline; filename=or-report-export.xml");
    response.setContentType("application/xml");
    ServletOutputStream outputStream=response.getOutputStream();
    xStream.toXML(selectedReports,outputStream);
    outputStream.flush();
    outputStream.close();
    return NONE;
  }
 catch (  Exception e) {
    addActionError(e.toString());
    return INPUT;
  }
}
 

Example 59

From project picketbox-http, under directory /src/test/java/org/picketbox/test/http/.

Source file: TestServletResponse.java

  17 
vote

public ServletOutputStream getOutputStream() throws IOException {
  bos.flush();
  return new ServletOutputStream(){
    @Override public void write(    int b) throws IOException {
      bos.write(b);
    }
  }
;
}
 

Example 60

From project platform_3, under directory /rack/src/test/java/com/proofpoint/rack/.

Source file: TestRackServlet.java

  17 
vote

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

Example 61

From project scooter, under directory /source/src/com/scooterframework/web/controller/.

Source file: ContentHandlerHelper.java

  17 
vote

/** 
 * Sends content bytes to the requestor.  Default <tt>mimeType</tt> is <tt>application/octet-stream</tt>.
 * @param response  The HTTP response object.
 * @param content  The content to be sent.
 * @param mimeType  The content MIME type.
 * @throws IOException
 * @throws ServletException
 */
public static void publish(HttpServletResponse response,byte[] content,String mimeType) throws IOException, ServletException {
  String encoding=response.getCharacterEncoding();
  if (encoding == null)   encoding="utf-8";
  if (mimeType == null || "".equals(mimeType))   mimeType="application/octet-stream";
  mimeType=mimeType.toLowerCase();
  if (mimeType.indexOf("charset") == -1) {
    response.setContentType(mimeType + "; charset=" + encoding);
  }
 else {
    response.setContentType(mimeType);
  }
  response.setContentLength(content.length);
  response.setStatus(HttpServletResponse.SC_OK);
  ServletOutputStream out=response.getOutputStream();
  out.write(content);
  out.close();
}
 

Example 62

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

Source file: Generate.java

  17 
vote

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;
}
 

Example 63

From project teatrove, under directory /teaservlet/src/main/java/org/teatrove/teaservlet/.

Source file: TeaServlet.java

  17 
vote

/** 
 * Inserts a plugin to expose parts of the teaservlet via the  EngineAccess interface. private void createEngineAccessPlugin(PluginContext context) { Plugin engineAccess = new EngineAccessPlugin(this); context.addPlugin(engineAccess); context.addPluginListener(engineAccess); }
 */
private boolean processResource(ApplicationRequest appRequest,ApplicationResponse appResponse) throws IOException {
  String context=appRequest.getContextPath();
  String requestURI=appRequest.getRequestURI();
  if (requestURI.startsWith(context)) {
    requestURI=requestURI.substring(context.length());
  }
  Asset asset=getEngine().getAssetEngine().getAsset(requestURI);
  if (asset == null) {
    return false;
  }
  appResponse.setContentType(asset.getMimeType());
  int read=-1;
  byte[] contents=new byte[1024];
  InputStream input=asset.getInputStream();
  ServletOutputStream output=appResponse.getOutputStream();
  while ((read=input.read(contents)) >= 0) {
    output.write(contents,0,read);
  }
  appResponse.finish();
  return true;
}
 

Example 64

From project tempo, under directory /ui-fw/src/main/java/org/intalio/tempo/uiframework/export/.

Source file: ExternalTasksServlet.java

  17 
vote

@Override protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  try {
    TokenClient tc=Configuration.getInstance().getTokenClient();
    String rtoken=request.getParameter("token");
    String pToken;
    String user;
    if (rtoken != null) {
      Property[] properties=tc.getTokenProperties(rtoken);
      user=PropertyUtils.getProperty(properties,AuthenticationConstants.PROPERTY_USER).getValue().toString();
      pToken=rtoken;
    }
 else {
      ApplicationState state=ApplicationState.getCurrentInstance(new HttpServletRequestWrapper(request));
      User currentUser=state.getCurrentUser();
      pToken=currentUser.getToken();
      user=currentUser.getName();
    }
    TasksCollector collector=new TasksCollector(new HttpServletRequestWrapper(request),user,pToken);
    tasks=collector.retrieveTasks();
    ServletOutputStream outputStream=response.getOutputStream();
    String filename="tasks for " + user + getFileExt();
    response.setContentType(getFileMimeType());
    response.addHeader("Content-disposition","attachment; filename=\"" + filename + "\"");
    generateFile(request,pToken,user,outputStream);
  }
 catch (  Exception e) {
    throw new ServletException(e);
  }
}
 

Example 65

From project tvguide-sample-parent, under directory /tvguide-client/src/main/java/com/acme/gwt/server/.

Source file: HomepageServlet.java

  17 
vote

@Override protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  ServletOutputStream out=resp.getOutputStream();
  resp.setDateHeader("Expires",new Date().getTime() + 60);
  out.println("<!doctype html>");
  out.println("<html>");
  out.println("<head>");
  out.println("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
  out.println("<title>GWT TV Guide Sample</title>");
  out.println("<script type=\"text/javascript\" language=\"javascript\" src=\"tvguide/tvguide.nocache.js\"></script>");
  out.println("<script type=\"text/javascript\">var store = '" + auth.getViewerAsJson() + "';</script>");
  out.println("<body>");
  out.println("<iframe src=\"javascript:''\" id=\"__gwt_historyFrame\" tabIndex='-1' style=\"position:absolute;width:0;height:0;border:0\"></iframe>");
  out.println("</body>");
  out.println("</html>");
}
 

Example 66

From project undertow, under directory /servlet/src/main/java/io/undertow/servlet/handlers/.

Source file: DefaultServlet.java

  17 
vote

@Override protected void doGet(final HttpServletRequest req,final HttpServletResponse resp) throws ServletException, IOException {
  final String path=getPath(req);
  if (!isAllowed(path)) {
    resp.setStatus(404);
    return;
  }
  ServletOutputStream out=null;
  final File resource=deployment.getDeploymentInfo().getResourceLoader().getResource(path);
  if (resource == null) {
    resp.setStatus(404);
    return;
  }
 else   if (resource.isDirectory()) {
    handleWelcomePage(req,resp,resource);
  }
 else {
    InputStream in=new BufferedInputStream(new FileInputStream(resource));
    try {
      int read;
      final byte[] buffer=new byte[1024];
      out=resp.getOutputStream();
      while ((read=in.read(buffer)) != -1) {
        out.write(buffer,0,read);
      }
    }
  finally {
      if (out != null) {
        IoUtils.safeClose(out);
      }
      IoUtils.safeClose(in);
    }
  }
}
 

Example 67

From project visural-common, under directory /src/main/java/com/visural/common/cache/inspector/.

Source file: CacheInspectorFilter.java

  17 
vote

public void doFilter(ServletRequest sr,ServletResponse sr1,FilterChain fc) throws IOException, ServletException {
  HttpServletRequest req=(HttpServletRequest)sr;
  HttpServletResponse res=(HttpServletResponse)sr1;
  if (req.getServletPath().startsWith(filterPath)) {
    res.setContentType("text/html");
    ServletOutputStream out=res.getOutputStream();
    if (module == null || module.get() == null) {
      out.write("No CacheModule has been registered with CacheInspectorFilter.class".getBytes());
      out.close();
    }
 else {
      StringTemplate t=htmlTemplate.getInstanceOf();
      Map<String,Map<String,CacheStatsAggregated>> stats=module.get().getStatistics(true);
      Map<CacheClass,List<StatEntry>> classes=new HashMap();
      for (      Entry<String,Map<String,CacheStatsAggregated>> e : stats.entrySet()) {
        List<StatEntry> methods=new ArrayList();
        classes.put(new CacheClass(e.getKey()),methods);
        for (        Entry<String,CacheStatsAggregated> s : e.getValue().entrySet()) {
          String methodName=s.getKey();
          Pattern p=Pattern.compile(".+" + Pattern.quote(e.getKey()) + "\\.(.+)\\(");
          Matcher m=p.matcher(s.getKey());
          if (m.find()) {
            methodName=m.group(1);
          }
          methods.add(new StatEntry(s.getKey().replace(e.getKey() + ".",""),methodName,s.getValue(),methods.size() % 2 == 0 ? "a" : "b"));
        }
      }
      t.setAttribute("classes",classes);
      t.setAttribute("server",req.getServerName() + ":" + req.getServerPort()+ req.getContextPath());
      out.write(t.toString().getBytes());
      out.close();
    }
  }
 else {
    fc.doFilter(sr,sr1);
  }
}
 

Example 68

From project vmarket, under directory /src/main/java/org/apache/velocity/servlet/.

Source file: VelocityServlet.java

  17 
vote

/** 
 * merges the template with the context.  Only override this if you really, really really need to. (And don't call us with questions if it breaks :)
 * @param template template object returned by the handleRequest() method
 * @param context  context created by the createContext() method
 * @param response servlet reponse (use this to get the output stream or Writer
 * @throws ResourceNotFoundException
 * @throws ParseErrorException
 * @throws MethodInvocationException
 * @throws IOException
 * @throws UnsupportedEncodingException
 * @throws Exception
 */
protected void mergeTemplate(Template template,Context context,HttpServletResponse response) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException, UnsupportedEncodingException, Exception {
  ServletOutputStream output=response.getOutputStream();
  VelocityWriter vw=null;
  String encoding=response.getCharacterEncoding();
  try {
    vw=(VelocityWriter)writerPool.get();
    if (vw == null) {
      vw=new VelocityWriter(new OutputStreamWriter(output,encoding),4 * 1024,true);
    }
 else {
      vw.recycle(new OutputStreamWriter(output,encoding));
    }
    template.merge(context,vw);
  }
  finally {
    if (vw != null) {
      try {
        vw.flush();
      }
 catch (      IOException e) {
      }
      vw.recycle(null);
      writerPool.put(vw);
    }
  }
}
 

Example 69

From project vraptor, under directory /vraptor-core/src/test/java/br/com/caelum/vraptor/interceptor/download/.

Source file: ByteArrayDownloadTest.java

  17 
vote

@Before public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  bytes=new byte[]{(byte)0};
  this.outputStream=new ByteArrayOutputStream();
  this.socketStream=new ServletOutputStream(){
    public void write(    int b) throws IOException {
      outputStream.write(b);
    }
  }
;
  when(response.getOutputStream()).thenReturn(socketStream);
}
 

Example 70

From project zanata, under directory /zanata-war/src/main/java/org/zanata/action/.

Source file: ConfigurationAction.java

  17 
vote

public void getData(){
  HttpServletResponse response=(HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
  response.setContentType("application/xml");
  response.addHeader("Content-disposition","attachment; filename=\"" + this.configurationServiceImpl.getConfigurationFileName() + "\"");
  response.setCharacterEncoding("UTF-8");
  try {
    ServletOutputStream os=response.getOutputStream();
    os.write(this.configurationServiceImpl.getConfigurationFileContents(this.projectSlug,this.iterationSlug,null).getBytes());
    os.flush();
    os.close();
    FacesContext.getCurrentInstance().responseComplete();
  }
 catch (  Exception e) {
    log.error("Failure : " + e.toString() + "\n");
  }
}
 

Example 71

From project zen-project, under directory /zen-webservice/src/main/java/com/nominanuda/springmvc/.

Source file: HtmlSaxPageViewResolver.java

  17 
vote

public ServletOutputStream getOutputStream() throws IOException {
  return new ServletOutputStream(){
    public void write(    int b) throws IOException {
      baos.write(b);
    }
    public void write(    byte[] b,    int off,    int len) throws IOException {
      baos.write(b,off,len);
    }
    public void write(    byte[] b) throws IOException {
      baos.write(b);
    }
  }
;
}
 

Example 72

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/servlet/filter/.

Source file: AbstractGZIPFilter.java

  16 
vote

/** 
 * Creates output stream with GZIP delegation.
 * @return servlet output stream
 * @throws IOException io exception
 */
private ServletOutputStream createOutputStream() throws IOException {
  final ServletResponse servletResponse=this.getResponse();
  gzipStream=new GZIPOutputStream(servletResponse.getOutputStream());
  return new ServletOutputStream(){
    @Override public void write(    final int b) throws IOException {
      gzipStream.write(b);
    }
    @Override public void flush() throws IOException {
      gzipStream.flush();
    }
    @Override public void close() throws IOException {
      gzipStream.close();
    }
    @Override public void write(    final byte[] b) throws IOException {
      gzipStream.write(b);
    }
    @Override public void write(    final byte[] b,    final int off,    final int len) throws IOException {
      gzipStream.write(b,off,len);
    }
  }
;
}
 

Example 73

From project Blitz, under directory /src/com/laxser/blitz/web/portal/impl/.

Source file: WindowResponse.java

  16 
vote

@Override public ServletOutputStream getOutputStream() throws IOException {
  if (out == null) {
    this.out=new ServletOutputStream(){
      ByteArrayOutputStream baos=new ByteArrayOutputStream(getBufferSize());
      @Override public void write(      int b) throws IOException {
        baos.write(b);
      }
      @Override public void flush() throws IOException {
        byte[] bytes=baos.toByteArray();
        baos.reset();
        window.appendContent(new String(bytes,getCharacterEncoding()));
      }
    }
;
  }
  return out;
}
 

Example 74

From project OpenID-Connect-Java-Spring-Server, under directory /openid-connect-server/src/test/java/org/mitre/openid/connect/view/.

Source file: X509CertificateViewTest.java

  16 
vote

/** 
 * Test method for  {@link org.mitre.openid.connect.view.X509CertificateView#renderMergedOutputModel(java.util.Map,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)}.
 * @throws IOException 
 * @throws NoSuchAlgorithmException 
 * @throws NoSuchFieldException 
 * @throws SecurityException 
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 */
@Test public void testRenderMergedOutputModelMapOfStringObjectHttpServletRequestHttpServletResponse() throws IOException, NoSuchAlgorithmException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
  X509CertificateView view=new X509CertificateView();
  Field field=view.getClass().getDeclaredField("config");
  field.setAccessible(true);
  field.set(view,config);
  Map<String,Object> model=createMock(Map.class);
  HttpServletRequest request=createMock(HttpServletRequest.class);
  HttpServletResponse response=createMock(HttpServletResponse.class);
  KeyPairGenerator generator=KeyPairGenerator.getInstance("RSA");
  KeyPair kp=generator.generateKeyPair();
  RsaSigner rsaSigner=new RsaSigner(JwsAlgorithm.RS256.getJwaName(),kp.getPublic(),kp.getPrivate());
  Map<String,JwtSigner> signers=new HashMap<String,JwtSigner>();
  signers.put("rsa1",rsaSigner);
  expect(model.get("signers")).andReturn(signers);
  expect(response.getOutputStream()).andReturn(new ServletOutputStream(){
    public void write(    int b) throws IOException {
    }
  }
);
  response.setContentType("application/x-pem-file");
  expectLastCall();
  replay(model);
  replay(request);
  replay(response);
  view.renderMergedOutputModel(model,request,response);
}
 

Example 75

From project pluto, under directory /pluto-container/src/main/java/org/apache/pluto/container/impl/.

Source file: HttpServletPortletResponseWrapper.java

  16 
vote

@Override public ServletOutputStream getOutputStream() throws IOException {
  if (servletOutputStream == null) {
    outputStream=mimeResponse != null ? mimeResponse.getPortletOutputStream() : DummyServletOutputStream.getInstance();
    if (outputStream instanceof ServletOutputStream) {
      servletOutputStream=(ServletOutputStream)outputStream;
    }
 else {
      servletOutputStream=new ServletOutputStream(){
        @Override public void write(        int b) throws IOException {
          outputStream.write(b);
        }
      }
;
    }
  }
  return servletOutputStream;
}
 

Example 76

From project sandbox_2, under directory /wicket-portlet/src/main/java/org/apache/wicket/protocol/http/portlet/.

Source file: WicketResponseState.java

  16 
vote

public ServletOutputStream getOutputStream() throws IOException {
  if (isStateAwareResponse) {
    return null;
  }
  if (outputStream == null) {
    if (printWriter != null) {
      throw new IllegalStateException("getWriter() has already been called on this response");
    }
    byteOutputBuffer=new ByteArrayOutputStream();
    outputStream=new ServletOutputStream(){
      @Override public void write(      int b) throws IOException {
        if (!closed) {
          byteOutputBuffer.write(b);
          if (contentLength > -1 && byteOutputBuffer.size() >= contentLength) {
            committed=true;
            closed=true;
          }
        }
      }
    }
;
  }
  return outputStream;
}
 

Example 77

From project skalli, under directory /org.eclipse.skalli.view.test/src/main/java/org/eclipse/skalli/view/internal/servlet/.

Source file: ResourceServletTest.java

  16 
vote

@Test public void testDoGet() throws Exception {
  HttpServletRequest mockRequest=createMock(HttpServletRequest.class);
  HttpServletResponse mockResponse=createMock(HttpServletResponse.class);
  Object[] mocks=new Object[]{mockRequest,mockResponse};
  ResourceServlet servlet=new ResourceServlet();
  reset(mocks);
  mockRequest.getPathInfo();
  expectLastCall().andReturn("/widgetsets/com.vaadin.terminal.gwt.DefaultWidgetSet/hosted.html");
  mockResponse.getOutputStream();
  expectLastCall().andReturn(new ServletOutputStream(){
    @Override public void write(    int b) throws IOException {
      written=true;
    }
  }
);
  replay(mocks);
  servlet.doGet(mockRequest,mockResponse);
  Assert.assertTrue(written);
  verify(mocks);
}
 

Example 78

From project sparsemapcontent, under directory /extensions/proxy/src/test/java/uk/co/tfd/sm/proxy/.

Source file: ProxyServletVivoMan.java

  16 
vote

@Test public void testVivoFeed() throws Exception {
  when(request.getPathInfo()).thenReturn("/tests/vivo");
  when(request.getHeaderNames()).thenReturn(headerNames.elements());
  Map<String,String[]> requestParameters=ImmutableMap.of("id",new String[]{"n7934"});
  when(request.getParameterMap()).thenReturn(requestParameters);
  final ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
  when(response.getOutputStream()).thenReturn(new ServletOutputStream(){
    @Override public void write(    int v) throws IOException {
      byteArrayOutputStream.write(v);
    }
  }
);
  long s=System.currentTimeMillis();
  servlet.service(request,response);
  LOGGER.info("Took {} ",(System.currentTimeMillis() - s));
  verify(response,Mockito.atMost(0)).sendError(404);
  String output=byteArrayOutputStream.toString("UTF-8");
  LOGGER.info("Got Response {} ",output);
}
 

Example 79

From project spring-security-saml, under directory /saml2-core/src/test/java/org/springframework/security/saml/websso/.

Source file: WebSSOProfileHoKImplTest.java

  16 
vote

@Before public void initialize() throws Exception {
  String resName="/" + getClass().getName().replace('.','/') + ".xml";
  context=new ClassPathXmlApplicationContext(resName);
  profile=context.getBean("webSSOprofile",WebSSOProfile.class);
  metadata=context.getBean("metadata",MetadataManager.class);
  options=new WebSSOProfileOptions(null);
  request=createNiceMock(HttpServletRequest.class);
  response=createNiceMock(HttpServletResponse.class);
  output=new ServletOutputStream(){
    public void write(    int b) throws IOException {
    }
  }
;
  storage=createMock(SAMLMessageStorage.class);
  contextProvider=context.getBean("contextProvider",SAMLContextProviderImpl.class);
  ((SAMLContextProviderImpl)contextProvider).setStorageFactory(new StorageFactoryTestImpl(storage));
  expect(request.getContextPath()).andReturn("/");
  replyMock();
  samlContext=contextProvider.getLocalAndPeerEntity(request,response);
  samlContext.setInboundMessageTransport(new HttpServletRequestAdapter(request));
  samlContext.setOutboundMessageTransport(new HttpServletResponseAdapter(response,false));
  verifyMock();
  expect(response.getOutputStream()).andReturn(output).anyTimes();
}
 

Example 80

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

Source file: Webserver.java

  15 
vote

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

Example 81

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

Source file: DefaultServlet.java

  15 
vote

/** 
 * 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;
}
 

Example 82

From project arquillian-extension-warp, under directory /impl/src/main/java/org/jboss/arquillian/warp/impl/server/execution/.

Source file: NonWritingPrintWriter.java

  15 
vote

void finallyWriteAndClose(ServletOutputStream delegateStream) throws IOException {
  this.flush();
  baos.flush();
  byte[] byteArray=baos.toByteArray();
  delegateStream.write(byteArray);
  if (wasClosed) {
    super.close();
  }
}
 

Example 83

From project core_4, under directory /api/src/main/java/org/ajax4jsf/io/.

Source file: FastBufferWriter.java

  15 
vote

public void printTo(ServletOutputStream outputStream) throws IOException {
  CharBuffer b=firstBuffer;
  while (b != null) {
    outputStream.print(new String(b.getChars()));
    b=b.getNext();
  }
}
 

Example 84

From project Cours-3eme-ann-e, under directory /Java/tomcat/examples/WEB-INF/classes/compressionFilters/.

Source file: CompressionServletResponseWrapper.java

  15 
vote

/** 
 * Create and return a ServletOutputStream to write the content associated with this Response.
 * @exception IOException if an input/output error occurs
 */
public ServletOutputStream createOutputStream() throws IOException {
  if (debug > 1) {
    System.out.println("createOutputStream gets called");
  }
  CompressionResponseStream stream=new CompressionResponseStream(origResponse);
  stream.setDebugLevel(debug);
  stream.setBuffer(threshold);
  return stream;
}
 

Example 85

From project gatein-common, under directory /common/src/main/java/org/gatein/common/servlet/.

Source file: BufferingResponseWrapper.java

  15 
vote

public ServletOutputStream getOutputStream() throws IOException {
  if (writer != null) {
    throw new IllegalStateException("Already obtained a PrintWriter");
  }
  if (outputStream == null) {
    outputStream=new ServletOutputStreamBuffer(500);
  }
  return outputStream;
}
 

Example 86

From project IOCipherServer, under directory /src/Acme/Serve/.

Source file: Serve.java

  15 
vote

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

Example 87

From project jboss-as-quickstart, under directory /kitchensink-html5-mobile/src/main/java/org/jboss/as/quickstarts/html5_mobile/util/.

Source file: JSONPRequestFilter.java

  15 
vote

@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  if (!(request instanceof HttpServletRequest)) {
    throw new ServletException("Only HttpServletRequest requests are supported");
  }
  final HttpServletRequest httpRequest=(HttpServletRequest)request;
  final HttpServletResponse httpResponse=(HttpServletResponse)response;
  String callback=getCallbackMethod(httpRequest);
  if (!isJSONPRequest(callback)) {
    chain.doFilter(request,response);
  }
 else {
    if (!SAFE_PRN.matcher(callback).matches()) {
      throw new ServletException("JSONP Callback method '" + CALLBACK_METHOD + "' parameter not valid function");
    }
    final ByteArrayOutputStream byteStream=new ByteArrayOutputStream();
    HttpServletResponseWrapper responseWrapper=new HttpServletResponseWrapper(httpResponse){
      @Override public ServletOutputStream getOutputStream() throws IOException {
        return new ServletOutputStream(){
          @Override public void write(          int b) throws IOException {
            byteStream.write(b);
          }
        }
;
      }
      @Override public PrintWriter getWriter() throws IOException {
        return new PrintWriter(byteStream);
      }
    }
;
    chain.doFilter(request,responseWrapper);
    response.setContentType(CONTENT_TYPE);
    response.setCharacterEncoding("UTF-8");
    response.getOutputStream().write((callback + "(").getBytes());
    response.getOutputStream().write(byteStream.toByteArray());
    response.getOutputStream().write(");".getBytes());
  }
}
 

Example 88

From project logback, under directory /logback-access/src/main/java/ch/qos/logback/access/servlet/.

Source file: TeeHttpServletResponse.java

  15 
vote

@Override public ServletOutputStream getOutputStream() throws IOException {
  if (teeServletOutputStream == null) {
    teeServletOutputStream=new TeeServletOutputStream(this.getResponse());
  }
  return teeServletOutputStream;
}
 

Example 89

From project ncDiamond, under directory /src/compressionFilters/.

Source file: CompressionServletResponseWrapper.java

  15 
vote

/** 
 * Create and return a ServletOutputStream to write the content associated with this Response.
 * @exception IOException if an input/output error occurs
 */
public ServletOutputStream createOutputStream() throws IOException {
  if (debug > 1) {
    System.out.println("createOutputStream gets called");
  }
  CompressionResponseStream stream=new CompressionResponseStream(origResponse);
  stream.setDebugLevel(debug);
  stream.setBuffer(threshold);
  return stream;
}
 

Example 90

From project nuxeo-opensocial, under directory /nuxeo-opensocial-server/src/main/java/org/apache/shindig/gadgets/servlet/.

Source file: NXConcatProxyServlet.java

  15 
vote

@Override public ServletOutputStream getOutputStream() throws IOException {
  if (errorCode != SC_OK) {
    outputStream=new NullServletOutputStream();
  }
  if (outputStream == null) {
    outputStream=super.getOutputStream();
  }
  return outputStream;
}
 

Example 91

From project portlet-utils, under directory /portal-rest-api/src/main/java/org/jasig/portlet/utils/rest/.

Source file: SimpleCrossContextRestApiInvoker.java

  15 
vote

@Override public ServletOutputStream getOutputStream(){
  if (writer != null) {
    final String msg="The method HttpServletResponse.getWriter has " + "already been called;  call either getOutputStream or " + "getWriter, but not both";
    throw new IllegalStateException(msg);
  }
  outputStream=new ServletOutputStreamImpl();
  return outputStream;
}
 

Example 92

From project remitt, under directory /src/main/java/org/remitt/server/.

Source file: TestHarnessServlet.java

  15 
vote

public void parserTest(String parserClass,String input,ServletOutputStream out) throws IOException {
  X12Message p=null;
  try {
    p=(X12Message)Class.forName(parserClass).newInstance();
  }
 catch (  InstantiationException e) {
    log.error(e);
    out.println(e.toString());
    return;
  }
catch (  IllegalAccessException e) {
    log.error(e);
    out.println(e.toString());
    return;
  }
catch (  ClassNotFoundException e) {
    log.error(e);
    out.println(e.toString());
    return;
  }
  try {
    p.parse(input);
  }
 catch (  FormatException e) {
    log.error(e);
    out.println(e.toString());
    return;
  }
  out.println(p.toString());
}
 

Example 93

From project rewrite, under directory /impl-servlet/src/main/java/org/ocpsoft/rewrite/servlet/impl/.

Source file: HttpRewriteWrappedResponse.java

  15 
vote

@Override public ServletOutputStream getOutputStream(){
  if (outputStream == null) {
    if (isResponseContentIntercepted())     outputStream=new RewriteServletOutputStream(bufferedResponseContent);
 else {
      try {
        lockStreams();
        outputStream=super.getOutputStream();
      }
 catch (      IOException e) {
        throw new RewriteException("Could not get response output stream.",e);
      }
    }
    if (isResponseStreamWrapped()) {
      HttpServletRewrite event=new HttpBufferRewriteImpl(request,this);
      OutputStream wrapped=outputStream;
      for (      ResponseStreamWrapper wrapper : responseStreamWrappers) {
        wrapped=wrapper.wrap(event,wrapped);
      }
      outputStream=new RewriteServletOutputStream(wrapped);
    }
  }
  return outputStream;
}
 

Example 94

From project riot, under directory /cachius/src/org/riotfamily/cachius/http/.

Source file: CachiusResponse.java

  15 
vote

/** 
 * Returns an ServletOutputStream that writes into the OutputStream provided by the CacheItem. All output is redirected so nothing will be  sent to the client.
 * @throws IllegalStateException If getWriter() has been called before
 * @throws IOException
 */
public ServletOutputStream getOutputStream() throws IOException {
  if (writer != null) {
    throw new IllegalStateException();
  }
  if (outputStream == null) {
    outputStream=new DelegatingServletOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
  }
  return outputStream;
}
 

Example 95

From project rolefen, under directory /dependency/apache-tomcat-6.0.26/webapps/examples/WEB-INF/classes/compressionFilters/.

Source file: CompressionServletResponseWrapper.java

  15 
vote

/** 
 * Create and return a ServletOutputStream to write the content associated with this Response.
 * @exception IOException if an input/output error occurs
 */
public ServletOutputStream createOutputStream() throws IOException {
  if (debug > 1) {
    System.out.println("createOutputStream gets called");
  }
  CompressionResponseStream stream=new CompressionResponseStream(origResponse);
  stream.setDebugLevel(debug);
  stream.setBuffer(threshold);
  return stream;
}
 

Example 96

From project rollyourowncbf, under directory /apache-tomcat-6.0.32/webapps/examples/WEB-INF/classes/compressionFilters/.

Source file: CompressionServletResponseWrapper.java

  15 
vote

/** 
 * Create and return a ServletOutputStream to write the content associated with this Response.
 * @exception IOException if an input/output error occurs
 */
public ServletOutputStream createOutputStream() throws IOException {
  if (debug > 1) {
    System.out.println("createOutputStream gets called");
  }
  CompressionResponseStream stream=new CompressionResponseStream(origResponse);
  stream.setDebugLevel(debug);
  stream.setBuffer(threshold);
  return stream;
}
 

Example 97

From project sandbox, under directory /xwiki-portlet/src/main/java/org/xwiki/portlet/controller/.

Source file: DispatchedMimeResponse.java

  15 
vote

@Override public ServletOutputStream getOutputStream() throws IOException {
  if (isOutputIntercepted()) {
    if (writerWrapper == null) {
      if (outputStreamWrapper == null) {
        outputStreamWrapper=new ByteArrayServletOutputStream();
      }
      return outputStreamWrapper;
    }
 else {
      throw new IllegalStateException();
    }
  }
 else {
    outputPreserved=true;
    return super.getOutputStream();
  }
}
 

Example 98

From project seamless, under directory /mock/src/main/java/org/seamless/mock/http/.

Source file: MockHttpServletResponse.java

  15 
vote

public ServletOutputStream getOutputStream(){
  if (!this.outputStreamAccessAllowed) {
    throw new IllegalStateException("OutputStream access not allowed");
  }
  return this.outputStream;
}
 

Example 99

From project sparqled, under directory /recommendation-servlet/src/main/java/org/sindice/analytics/servlet/.

Source file: BufferedHttpResponseWrapper.java

  15 
vote

public ServletOutputStream getOutputStream() throws IOException {
  if (this.printWriter != null) {
    throw new IllegalStateException("The Servlet API forbids calling getOutputStream( ) after" + " getWriter( ) has been called");
  }
  if (this.outputStream == null) {
    this.outputStream=this.bufferedServletOut;
  }
  return this.outputStream;
}
 

Example 100

From project waffle, under directory /Source/ThirdParty/tomcat/webapps/examples/WEB-INF/classes/compressionFilters/.

Source file: CompressionServletResponseWrapper.java

  15 
vote

/** 
 * Create and return a ServletOutputStream to write the content associated with this Response.
 * @exception IOException if an input/output error occurs
 */
public ServletOutputStream createOutputStream() throws IOException {
  if (debug > 1) {
    System.out.println("createOutputStream gets called");
  }
  CompressionResponseStream stream=new CompressionResponseStream(origResponse);
  stream.setDebugLevel(debug);
  stream.setBuffer(threshold);
  return stream;
}
 

Example 101

From project webutilities, under directory /src/main/java/com/googlecode/webutilities/common/.

Source file: WebUtilitiesResponseWrapper.java

  15 
vote

@Override public ServletOutputStream getOutputStream() throws IOException {
  if (getWriterCalled) {
    throw new IllegalStateException("getWriter already called.");
  }
  getStreamCalled=true;
  return this.stream;
}