Java Code Examples for javax.servlet.ServletInputStream

The following examples show how to use javax.servlet.ServletInputStream. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Tomcat7.0.67   Source File: Request.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return the servlet input stream for this Request.  The default
 * implementation returns a servlet input stream created by
 * <code>createInputStream()</code>.
 *
 * @exception IllegalStateException if <code>getReader()</code> has
 *  already been called for this request
 * @exception IOException if an input/output error occurs
 */
@Override
public ServletInputStream getInputStream() throws IOException {

    if (usingReader) {
        throw new IllegalStateException
            (sm.getString("coyoteRequest.getInputStream.ise"));
    }

    usingInputStream = true;
    if (inputStream == null) {
        inputStream = new CoyoteInputStream(inputBuffer);
    }
    return inputStream;

}
 
Example 2
Source Project: hdw-dubbo   Source File: WebUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 复制输入流
 *
 * @param inputStream
 * @return</br>
 */
public static InputStream cloneInputStream(ServletInputStream inputStream) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len;
    try {
        while ((len = inputStream.read(buffer)) > -1) {
            byteArrayOutputStream.write(buffer, 0, len);
        }
        byteArrayOutputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
    InputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    return byteArrayInputStream;
}
 
Example 3
Source Project: weixin4j   Source File: WeixinUrlFilter.java    License: Apache License 2.0 6 votes vote down vote up
private void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/xml");
        //获取POST流
        ServletInputStream in = request.getInputStream();
        if (Configuration.isDebug()) {
            System.out.println("接收到微信输入流,准备处理...");
        }
        IMessageHandler messageHandler = HandlerFactory.getMessageHandler();
        //处理输入消息,返回结果
        String xml = messageHandler.invoke(in);
        //返回结果
        response.getWriter().write(xml);
    } catch (Exception ex) {
        ex.printStackTrace();
        response.getWriter().write("");
    }
}
 
Example 4
Source Project: wafer-java-server-sdk   Source File: HttpMock.java    License: MIT License 6 votes vote down vote up
public void setRequestBody(String requestBody) {
	try {
		// @see http://blog.timmattison.com/archives/2014/12/16/mockito-and-servletinputstreams/
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(requestBody.getBytes("utf-8"));
		ServletInputStream mockServletInputStream = mock(ServletInputStream.class);
		when(mockServletInputStream.read(Matchers.<byte[]>any(), anyInt(), anyInt())).thenAnswer(new Answer<Integer>() {
		    @Override
		    public Integer answer(InvocationOnMock invocationOnMock) throws Throwable {
		        Object[] args = invocationOnMock.getArguments();
		        byte[] output = (byte[]) args[0];
		        int offset = (int) args[1];
		        int length = (int) args[2];
		        return byteArrayInputStream.read(output, offset, length);
		    }
		});
		when(request.getInputStream()).thenReturn(mockServletInputStream);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 5
Source Project: cougar   Source File: SoapTransportCommandProcessorTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests a client error response is sent for invalid input
 * @throws Exception
 */
@Test
public void testProcess_IOException() throws Exception {
    when(request.getScheme()).thenReturn("http");
    ServletInputStream is = mock(ServletInputStream.class);
    when(request.getInputStream()).thenReturn(is);
    when(is.read()).thenThrow(new IOException("i/o error"));
    when(is.read((byte[])any())).thenThrow(new IOException("i/o error"));
    when(is.read((byte[])any(),anyInt(),anyInt())).thenThrow(new IOException("i/o error"));

    // Resolve the input command
    soapCommandProcessor.process(command);
    assertEquals(CommandStatus.Complete, command.getStatus());
    assertSoapyEquals(buildSoapMessage(null, null, invalidOpError, null), testOut.getOutput());
    verify(response).setContentType(MediaType.TEXT_XML);
    verify(response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    verify(logger).logAccess(eq(command), isA(ExecutionContext.class), anyLong(), anyLong(),
            any(MediaType.class), any(MediaType.class), any(ResponseCode.class));

    //verifyTracerCalls(); // todo: #81: put this back
}
 
Example 6
Source Project: botwall4j   Source File: CharRequestWrapper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ServletInputStream getInputStream() throws IOException {
  if (getReaderCalled) {
    throw new IllegalStateException("getReader already called");
  }

  getInputStreamCalled = true;
  final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.newRequestBody.getBytes());

  return new ServletInputStream() {
    @Override
    public int read() throws IOException {
      return byteArrayInputStream.read();
    }
  };
}
 
Example 7
Source Project: Tomcat8-Source-Read   Source File: TestNonBlockingAPI.java    License: MIT License 6 votes vote down vote up
@Override
public void onDataAvailable() throws IOException {
    ServletInputStream in = ctx.getRequest().getInputStream();
    String s = "";
    byte[] b = new byte[8192];
    int read = 0;
    do {
        read = in.read(b);
        if (read == -1) {
            break;
        }
        s += new String(b, 0, read);
    } while (ignoreIsReady || in.isReady());
    log.info(s);
    body.append(s);
}
 
Example 8
@Override
public ServletInputStream getInputStream() throws java.io.IOException {
  String contentType = getContentType();
  if( contentType != null && contentType.startsWith( "application/x-www-form-urlencoded" ) ) {
    String encoding = getCharacterEncoding();
    if( encoding == null ) {
      encoding = Charset.defaultCharset().name();
    }
    String body = IOUtils.toString( super.getInputStream(), encoding );
    Map<String, List<String>> params = getParams( body );
    if (params == null) {
      params = new LinkedHashMap<>();
    }
    body = urlEncode( params, encoding );
    // ASCII is OK here because the urlEncode about should have already escaped
    return new ServletInputStreamWrapper( new ByteArrayInputStream( body.getBytes(StandardCharsets.US_ASCII.name()) ) );
  } else {
    return super.getInputStream();
  }
}
 
Example 9
Source Project: Tomcat8-Source-Read   Source File: TestNonBlockingAPI.java    License: MIT License 6 votes vote down vote up
@Override
public void onDataAvailable() throws IOException {
    ServletInputStream in = ctx.getRequest().getInputStream();
    String s = "";
    byte[] b = new byte[8192];
    int read = 0;
    do {
        read = in.read(b);
        if (read == -1) {
            break;
        }
        s += new String(b, 0, read);
    } while (in.isReady());
    log.info("Read [" + s + "]");
    body.append(s);
}
 
Example 10
Source Project: knox   Source File: DefaultDispatchTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCallToSecureClusterWithoutDelegationToken() throws URISyntaxException, IOException {
  DefaultDispatch defaultDispatch = new DefaultDispatch();
  defaultDispatch.setReplayBufferSize(10);
  ServletContext servletContext = EasyMock.createNiceMock( ServletContext.class );
  GatewayConfig gatewayConfig = EasyMock.createNiceMock( GatewayConfig.class );
  EasyMock.expect(gatewayConfig.isHadoopKerberosSecured()).andReturn( Boolean.TRUE ).anyTimes();
  EasyMock.expect( servletContext.getAttribute( GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE ) ).andReturn( gatewayConfig ).anyTimes();
  ServletInputStream inputStream = EasyMock.createNiceMock( ServletInputStream.class );
  HttpServletRequest inboundRequest = EasyMock.createNiceMock( HttpServletRequest.class );
  EasyMock.expect(inboundRequest.getQueryString()).andReturn( "a=123").anyTimes();
  EasyMock.expect(inboundRequest.getInputStream()).andReturn( inputStream).anyTimes();
  EasyMock.expect(inboundRequest.getServletContext()).andReturn( servletContext ).anyTimes();
  EasyMock.replay( gatewayConfig, servletContext, inboundRequest );
  HttpEntity httpEntity = defaultDispatch.createRequestEntity(inboundRequest);
  assertTrue("not buffering in the absence of delegation token",
      (httpEntity instanceof PartiallyRepeatableHttpEntity));
}
 
Example 11
Source Project: knox   Source File: LivyDispatch.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ServletInputStream getInputStream() throws IOException {
  ServletInputStream inputStream = super.getInputStream();

  HttpServletRequest request = (HttpServletRequest)getRequest();
  String requestURI = request.getRequestURI();
  if(matchProxyUserEndpoints(requestURI)) {
    // Parse the json object from the request
    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, Object> jsonMap = objectMapper.readValue(inputStream, new TypeReference<Map<String,Object>>(){});

    // Force the proxyUser to be set to the remote user
    jsonMap.put("proxyUser", SubjectUtils.getCurrentEffectivePrincipalName());

    // Create the new ServletInputStream with modified json map.
    String s = objectMapper.writeValueAsString(jsonMap);
    return new UrlRewriteRequestStream(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)));
  }

  return inputStream;
}
 
Example 12
@Test
public void testGetInputStream() throws IOException {
  Buffer body = Buffer.buffer();
  body.appendByte((byte) 1);

  new Expectations() {
    {
      context.getBody();
      result = body;
    }
  };

  ServletInputStream is1 = request.getInputStream();
  Assert.assertSame(is1, request.getInputStream());
  int value = is1.read();
  is1.close();
  Assert.assertEquals(1, value);
  Assert.assertSame(is1, request.getInputStream());

  request.setBodyBuffer(Buffer.buffer().appendByte((byte)2));
  ServletInputStream is2 = request.getInputStream();
  Assert.assertNotSame(is1, is2);
}
 
Example 13
Source Project: orion.server   Source File: FileHandlerV1.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void handleMultiPartPut(HttpServletRequest request, HttpServletResponse response, IFileStore file) throws IOException, CoreException,
		JSONException, NoSuchAlgorithmException {
	String typeHeader = request.getHeader(ProtocolConstants.HEADER_CONTENT_TYPE);
	String boundary = typeHeader.substring(typeHeader.indexOf("boundary=\"") + 10, typeHeader.length() - 1); //$NON-NLS-1$
	ServletInputStream requestStream = request.getInputStream();
	BufferedReader requestReader = new BufferedReader(new InputStreamReader(requestStream, "UTF-8")); //$NON-NLS-1$
	handlePutMetadata(requestReader, boundary, file);
	// next come the headers for the content
	Map<String, String> contentHeaders = new HashMap<String, String>();
	String line;
	while ((line = requestReader.readLine()) != null && line.length() > 0) {
		String[] header = line.split(":"); //$NON-NLS-1$
		if (header.length == 2)
			contentHeaders.put(header[0], header[1]);
	}
	// now for the file contents
	handlePutContents(request, requestStream, response, file);
}
 
Example 14
Source Project: spring-boot-demo   Source File: RequestWrapper.java    License: MIT License 6 votes vote down vote up
/**
 * 复制输入流
 * @param inputStream
 * @return
 */
public InputStream cloneInputStream(ServletInputStream inputStream) {

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len;
    try {
        while ((len = inputStream.read(buffer)) > -1) {
            byteArrayOutputStream.write(buffer, 0, len);
        }
        byteArrayOutputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
}
 
Example 15
Source Project: cumulusrdf   Source File: CRUDServletPostTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * If an internal server error occurs during deletion the service must
 * answer with 500 HTTP status code. Note that this doesn't cover any
 * possible scenarios...just emulating an uncaught exception in order to see
 * if a correct response code is returned.
 * 
 * @throws Exception hopefully never, otherwise the test fails.
 */
@Test
public void postWithUnknownInternalServerFailure() throws Exception {

	when(_context.getAttribute(ConfigParams.STORE)).thenReturn(null);

	final HttpServletRequest request = createMockHttpRequest(null, null, null, null, null);
	when(request.getHeader(Headers.CONTENT_TYPE)).thenReturn(MimeTypes.TEXT_PLAIN);

	final ServletInputStream stream = new ServletInputStream() {
		final InputStream _inputStream = new ByteArrayInputStream(_triplesAsString.getBytes(Environment.CHARSET_UTF8));

		@Override
		public int read() throws IOException {
			return _inputStream.read();
		}
	};

	when(request.getInputStream()).thenReturn(stream);
	final HttpServletResponse response = mock(HttpServletResponse.class);

	_classUnderTest.doPost(request, response);

	verify(response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
 
Example 16
Source Project: quarkus-http   Source File: EarlyCloseClientServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    try {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final ServletInputStream inputStream = req.getInputStream();
        byte[] buf = new byte[1024];
        int read;
        while ((read = inputStream.read(buf)) != -1) {
            out.write(buf, 0, read);
        }
        resp.getOutputStream().write(out.toByteArray());
        completedNormally = true;
    } catch (IOException e) {
        exceptionThrown = true;
    } finally {
        latch.countDown();
    }
}
 
Example 17
Source Project: NFVO   Source File: CustomHttpServletRequestWrapper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ServletInputStream getInputStream() {
  final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
  return new ServletInputStream() {
    @Override
    public boolean isFinished() {
      return byteArrayInputStream.available() == 0;
    }

    @Override
    public boolean isReady() {
      return true;
    }

    @Override
    public void setReadListener(ReadListener listener) {
      throw new RuntimeException("Not implemented");
    }

    public int read() {
      return byteArrayInputStream.read();
    }
  };
}
 
Example 18
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ServletInputStream inputStream = request.getInputStream();
    if (inputStream != null) {
        inputStream.mark(Integer.MAX_VALUE);
    }
    try {
        String pathInfo = request.getPathInfo();
        if (pathInfo.startsWith(PATH_INGEST)) {
            stats.incIngestRequestCount();
            add(request, pathInfo, response);
        } else if (pathInfo.startsWith(PATH_BATCH_INGEST)) {
            stats.incBatchIngestRequestCount();
            batchAdd(request, pathInfo, response);
        } else {
            stats.incInvalidRequestCount();
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (Throwable ex) {
        String requestTxt = readRequest(request);
        stats.setLastFailedRequest(readRequestHead(request) + requestTxt);
        stats.registerError(ex);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
 
Example 19
@Test
public void getInputStreamCache() throws IOException {
  requestEx.setCacheRequest(true);

  ServletInputStream inputStream = request.getInputStream();
  new Expectations(IOUtils.class) {
    {
      IOUtils.toByteArray(inputStream);
      result = "abc".getBytes();
    }
  };

  ServletInputStream cachedInputStream = requestEx.getInputStream();
  Assert.assertEquals("abc", IOUtils.toString(cachedInputStream, StandardCharsets.UTF_8));
  Assert.assertEquals("abc", requestEx.getBodyBuffer().toString());
  // do not create another one
  Assert.assertSame(cachedInputStream, requestEx.getInputStream());
}
 
Example 20
Source Project: Tomcat8-Source-Read   Source File: Request.java    License: MIT License 5 votes vote down vote up
/**
 * @return the servlet input stream for this Request.  The default
 * implementation returns a servlet input stream created by
 * <code>createInputStream()</code>.
 *
 * @exception IllegalStateException if <code>getReader()</code> has
 *  already been called for this request
 * @exception IOException if an input/output error occurs
 */
@Override
public ServletInputStream getInputStream() throws IOException {

    if (usingReader) {
        throw new IllegalStateException(sm.getString("coyoteRequest.getInputStream.ise"));
    }

    usingInputStream = true;
    if (inputStream == null) {
        inputStream = new CoyoteInputStream(inputBuffer);
    }
    return inputStream;

}
 
Example 21
/**
 * Returns an input stream backed by the saved body data.
 * @return ServletInputStream the Servlet input stream object
 * @throws IOException if we can not get the Servlet input stream
 */
public ServletInputStream getInputStream() throws IOException
{
    if (this._bodyInfoData != null)
    {
        return new ExServletInputStream(new ByteArrayInputStream(this._bodyInfoData));
    }
    return super.getInputStream();
}
 
Example 22
Source Project: DimpleBlog   Source File: XssHttpServletRequestWrapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ServletInputStream getInputStream() throws IOException {
    // 非json类型,直接返回
    if (!isJsonRequest()) {
        return super.getInputStream();
    }

    // 为空,直接返回
    String json = IOUtils.toString(super.getInputStream(), StandardCharsets.UTF_8);
    if (StringUtils.isEmpty(json)) {
        return super.getInputStream();
    }

    // xss过滤
    json = EscapeUtil.clean(json).trim();
    final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
    return new ServletInputStream() {
        @Override
        public boolean isFinished() {
            return true;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener readListener) {
        }

        @Override
        public int read() throws IOException {
            return bis.read();
        }
    };
}
 
Example 23
Source Project: Tomcat8-Source-Read   Source File: TestUpgrade.java    License: MIT License 5 votes vote down vote up
@Override
public void init(WebConnection connection) {

    try (ServletInputStream sis = connection.getInputStream();
         ServletOutputStream sos = connection.getOutputStream()){
        byte[] buffer = new byte[8192];
        int read;
        while ((read = sis.read(buffer)) >= 0) {
            sos.write(buffer, 0, read);
            sos.flush();
        }
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    }
}
 
Example 24
Source Project: selenium   Source File: CrossDomainRpcLoaderTest.java    License: Apache License 2.0 5 votes vote down vote up
private HttpServletRequest createJsonRequest(
    String method,
    String path,
    Object data) throws IOException {
  when(mockRequest.getHeader("content-type")).thenReturn("application/json");

  Map<String, Object> payload = new TreeMap<>();
  payload.put("method", method);
  payload.put("path", path);
  payload.put("data", data);

  InputStream stream = new ByteArrayInputStream(new Json().toJson(payload).getBytes(UTF_8));
  when(mockRequest.getInputStream()).thenReturn(new ServletInputStream() {
    @Override
    public int read() throws IOException {
      return stream.read();
    }

    @Override
    public boolean isFinished() {
      return false;
    }

    @Override
    public boolean isReady() {
      return true;
    }

    @Override
    public void setReadListener(ReadListener readListener) {
      throw new UnsupportedOperationException();
    }
  });

  return mockRequest;
}
 
Example 25
Source Project: Tomcat8-Source-Read   Source File: TestUpgrade.java    License: MIT License 5 votes vote down vote up
@Override
public void init(WebConnection connection) {
    ServletInputStream sis;
    try {
        sis = connection.getInputStream();
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    }
    sis.setReadListener(null);
}
 
Example 26
Source Project: Tomcat8-Source-Read   Source File: TestUpgrade.java    License: MIT License 5 votes vote down vote up
@Override
public void init(WebConnection connection) {
    ServletInputStream sis;
    ServletOutputStream sos;
    try {
        sis = connection.getInputStream();
        sos = connection.getOutputStream();
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    }
    sos.setWriteListener(new NoOpWriteListener());
    ReadListener rl = new NoOpReadListener();
    sis.setReadListener(rl);
    sis.setReadListener(rl);
}
 
Example 27
Source Project: micro-integrator   Source File: MeteredServletRequest.java    License: Apache License 2.0 5 votes vote down vote up
public ServletInputStream getInputStream() throws IOException {
	if (wrappedInputStream == null) {
		ServletInputStream is = wrappedHttpServletRequest.getInputStream();
		wrappedInputStream = new MeteringInputStream(is);
	}
	return wrappedInputStream;
}
 
Example 28
Source Project: sdb-mall   Source File: XssHttpServletRequestWrapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ServletInputStream getInputStream() throws IOException {
    //非json类型,直接返回
    if(!MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(super.getHeader(HttpHeaders.CONTENT_TYPE))){
        return super.getInputStream();
    }

    //为空,直接返回
    String json = IOUtils.toString(super.getInputStream(), "utf-8");
    if (StringUtils.isBlank(json)) {
        return super.getInputStream();
    }

    //xss过滤
    json = xssEncode(json);
    final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes("utf-8"));
    return new ServletInputStream() {
        @Override
        public boolean isFinished() {
            return true;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener readListener) {

        }

        @Override
        public int read() throws IOException {
            return bis.read();
        }
    };
}
 
Example 29
Source Project: uavstack   Source File: RewriteIvcRequestWrapper.java    License: Apache License 2.0 5 votes vote down vote up
private ServletInputStream wrapServletInputStream() throws IOException {

        if (rewriteInputStream == null) {
            try {
                ServletInputStream inputStream = request.getInputStream();
                rewriteInputStream = new RewriteIvcInputStream(inputStream, request.getCharacterEncoding());
            }
            catch (IOException e) {
                builder = new StringBuilder(e.toString());
                throw e;
            }
        }

        return rewriteInputStream;
    }
 
Example 30
Source Project: SuperBoot   Source File: RequestBodyDecryptWrapper.java    License: MIT License 5 votes vote down vote up
@Override
public ServletInputStream getInputStream() throws IOException {
    if (requestBody == null) {
        requestBody = new byte[0];
    }
    //变更请求内容
    setRequestBody();
    final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);
    return new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return bais.read();
        }

        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener listener) {

        }
    };
}