类javax.servlet.ServletInputStream源码实例Demo

下面列出了怎么用javax.servlet.ServletInputStream的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: Tomcat7.0.67   文件: Request.java
/**
 * 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;

}
 
源代码2 项目: hdw-dubbo   文件: WebUtil.java
/**
 * 复制输入流
 *
 * @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;
}
 
源代码3 项目: weixin4j   文件: WeixinUrlFilter.java
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("");
    }
}
 
源代码4 项目: wafer-java-server-sdk   文件: HttpMock.java
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();
	}
}
 
/**
 * 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
}
 
源代码6 项目: botwall4j   文件: CharRequestWrapper.java
@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();
    }
  };
}
 
源代码7 项目: Tomcat8-Source-Read   文件: TestNonBlockingAPI.java
@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);
}
 
@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();
  }
}
 
源代码9 项目: Tomcat8-Source-Read   文件: TestNonBlockingAPI.java
@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);
}
 
源代码10 项目: knox   文件: DefaultDispatchTest.java
@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));
}
 
源代码11 项目: knox   文件: LivyDispatch.java
@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;
}
 
@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);
}
 
源代码13 项目: orion.server   文件: FileHandlerV1.java
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);
}
 
源代码14 项目: spring-boot-demo   文件: RequestWrapper.java
/**
 * 复制输入流
 * @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());
}
 
源代码15 项目: cumulusrdf   文件: CRUDServletPostTest.java
/**
 * 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);
}
 
源代码16 项目: quarkus-http   文件: EarlyCloseClientServlet.java
@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();
    }
}
 
源代码17 项目: NFVO   文件: CustomHttpServletRequestWrapper.java
@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();
    }
  };
}
 
源代码18 项目: realtime-analytics   文件: IngestServlet.java
@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);
    }
}
 
@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());
}
 
源代码20 项目: Tomcat8-Source-Read   文件: Request.java
/**
 * @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;

}
 
/**
 * 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();
}
 
源代码22 项目: DimpleBlog   文件: XssHttpServletRequestWrapper.java
@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();
        }
    };
}
 
源代码23 项目: Tomcat8-Source-Read   文件: TestUpgrade.java
@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);
    }
}
 
源代码24 项目: selenium   文件: CrossDomainRpcLoaderTest.java
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;
}
 
源代码25 项目: Tomcat8-Source-Read   文件: TestUpgrade.java
@Override
public void init(WebConnection connection) {
    ServletInputStream sis;
    try {
        sis = connection.getInputStream();
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    }
    sis.setReadListener(null);
}
 
源代码26 项目: Tomcat8-Source-Read   文件: TestUpgrade.java
@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);
}
 
源代码27 项目: micro-integrator   文件: MeteredServletRequest.java
public ServletInputStream getInputStream() throws IOException {
	if (wrappedInputStream == null) {
		ServletInputStream is = wrappedHttpServletRequest.getInputStream();
		wrappedInputStream = new MeteringInputStream(is);
	}
	return wrappedInputStream;
}
 
源代码28 项目: sdb-mall   文件: XssHttpServletRequestWrapper.java
@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();
        }
    };
}
 
源代码29 项目: uavstack   文件: RewriteIvcRequestWrapper.java
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;
    }
 
源代码30 项目: SuperBoot   文件: RequestBodyDecryptWrapper.java
@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) {

        }
    };
}
 
 类所在包
 同包方法