Java Code Examples for javax.servlet.ServletInputStream

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 candlepin, under directory /src/main/java/org/candlepin/servlet/filter/logging/.

Source file: LoggingRequestWrapper.java

  24 
vote

@Override public ServletInputStream getInputStream() throws IOException {
  final ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(body);
  ServletInputStream servletInputStream=new ServletInputStream(){
    public int read() throws IOException {
      return byteArrayInputStream.read();
    }
  }
;
  return servletInputStream;
}
 

Example 2

From project orion.server, under directory /bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/internal/server/servlets/xfer/.

Source file: ClientImport.java

  23 
vote

/** 
 * Reads the chunk of data to be imported from the request's input stream.
 */
private byte[] readChunk(HttpServletRequest req,int chunkSize) throws IOException {
  ServletInputStream requestStream=req.getInputStream();
  String contentType=req.getHeader(ProtocolConstants.HEADER_CONTENT_TYPE);
  if (contentType.startsWith("multipart"))   return readMultiPartChunk(requestStream,contentType);
  ByteArrayOutputStream outputStream=new ByteArrayOutputStream(chunkSize);
  IOUtilities.pipe(requestStream,outputStream,false,false);
  return outputStream.toByteArray();
}
 

Example 3

From project torquebox, under directory /modules/web/src/test/java/org/torquebox/web/rack/.

Source file: RackEnvironmentTest.java

  23 
vote

@Test public void testMissingContentLength() throws Exception {
  final ServletContext servletContext=mock(ServletContext.class);
  final HttpServletRequest servletRequest=mock(HttpServletRequest.class);
  final ServletInputStream inputStream=new MockServletInputStream(new ByteArrayInputStream("".getBytes()));
  when(servletRequest.getInputStream()).thenReturn(inputStream);
  when(servletRequest.getContentLength()).thenReturn(-1);
  RackEnvironment env=new RackEnvironment(ruby,servletContext,servletRequest);
  RubyHash envHash=env.getEnv();
  assertNotNull(envHash);
  assertNull(envHash.get("CONTENT_LENGTH"));
}
 

Example 4

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

Source file: Consumer.java

  22 
vote

public boolean execute(HttpServletRequest request,HttpServletResponse response,Map<Object,Object> ctx) throws Exception {
  int length=request.getContentLength();
  Log.debug("Consumer#execute: " + length);
  ServletInputStream in=request.getInputStream();
  int count;
  byte[] b=new byte[8092];
  while ((count=in.read(b)) != -1) {
    total+=count;
    Log.debug(String.format("read %s (expecting %s)",total,length));
  }
  Log.debug(String.format("read total %s (expecting %s)",total,length));
  return true;
}
 

Example 5

From project Ivory, under directory /prism/src/main/java/org/apache/ivory/resource/.

Source file: AbstractInstanceManager.java

  22 
vote

private Properties getProperties(HttpServletRequest request) throws IOException {
  Properties props=new Properties();
  ServletInputStream xmlStream=request == null ? null : request.getInputStream();
  if (xmlStream != null) {
    if (xmlStream.markSupported()) {
      xmlStream.mark(XML_DEBUG_LEN);
    }
    props.load(xmlStream);
  }
  return props;
}
 

Example 6

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

Source file: TeeServletInputStream.java

  22 
vote

private void duplicateInputStream(HttpServletRequest request){
  ServletInputStream originalSIS=null;
  try {
    originalSIS=request.getInputStream();
    inputBuffer=consumeBufferAndReturnAsByteArray(originalSIS);
    this.in=new ByteArrayInputStream(inputBuffer);
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
 finally {
    closeStrean(originalSIS);
  }
}
 

Example 7

From project Mockey, under directory /src/java/com/mockey/server/.

Source file: RedoRequestWrapper.java

  22 
vote

@Override public ServletInputStream getInputStream() throws IOException {
  final ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(body.getBytes());
  ServletInputStream servletInputStream=new ServletInputStream(){
    public int read() throws IOException {
      return byteArrayInputStream.read();
    }
  }
;
  return servletInputStream;
}
 

Example 8

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

Source file: PeepingTomRequestWrapper.java

  22 
vote

@Override public ServletInputStream getInputStream() throws IOException {
  if (stream == null) {
    final ServletInputStream originalInputStream=super.getInputStream();
    stream=new OpenableServletInputStream(originalInputStream);
  }
  return stream;
}
 

Example 9

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

Source file: BasicTest.java

  22 
vote

@Override protected void doPut(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  ServletInputStream is=req.getInputStream();
  String val=Util.readString(is,null);
  Assert.assertEquals("hello world",val);
  resp.setStatus(204);
}
 

Example 10

From project repose, under directory /project-set/components/datastore/src/test/java/com/rackspace/papi/components/datastore/.

Source file: DatastoreFilterLogicHandlerTest.java

  22 
vote

@Test public void shouldPutCacheObjects() throws Exception {
  final ServletInputStream inputStream=new ServletInputStreamWrapper(new ByteArrayInputStream(new byte[]{'t','e','s','t'}));
  final HttpServletRequest mockPutRequest=mockRequestWithMethod("PUT","10.1.1.1");
  when(mockPutRequest.getInputStream()).thenReturn(inputStream);
  logicHandler.handleRequest(mockPutRequest,mockResponse);
  verify(hashedDatastore,times(1)).put(eq(RESOURCE),any(byte[].class),any(byte[].class),eq(60),eq(TimeUnit.SECONDS),eq(RemoteBehavior.ALLOW_FORWARDING));
}
 

Example 11

From project amber, under directory /oauth-2.0/dynamicreg-server/src/main/java/org/apache/amber/oauth2/ext/dynamicreg/server/request/.

Source file: JSONHttpServletRequestWrapper.java

  21 
vote

/** 
 * Lazily read JSON from request
 * @throws OAuthProblemException
 */
private void readJsonBody(){
  if (!bodyRead) {
    bodyRead=true;
    try {
      final ServletRequest request=getRequest();
      String contentType=request.getContentType();
      final String expectedContentType=OAuth.ContentType.JSON;
      if (!OAuthUtils.hasContentType(contentType,expectedContentType)) {
        return;
      }
      final ServletInputStream inputStream=request.getInputStream();
      if (inputStream == null) {
        return;
      }
      final String jsonString=OAuthUtils.saveStreamAsString(inputStream);
      body=new JSONObject(jsonString);
    }
 catch (    JSONException e) {
      log.error("Cannot decode request body as a JSON: ",e);
    }
catch (    Exception e) {
      log.error("Dynamic client registration error: ",e);
      throw new OAuthRuntimeException("OAuth server error");
    }
  }
}
 

Example 12

From project capedwarf-blue, under directory /tasks/src/main/java/org/jboss/capedwarf/tasks/.

Source file: TasksServletRequestCreator.java

  21 
vote

@Override public ServletInputStream getInputStream() throws IOException {
  return new ServletInputStream(){
    public int read() throws IOException {
      try {
        final int rc=msg.readBytes(buf,1);
        return (rc != -1) ? buf[0] : -1;
      }
 catch (      JMSException e) {
        throw new IOException(e);
      }
    }
  }
;
}
 

Example 13

From project components-ness-tracking, under directory /src/test/java/com/nesscomputing/tracking/.

Source file: MockedHttpServletRequest.java

  21 
vote

@Override public ServletInputStream getInputStream() throws IOException {
  final InputStream stream=new NullInputStream(getContentLength());
  return new ServletInputStream(){
    @Override public int read() throws IOException {
      return stream.read();
    }
  }
;
}
 

Example 14

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

Source file: CopyHttpServletRequest.java

  21 
vote

/** 
 * @return
 * @throws IOException 
 */
public ServletInputStream getInputStream() throws IOException {
  if (this.reqContentBytes == null) {
    return super.getInputStream();
  }
  return new ServletInputStream(){
    private ByteArrayInputStream bis=new ByteArrayInputStream(CopyHttpServletRequest.this.reqContentBytes);
    @Override public int read() throws IOException {
      return bis.read();
    }
  }
;
}
 

Example 15

From project javamagic, under directory /ajaxupload/src/test/java/com/googlecode/tawus/ajaxupload/internal/services/.

Source file: AjaxUploadDecoderImplTest.java

  21 
vote

@Test public void check_new_uploaded_file_is_created_during_setup() throws Exception {
  HttpServletRequest request=mockHttpServletRequest();
  FileItem item=mockFileItem();
  ServletInputStream inputStream=newStringInputStream("Test stream data");
  ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
  expect(request.getHeader(AjaxUploadDecoderImpl.AJAX_UPLOAD_HEADER)).andReturn("test");
  expect(request.getContentType()).andReturn("test/test");
  expect(request.getParameter(AjaxUploadConstants.FILE_PARAMETER)).andReturn("myfilename");
  expect(request.getInputStream()).andReturn(inputStream);
  expect(fileItemFactory.createItem("test","test/test",false,"myfilename")).andReturn(item);
  expect(item.getOutputStream()).andReturn(outputStream);
  replay();
  decoder.setupUploadedFile(request);
  verify();
  assertEquals(outputStream.toString(),"Test stream data");
}
 

Example 16

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

Source file: StagingHttpRequest.java

  21 
vote

public ServletInputStream getInputStream() throws IOException {
  String body=getRequestBody();
  if (null != body) {
    final ByteArrayInputStream input=new ByteArrayInputStream(body.getBytes(getCharacterEncoding()));
    return new ServletInputStream(){
      @Override public int read() throws IOException {
        return input.read();
      }
    }
;
  }
  return null;
}
 

Example 17

From project lyo.rio, under directory /org.eclipse.lyo.rio.am/src/main/java/org/eclipse/lyo/oslc/am/linktype/.

Source file: LinkTypeService.java

  21 
vote

/** 
 * @see HttpServlet#doPut(HttpServletRequest,HttpServletResponse)
 */
protected void doPut(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  try {
    RioStore store=this.getStore();
    LinkTypeHelper helper=new LinkTypeHelper();
    LinkType linkType=helper.getLinkTypeFromResourceUri(store,request.getRequestURL().toString());
    if (linkType == null) {
      throw new RioServiceException(IConstants.SC_NOT_FOUND);
    }
    checkConditionalHeaders(request,linkType);
    String contentType=request.getContentType();
    if (!IConstants.CT_RDF_XML.equals(contentType)) {
      throw new RioServiceException(IConstants.SC_UNSUPPORTED_MEDIA_TYPE);
    }
    ServletInputStream content=request.getInputStream();
    String uri=store.nextAvailableUri(IAmConstants.SERVICE_LINKTYPE);
    List<RioStatement> statements=store.parse(request.getRequestURL().toString(),content,contentType);
    String about=statements.get(0).getSubject();
    LinkType updatedLinkType=new LinkType(uri,about);
    updatedLinkType.addStatements(statements);
    String userId=request.getRemoteUser();
    String userUri=this.getUserUri(userId);
    store.update(updatedLinkType,userUri);
    updatedLinkType=helper.getLinkTypeFromResourceUri(store,request.getRequestURL().toString());
    response.setStatus(IConstants.SC_OK);
    response.addHeader(IConstants.HDR_ETAG,updatedLinkType.getETag());
    response.addHeader(IConstants.HDR_LOCATION,updatedLinkType.getUri());
    String lastModified=StringUtils.rfc2822(updatedLinkType.getModified());
    response.addHeader(IConstants.HDR_LAST_MODIFIED,lastModified);
  }
 catch (  Exception e) {
    throw new RioServiceException(IConstants.SC_INTERNAL_ERROR,e);
  }
}
 

Example 18

From project lyo.server, under directory /org.eclipse.lyo.samples.sharepoint/src/org/eclipse/lyo/samples/sharepoint/adapter/.

Source file: ResourceService.java

  21 
vote

/** 
 * @see HttpServlet#doPut(HttpServletRequest,HttpServletResponse)
 */
protected void doPut(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  try {
    ShareStore store=this.getStore();
    OslcResource resource=store.getOslcResource(request.getRequestURL().toString());
    if (resource == null) {
      throw new ShareServiceException(IConstants.SC_NOT_FOUND);
    }
    checkConditionalHeaders(request,resource);
    Date created=resource.getCreated();
    String creator=resource.getCreator();
    String contentType=request.getContentType();
    if (!contentType.startsWith(IConstants.CT_RDF_XML)) {
      throw new ShareServiceException(IConstants.SC_UNSUPPORTED_MEDIA_TYPE);
    }
    ServletInputStream content=request.getInputStream();
    OslcResource updatedResource=new OslcResource(resource.getUri());
    List<ShareStatement> statements=store.parse(resource.getUri(),content,contentType);
    updatedResource.addStatements(statements);
    updatedResource.setCreated(created);
    updatedResource.setCreator(creator);
    String userId=request.getRemoteUser();
    String userUri=this.getUserUri(userId);
    store.update(updatedResource,userUri);
    updatedResource=store.getOslcResource(resource.getUri());
    response.setStatus(IConstants.SC_OK);
    response.addHeader(IConstants.HDR_ETAG,updatedResource.getETag());
    response.addHeader(IConstants.HDR_LOCATION,updatedResource.getUri());
    String lastModified=StringUtils.rfc2822(updatedResource.getModified());
    response.addHeader(IConstants.HDR_LAST_MODIFIED,lastModified);
  }
 catch (  ShareServerException e) {
    throw new ShareServiceException(IConstants.SC_BAD,e);
  }
}
 

Example 19

From project maven-wagon, under directory /wagon-provider-test/src/main/java/org/apache/maven/wagon/http/.

Source file: HttpWagonTestCase.java

  21 
vote

public void handle(String target,HttpServletRequest request,HttpServletResponse response,int dispatch) throws IOException, ServletException {
  Request base_request=request instanceof Request ? (Request)request : HttpConnection.getCurrentConnection().getRequest();
  if (base_request.isHandled() || !"PUT".equals(base_request.getMethod())) {
    return;
  }
  base_request.setHandled(true);
  File file=new File(resourceBase,URLDecoder.decode(request.getPathInfo()));
  file.getParentFile().mkdirs();
  FileOutputStream out=new FileOutputStream(file);
  ServletInputStream in=request.getInputStream();
  try {
    IOUtil.copy(in,out);
  }
  finally {
    in.close();
    out.close();
  }
  putCallNumber++;
  DeployedResource deployedResource=new DeployedResource();
  deployedResource.httpMethod=request.getMethod();
  deployedResource.requestUri=request.getRequestURI();
  deployedResource.transferEncoding=request.getHeader("Transfer-Encoding");
  deployedResource.contentLength=request.getHeader("Content-Length");
  deployedResources.add(deployedResource);
  response.setStatus(HttpServletResponse.SC_CREATED);
  handlerRequestResponses.add(new HandlerRequestResponse(request.getMethod(),((Response)response).getStatus(),request.getRequestURI()));
}
 

Example 20

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

Source file: TestServletRequest.java

  21 
vote

public ServletInputStream getInputStream() throws IOException {
  return new ServletInputStream(){
    @Override public int read() throws IOException {
      return is.read();
    }
  }
;
}
 

Example 21

From project tawus, under directory /tawus-ajaxupload/src/test/java/com/googlecode/tawus/ajaxupload/internal/services/.

Source file: AjaxUploadDecoderImplTest.java

  21 
vote

@Test public void check_new_uploaded_file_is_created_during_setup() throws Exception {
  HttpServletRequest request=mockHttpServletRequest();
  FileItem item=mockFileItem();
  ServletInputStream inputStream=newStringInputStream("Test stream data");
  ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
  expect(request.getHeader(AjaxUploadDecoderImpl.AJAX_UPLOAD_HEADER)).andReturn("test");
  expect(request.getContentType()).andReturn("test/test");
  expect(request.getParameter(AjaxUploadConstants.FILE_PARAMETER)).andReturn("myfilename");
  expect(request.getInputStream()).andReturn(inputStream);
  expect(fileItemFactory.createItem("test","test/test",false,"myfilename")).andReturn(item);
  expect(item.getOutputStream()).andReturn(outputStream);
  replay();
  decoder.setupUploadedFile(request);
  verify();
  assertEquals(outputStream.toString(),"Test stream data");
}
 

Example 22

From project vysper, under directory /server/extensions/xep0124-xep0206-bosh/src/test/java/org/apache/vysper/xmpp/extension/xep0124/.

Source file: BoshDecoderTest.java

  21 
vote

@Test public void testDecode() throws IOException, SAXException {
  ServletInputStream input=new ServletInputStreamMock("<body rid='3549788615' xmlns='http://jabber.org/protocol/httpbind' to='vysper.org' xml:lang='en' wait='60' hold='1' ver='1.6' xmpp:version='1.0' xmlns:xmpp='urn:xmpp:xbosh'/>");
  expect(request.getInputStream()).andReturn(input);
  Capture<Stanza> captured=new Capture<Stanza>();
  boshHandler.process(EasyMock.<HttpServletRequest>notNull(),EasyMock.<Stanza>capture(captured));
  mocksControl.replay();
  boshDecoder.decode();
  mocksControl.verify();
  Stanza request=captured.getValue();
  assertNotNull(request);
  assertEquals("body",request.getName());
  assertEquals(NamespaceURIs.XEP0124_BOSH,request.getNamespaceURI());
  assertEquals("3549788615",request.getAttributeValue("rid"));
  assertEquals("vysper.org",request.getAttributeValue("to"));
  assertEquals("60",request.getAttributeValue("wait"));
  assertEquals("1",request.getAttributeValue("hold"));
  assertEquals("1.6",request.getAttributeValue("ver"));
  assertEquals("1.0",request.getAttributeValue(NamespaceURIs.URN_XMPP_XBOSH,"version"));
  assertEquals("en",request.getAttributeValue(NamespaceURIs.XML,"lang"));
}
 

Example 23

From project wagon-ahc, under directory /src/test/java/org/sonatype/maven/wagon/providers/http/.

Source file: HttpWagonTestCase.java

  21 
vote

public void handle(final String target,final HttpServletRequest request,final HttpServletResponse response,final int dispatch) throws IOException, ServletException {
  Request base_request=request instanceof Request ? (Request)request : HttpConnection.getCurrentConnection().getRequest();
  if (base_request.isHandled() || !"PUT".equals(base_request.getMethod())) {
    return;
  }
  base_request.setHandled(true);
  File file=new File(resourcePath,URLDecoder.decode(request.getPathInfo()));
  file.getParentFile().mkdirs();
  FileOutputStream out=new FileOutputStream(file);
  ServletInputStream in=request.getInputStream();
  try {
    IOUtil.copy(in,out);
  }
  finally {
    in.close();
    out.close();
  }
  response.setStatus(HttpServletResponse.SC_CREATED);
}
 

Example 24

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

Source file: ServletHelper.java

  21 
vote

/** 
 * @param servletRequest
 * @return an InputStream that contains at least one byte or null if underlying stream is null or empty
 * @throws IOException if thrown while accessing the underlying ServletInputStream
 */
public @Nullable InputStream getServletRequestBody(HttpServletRequest servletRequest) throws IOException {
  ServletInputStream sis=servletRequest.getInputStream();
  if (sis == null) {
    return null;
  }
 else {
    PushbackInputStream pis=new PushbackInputStream(sis);
    int val=pis.read();
    if (val == -1) {
      return null;
    }
 else {
      pis.unread(val);
      return pis;
    }
  }
}
 

Example 25

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

Source file: TestRackServlet.java

  20 
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 26

From project grouperfish, under directory /service/src/test/java/com/mozilla/grouperfish/rest/jaxrs/.

Source file: RestHelperTest.java

  20 
vote

public void testPutAny() throws IOException {
  final HttpServletRequest mock=mock(HttpServletRequest.class);
  final String body="{\"id\": \"mydoc\"}";
  when(mock.getMethod()).thenReturn("PUT");
  when(mock.getContentLength()).thenReturn(body.length());
  when(mock.getInputStream()).thenReturn(new ServletInputStream(){
    final ByteArrayInputStream byteStream=new ByteArrayInputStream(body.getBytes());
    @Override public int read() throws IOException {
      return byteStream.read();
    }
  }
);
  final Response response=RestHelper.putAny(DocumentsResource.class,NS,"mydoc",mock);
  assertNotNull(response);
  assertEquals(201,response.getStatus());
}
 

Example 27

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

Source file: TestRackServlet.java

  20 
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 28

From project stubby4j, under directory /src/test/java/org/stubby/handlers/.

Source file: AdminHandlerTest.java

  20 
vote

@Test public void verifyBehaviourDuringPostRequestOnRegisterNewEndpoint() throws Exception {
  final String requestPathInfo=AdminEndpoints.STUBDATA_NEW.desc();
  @SuppressWarnings("unchecked") final List<StubHttpLifecycle> mockStubHttpLifecycleList=Mockito.mock(List.class);
  when(mockJettyOrchestrator.getDataStore()).thenReturn(mockDataStore);
  when(mockJettyOrchestrator.getYamlParser()).thenReturn(mockYamlParser);
  when(mockYamlParser.getLoadedConfigYamlPath()).thenReturn("/User/filename.yaml");
  when(mockHttpServletRequest.getMethod()).thenReturn("post");
  when(mockHttpServletRequest.getPathInfo()).thenReturn(requestPathInfo);
  when(mockHttpServletRequest.getContextPath()).thenReturn(requestPathInfo);
  when(mockDataStore.getStubHttpLifecycles()).thenReturn(mockStubHttpLifecycleList);
  when(mockStubHttpLifecycleList.size()).thenReturn(1);
  final AdminHandler adminHandler=new AdminHandler(mockJettyOrchestrator);
  final String postData="" + "-  request:\n" + "      method: GET\n"+ "      url: /item/8\n"+ "   response:\n"+ "      headers:\n"+ "         content-type: application/json\n"+ "      status: 200\n"+ "      body: {\"alex\" : \"zagniotov\"}";
  final InputStream inputStream=new ByteArrayInputStream(postData.getBytes());
  Mockito.when(mockHttpServletRequest.getInputStream()).thenReturn(new ServletInputStream(){
    @Override public int read() throws IOException {
      return inputStream.read();
    }
  }
);
  adminHandler.handle(requestPathInfo,mockRequest,mockHttpServletRequest,mockHttpServletResponse);
  verify(mockHttpServletResponse,never()).setStatus(HttpStatus.BAD_REQUEST_400);
  verify(mockHttpServletResponse,never()).setStatus(HttpStatus.CONFLICT_409);
  verify(mockHttpServletResponse,never()).setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
  verify(mockStubHttpLifecycleList,times(1)).clear();
  verify(mockDataStore,times(1)).setStubHttpLifecycles(Mockito.anyListOf(StubHttpLifecycle.class));
  verify(mockHttpServletResponse,times(1)).setStatus(HttpStatus.CREATED_201);
}
 

Example 29

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

Source file: Webserver.java

  19 
vote

public ServletInputStream getInputStream() throws IOException {
synchronized (in) {
    if (((ServeInputStream)in).isReturnedAsReader())     throw new IllegalStateException("Already returned as a reader.");
    ((ServeInputStream)in).setReturnedAsStream(true);
  }
  return in;
}
 

Example 30

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

Source file: Serve.java

  19 
vote

public ServletInputStream getInputStream() throws IOException {
synchronized (in) {
    if (((ServeInputStream)in).isReturnedAsReader())     throw new IllegalStateException("Already returned as a reader.");
    ((ServeInputStream)in).setReturnedAsStream(true);
  }
  return in;
}
 

Example 31

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

Source file: HttpUtils.java

  19 
vote

/** 
 * Parses data from an HTML form that the client sends to  the server using the HTTP POST method and the  <i>application/x-www-form-urlencoded</i> MIME type. <p>The data sent by the POST method contains key-value pairs. A key can appear more than once in the POST data with different values. However, the key appears only once in  the hashtable, with its value being an array of strings containing the multiple values sent by the POST method. <p>The keys and values in the hashtable are stored in their decoded form, so any + characters are converted to spaces, and characters sent in hexadecimal notation (like <i>%xx</i>) are converted to ASCII characters.
 * @param len	an integer specifying the length,in characters, of the  <code>ServletInputStream</code> object that is also passed to this method
 * @param in	the <code>ServletInputStream</code>object that contains the data sent from the client
 * @return		a <code>HashTable</code> object builtfrom the parsed key-value pairs
 * @exception IllegalArgumentException if the datasent by the POST method is invalid
 */
public static Hashtable<String,String[]> parsePostData(int len,ServletInputStream in){
  if (len <= 0) {
    return new Hashtable<String,String[]>();
  }
  if (in == null) {
    throw new IllegalArgumentException();
  }
  byte[] postedBytes=new byte[len];
  try {
    int offset=0;
    do {
      int inputLen=in.read(postedBytes,offset,len - offset);
      if (inputLen <= 0) {
        String msg=lStrings.getString("err.io.short_read");
        throw new IllegalArgumentException(msg);
      }
      offset+=inputLen;
    }
 while ((len - offset) > 0);
  }
 catch (  IOException e) {
    throw new IllegalArgumentException(e.getMessage());
  }
  try {
    String postedBody=new String(postedBytes,0,len,"8859_1");
    return parseQueryString(postedBody);
  }
 catch (  java.io.UnsupportedEncodingException e) {
    throw new IllegalArgumentException(e.getMessage());
  }
}
 

Example 32

From project jbossportletbridge, under directory /extension/richfaces/src/main/java/org/jboss/portletbridge/richfaces/request/.

Source file: HttpServletRequestAdapter.java

  19 
vote

/** 
 * @see javax.servlet.ServletRequest#getInputStream()
 */
@Override public ServletInputStream getInputStream() throws IOException {
  if (request instanceof ClientDataRequest) {
    return new ServletInputStreamAdapter((ClientDataRequest)request);
  }
  throw new UnsupportedOperationException();
}
 

Example 33

From project onebusaway-nyc, under directory /onebusaway-nyc-queue-http-proxy/src/main/java/org/onebusaway/nyc/queue_http_proxy/.

Source file: BHSListenerServlet.java

  19 
vote

private void service(ServletInputStream stream) throws IOException {
  ByteArrayOutputStream baos=new ByteArrayOutputStream(CHUNK_SIZE);
  byte[] buff=new byte[CHUNK_SIZE];
  int noData=stream.readLine(buff,0,CHUNK_SIZE);
  while (noData != -1) {
    baos.write(buff,0,noData);
    noData=stream.readLine(buff,0,CHUNK_SIZE);
  }
  enqueue(baos.toByteArray());
}
 

Example 34

From project rewrite, under directory /showcase/rest-ws/src/main/java/org/ocpsoft/rewrite/showcase/rest/.

Source file: XMLUtil.java

  19 
vote

@SuppressWarnings("unchecked") public static <T>T streamToObject(final Class<T> type,final ServletInputStream inputStream){
  try {
    Unmarshaller unmarshaller=JAXBContext.newInstance(type).createUnmarshaller();
    T result=(T)unmarshaller.unmarshal(inputStream);
    return result;
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 35

From project riot, under directory /forms/src/org/riotfamily/forms/fileupload/.

Source file: HttpUploadRequest.java

  19 
vote

public ServletInputStream getInputStream() throws IOException {
  if (wrappedStream == null) {
    wrappedStream=super.getInputStream();
    countingInputStream.setSourceStream(wrappedStream);
  }
  return countingInputStream;
}
 

Example 36

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

Source file: MockHttpServletRequest.java

  19 
vote

public ServletInputStream getInputStream() throws IOException {
  if (this.content != null) {
    return new DelegatingServletInputStream(new ByteArrayInputStream(this.content));
  }
 else {
    return null;
  }
}
 

Example 37

From project tempo, under directory /fds/src/test/java/org/intalio/tempo/workflow/fds/.

Source file: FormDispatcherServletTest.java

  19 
vote

@Specification void testIB4P() throws Exception {
class MockServletInputStream extends ServletInputStream {
    private InputStream _is;
    public MockServletInputStream(    InputStream is) throws IOException {
      _is=is;
    }
    public int read() throws IOException {
      return _is.read();
    }
  }
  final MockServletInputStream msis=new MockServletInputStream(requestInputStream);
  CharArrayWriter caw=new CharArrayWriter();
  final PrintWriter pw=new PrintWriter(caw);
  expect.that(new Expectations(){
{
      atLeast(1).of(request).getRequestURI();
      will(returnValue(_URI_PREFIX + _IB4P_URI));
      one(request).getHeader("SOAPAction");
      will(returnValue(null));
      one(request).getInputStream();
      will(returnValue(msis));
      one(request).getCharacterEncoding();
      will(returnValue("UTF-8"));
      one(response).setCharacterEncoding("UTF-8");
      one(response).setContentType("text/xml; charset=UTF-8");
      one(response).getWriter();
      will(returnValue(pw));
    }
  }
);
  fdServlet.doPost(request,response);
  Assert.assertTrue(caw.toString().contains("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"));
}
 

Example 38

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

Source file: HttpServletRequestImpl.java

  19 
vote

@Override public ServletInputStream getInputStream() throws IOException {
  if (servletInputStream == null) {
    if (reader != null) {
      throw UndertowServletMessages.MESSAGES.getReaderAlreadyCalled();
    }
    servletInputStream=new ServletInputStreamImpl(exchange.getInputStream());
  }
  readStarted=true;
  return servletInputStream;
}
 

Example 39

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

Source file: CompressedHttpServletRequestWrapper.java

  19 
vote

public ServletInputStream getInputStream() throws IOException {
  if (getReaderCalled) {
    throw new IllegalStateException("getReader() has been already called");
  }
  getInputStreamCalled=true;
  return getCompressedServletInputStream();
}
 

Example 40

From project winstone, under directory /src/java/javax/servlet/http/.

Source file: HttpUtils.java

  19 
vote

/** 
 * @deprecated Parses data from an HTML form that the client sends to theserver using the HTTP POST method and the application/x-www-form-urlencoded MIME type.
 */
public static Hashtable parsePostData(int len,ServletInputStream in){
  try {
    byte body[]=new byte[len];
    int startPos=0;
    int readChars=in.read(body,startPos,len - startPos);
    while ((readChars != -1) && (len != startPos)) {
      startPos+=readChars;
      readChars=in.read(body,startPos,len - startPos);
    }
    if (len != startPos)     throw new java.io.IOException("Stream ended early");
 else {
      String post=new String(body,0,len,"8859_1");
      return parseQueryString(post);
    }
  }
 catch (  java.io.IOException err) {
    throw new IllegalArgumentException("Error parsing request body - " + err.getMessage());
  }
}