java类javax.servlet.ServletInputStream的实例源码

TestStandardHttpServletRequestEx.java 文件源码 项目:incubator-servicecomb-java-chassis 阅读 36 收藏 0 点赞 0 评论 0
@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));
  Assert.assertEquals("abc", requestEx.getBodyBuffer().toString());
  // do not create another one
  Assert.assertSame(cachedInputStream, requestEx.getInputStream());
}
TestVertxServerRequestToHttpServletRequest.java 文件源码 项目:incubator-servicecomb-java-chassis 阅读 38 收藏 0 点赞 0 评论 0
@Test
public void testGetInputStream() throws IOException {
  Buffer body = Buffer.buffer();
  body.appendByte((byte) 1);

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

  ServletInputStream is = request.getInputStream();
  Assert.assertSame(is, request.getInputStream());
  int value = is.read();
  is.close();
  Assert.assertEquals(1, value);
}
ApiServlet.java 文件源码 项目:Webhook_server 阅读 37 收藏 0 点赞 0 评论 0
/**
 * 获取客户端get/post方法上传来的参数信息,并转换为
 * <code>map<String,String></code>形式
 */
private HashMap<String, String> getReqParaMap(ServletInputStream is) throws IOException {
    byte[] buf = new byte[1024];
    int len;
    StringBuffer sb = new StringBuffer();
    while ((len = is.read(buf)) != -1) {
        sb.append(new String(buf, 0, len));
    }

    String paraStr = sb.toString();
    HashMap<String, String> paraMap = new HashMap<>();
    if (paraStr.length() > 0) {
        String[] split = paraStr.split("&");
        for (String aSplit : split) {
            String[] entry = aSplit.split("=");
            paraMap.put(entry[0], entry[1]);
        }
    }
    return paraMap;
}
PublicApiHttpServletRequest.java 文件源码 项目:alfresco-remote-api 阅读 37 收藏 0 点赞 0 评论 0
private static HttpServletRequest getWrappedHttpServletRequest(HttpServletRequest request) throws IOException
{
    //TODO is it really necessary to wrap the request into a BufferedInputStream?
    // If not, then we could remove the check for multipart upload. 
    // The check is needed as we get an IOException (Resetting to invalid mark) for files more than 8193 bytes. 
    boolean resetSupported = true;
    String contentType = request.getHeader(HEADER_CONTENT_TYPE);
    if (contentType != null && contentType.startsWith(MULTIPART_FORM_DATA))
    {
       resetSupported = false;
    }
    final PublicApiServletInputStream sis = new PublicApiServletInputStream(request.getInputStream(), resetSupported);
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request)
    {
        public ServletInputStream getInputStream() throws java.io.IOException
        {
            return sis;
        }
    };
    return wrapper;
}
Request.java 文件源码 项目:tomcat7 阅读 37 收藏 0 点赞 0 评论 0
/**
 * 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;

}
ProtobufHandler.java 文件源码 项目:ja-micro 阅读 32 收藏 0 点赞 0 评论 0
private Message readRpcBody(ServletInputStream in,
                            Class<? extends Message> requestClass) throws Exception {
    byte chunkSize[] = new byte[4];
    in.read(chunkSize);
    int size = Ints.fromByteArray(chunkSize);
    if (size == 0) {
        return ProtobufUtil.newEmptyMessage(requestClass);
    }
    if (size > ProtobufUtil.MAX_BODY_CHUNK_SIZE) {
        String message = "Invalid body chunk size: " + size;
        throw new RpcReadException(chunkSize, in, message);
    }
    byte bodyData[] = readyFully(in, size);
    Message pbRequest = ProtobufUtil.byteArrayToProtobuf(bodyData, requestClass);
    return pbRequest;
}
ProtobufHandler.java 文件源码 项目:ja-micro 阅读 36 收藏 0 点赞 0 评论 0
private byte[] readyFully(ServletInputStream in, int totalSize) throws Exception {
    byte[] retval = new byte[totalSize];
    int bytesRead = 0;
    while (bytesRead < totalSize) {
        try {
            int read = in.read(retval, bytesRead, totalSize - bytesRead);
            if (read == -1) {
                throw new RpcCallException(RpcCallException.Category.InternalServerError,
                        "Unable to read complete request or response");
            }
            bytesRead += read;
        } catch (IOException e) {
            throw new RpcCallException(RpcCallException.Category.InternalServerError,
                    "IOException reading data: " + e);
        }
    }
    return retval;
}
RpcReadExceptionTest.java 文件源码 项目:ja-micro 阅读 37 收藏 0 点赞 0 评论 0
public void testBodyReading(String first, String second) throws IOException {
    ServletInputStream x = (ServletInputStream) new RpcHandlerTest_InputStream(second);
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    Map<String, Set<String>> headers = new TreeMap<>();
    when(request.getHeaderNames())
            .thenReturn(
                    new RpcReadExceptionTest.RpcHandlerTest_IteratorEnumeration<>(headers.keySet().iterator())
            );

    when(request.getInputStream()).thenReturn(x);
    when(request.getRequestURL())
            .thenReturn(new StringBuffer("http://fizz.buzz"));

    RpcReadException rpcReadException = new RpcReadException(first.getBytes(), x, "i am a message");
    String json = rpcReadException.toJson(request);

    try {
        JsonElement root = new JsonParser().parse(json);
        JsonObject jsob = root.getAsJsonObject();
        JsonElement b = jsob.get("request_body");
        Assert.assertNotNull(b);
        Assert.assertEquals(first+second, this.decode(b.getAsString()));
    } catch (Exception ex) {
        Assert.fail(ex.toString());
    }
}
BufferedRequestWrapperTest.java 文件源码 项目:crnk-framework 阅读 31 收藏 0 点赞 0 评论 0
@Test
public void onDataInRequestShouldReturnThisData() throws Exception {
    // GIVEN
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream("hello".getBytes());
    when(request.getInputStream()).thenReturn(new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return byteArrayInputStream.read();
        }
    });

    // WHEN
    BufferedRequestWrapper sut = new BufferedRequestWrapper(request);
    ServletInputStream inputStream = sut.getInputStream();

    // THEN
    assertThat(inputStream).hasSameContentAs(new ByteArrayInputStream("hello".getBytes()));
}
TestBLOBHandler.java 文件源码 项目:flume-release-1.7.0 阅读 31 收藏 0 点赞 0 评论 0
@SuppressWarnings({ "rawtypes" })
@Test(expected = IllegalArgumentException.class)
public void testMissingParameters() throws Exception {
  Map requestParameterMap = new HashMap();

  HttpServletRequest req = mock(HttpServletRequest.class);
  final String tabData = "a\tb\tc";

  ServletInputStream servletInputStream = new DelegatingServletInputStream(
      new ByteArrayInputStream(tabData.getBytes()));

  when(req.getInputStream()).thenReturn(servletInputStream);
  when(req.getParameterMap()).thenReturn(requestParameterMap);

  Context context = mock(Context.class);
  when(
      context.getString(BLOBHandler.MANDATORY_PARAMETERS,
          BLOBHandler.DEFAULT_MANDATORY_PARAMETERS)).thenReturn("param1");

  handler.configure(context);

  handler.getEvents(req);

}
ServletWebSocketHttpExchange.java 文件源码 项目:lams 阅读 31 收藏 0 点赞 0 评论 0
@Override
public IoFuture<byte[]> readRequestData() {
    final ByteArrayOutputStream data = new ByteArrayOutputStream();
    try {
        final ServletInputStream in = request.getInputStream();
        byte[] buf = new byte[1024];
        int r;
        while ((r = in.read(buf)) != -1) {
            data.write(buf, 0, r);
        }
        return new FinishedIoFuture<>(data.toByteArray());
    } catch (IOException e) {
        final FutureResult<byte[]> ioFuture = new FutureResult<>();
        ioFuture.setException(e);
        return ioFuture.getIoFuture();
    }
}
FileStoreController.java 文件源码 项目:S3Mock 阅读 36 收藏 0 点赞 0 评论 0
/**
 * Adds an object to a bucket.
 *
 * http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html
 *
 * @param bucketName the Bucket in which to store the file in.
 * @param request http servlet request
 * @return ResponseEntity with Status Code and ETag
 */
@RequestMapping(value = "/{bucketName:.+}/**", method = RequestMethod.PUT)
public ResponseEntity<String> putObject(@PathVariable final String bucketName,
    final HttpServletRequest request) {
  final String filename = filenameFrom(bucketName, request);
  try (ServletInputStream inputStream = request.getInputStream()) {
    final S3Object s3Object = fileStore.putS3Object(bucketName,
        filename,
        request.getContentType(),
        inputStream,
        isV4SigningEnabled(request));

    final HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setETag("\"" + s3Object.getMd5() + "\"");
    responseHeaders.setLastModified(s3Object.getLastModified());
    return new ResponseEntity<>(responseHeaders, HttpStatus.CREATED);
  } catch (final IOException e) {
    LOG.error("Object could not be saved!", e);
    return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
  }
}
BodyReaderWrapper.java 文件源码 项目:spring-boot-start-current 阅读 36 收藏 0 点赞 0 评论 0
@Override
public ServletInputStream getInputStream () throws IOException {
    if ( null == body ) {
        return super.getInputStream();
    }
    final ByteArrayInputStream inputStream = new ByteArrayInputStream( body );
    return new ServletInputStream() {
        @Override
        public boolean isFinished () {
            return false;
        }

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

        @Override
        public void setReadListener ( ReadListener readListener ) {

        }

        @Override
        public int read () throws IOException {
            return inputStream.read();
        }
    };
}
Request.java 文件源码 项目:apache-tomcat-7.0.73-with-comment 阅读 32 收藏 0 点赞 0 评论 0
/**
 * 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;

}
VertxServerRequestToHttpServletRequest.java 文件源码 项目:incubator-servicecomb-java-chassis 阅读 61 收藏 0 点赞 0 评论 0
@Override
public ServletInputStream getInputStream() throws IOException {
  if (inputStream == null) {
    inputStream = new BufferInputStream(context.getBody().getByteBuf());
  }
  return inputStream;
}
StandardHttpServletRequestEx.java 文件源码 项目:incubator-servicecomb-java-chassis 阅读 36 收藏 0 点赞 0 评论 0
@Override
public ServletInputStream getInputStream() throws IOException {
  if (this.inputStream == null) {
    if (cacheRequest) {
      byte inputBytes[] = IOUtils.toByteArray(getRequest().getInputStream());
      ByteBuf byteBuf = Unpooled.wrappedBuffer(inputBytes);
      this.inputStream = new BufferInputStream(byteBuf);
      setBodyBuffer(Buffer.buffer(Unpooled.wrappedBuffer(byteBuf)));
    } else {
      this.inputStream = getRequest().getInputStream();
    }
  }
  return this.inputStream;
}
XssHttpServletRequestWrapper.java 文件源码 项目:my-spring-boot-project 阅读 34 收藏 0 点赞 0 评论 0
@Override
public ServletInputStream getInputStream() throws IOException {
    //非json类型,直接返回
    if (!super.getHeader(HttpHeaders.CONTENT_TYPE).equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
        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 false;
        }

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

        @Override
        public void setReadListener(ReadListener readListener) {

        }

        @Override
        public int read() throws IOException {
            return bis.read();
        }
    };
}
ApiServlet.java 文件源码 项目:Webhook_server 阅读 30 收藏 0 点赞 0 评论 0
/**
 * 处理gira 的 hook 请求
 */
private void processGiraHook(HttpServletRequest req) throws IOException {
    ServletInputStream inputStream = req.getInputStream();
    JiraBugEventBean bean = convertBody(inputStream, JiraBugEventBean.class);
    if (bean != null) {
        String event = bean.getWebhookEvent();
        JiraBugEventBean.IssueBean issue = bean.getIssue();
        JiraBugEventBean.IssueBean.FieldsBean fields = issue.getFields();

        List<String> affectLabels = fields.getLabels();//测试版本号
        String type = fields.getIssuetype().getName();//issue类型,如 Bug
        String projectName = fields.getProject().getKey();

        String creatorName = fields.getCreator().getDisplayName();
        String summary = fields.getSummary();// bug标题
        String keyId = issue.getKey();// bug编号,如 UPLUSGO-1241
        String url = Params.jiraBrowseUrl + keyId;//issue详情访问网址
        String assigneeName = fields.getAssignee().getDisplayName();//bug归属人

        StringBuilder sb = new StringBuilder();
        sb.append(event).append("\n")
                .append("类型: ").append(type).append("\n")
                .append("版本: ").append(affectLabels).append("\n")
                .append("项目: ").append(projectName).append("\n")
                .append("创建: ").append(creatorName).append("\n")
                .append("概要: ").append(summary).append("\n")
                .append("查看: ").append(url).append("\n")
                .append("服务器时间: ").append(TimeUtil.msec2date(System.currentTimeMillis()));

        httpUtil.sendTextMsg(assigneeName, sb.toString());
    }
}
AccessLogFilter.java 文件源码 项目:dremio-oss 阅读 34 收藏 0 点赞 0 评论 0
@Override
public ServletInputStream getInputStream() throws IOException {
  final ServletInputStream inputStream = d.getInputStream();
  return new ServletInputStream() {

    @Override
    public int read() throws IOException {
      int b = inputStream.read();
      if (b != -1) {
        reqBody.write(b);
      }
      return b;
    }

    @Override
    public void setReadListener(ReadListener readListener) {
      inputStream.setReadListener(readListener);
    }

    @Override
    public boolean isReady() {
      return inputStream.isReady();
    }

    @Override
    public boolean isFinished() {
      return inputStream.isFinished();
    }
  };
}
SampleProtocolHandler.java 文件源码 项目:Mastering-Java-EE-Development-with-WildFly 阅读 38 收藏 0 点赞 0 评论 0
@Override
public void init(WebConnection wc) {
    try (ServletInputStream input = wc.getInputStream(); ServletOutputStream output = wc.getOutputStream();) {
        output.write(("upgrade" + CRLF).getBytes());
        output.write(("received" + CRLF).getBytes());
        output.write("END".getBytes());
    } catch (IOException ex) {
    }
}
JsonRequestWrapper.java 文件源码 项目:wxcard 阅读 34 收藏 0 点赞 0 评论 0
@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();
      }

@Override
public boolean isFinished() {
    // TODO Auto-generated method stub
    return false;
}

@Override
public boolean isReady() {
    // TODO Auto-generated method stub
    return false;
}

@Override
public void setReadListener(ReadListener readListener) {
    // TODO Auto-generated method stub

}
    };
    return servletInputStream;
  }
JsonContentCachingRequestWrapper.java 文件源码 项目:plumdo-stock 阅读 33 收藏 0 点赞 0 评论 0
@Override
public ServletInputStream getInputStream() throws IOException {
    if (this.inputStream == null) {
        this.inputStream = new ContentCachingInputStream(getRequest().getInputStream());
    }
    return this.inputStream;
}
Request.java 文件源码 项目:tomcat7 阅读 33 收藏 0 点赞 0 评论 0
/**
 * Create and return a ServletInputStream to read the content
 * associated with this Request.
 *
 * @exception IOException if an input/output error occurs
 */
public ServletInputStream createInputStream()
    throws IOException {
    if (inputStream == null) {
        inputStream = new CoyoteInputStream(inputBuffer);
    }
    return inputStream;
}
RequestFacade.java 文件源码 项目:tomcat7 阅读 44 收藏 0 点赞 0 评论 0
@Override
public ServletInputStream getInputStream() throws IOException {

    if (request == null) {
        throw new IllegalStateException(
                        sm.getString("requestFacade.nullRequest"));
    }

    return request.getInputStream();
}
ProtobufHandler.java 文件源码 项目:ja-micro 阅读 37 收藏 0 点赞 0 评论 0
private RpcEnvelope.Request readRpcEnvelope(ServletInputStream in) throws Exception {
    byte chunkSize[] = new byte[4];
    in.read(chunkSize);
    int size = Ints.fromByteArray(chunkSize);
    if (size <= 0 || size > ProtobufUtil.MAX_HEADER_CHUNK_SIZE) {
        String message = "Invalid header chunk size: " + size;
        throw new RpcReadException(chunkSize, in, message);
    }
    byte headerData[] = readyFully(in, size);
    RpcEnvelope.Request rpcRequest = RpcEnvelope.Request.parseFrom(headerData);
    return rpcRequest;
}
HeidelpayResponseServlet.java 文件源码 项目:oscm 阅读 37 收藏 0 点赞 0 评论 0
/**
 * Converts the input given in the request to a properties object.
 * 
 * @param request
 *            The received request.
 * @return The properties contained in the request.
 * @throws IOException
 *             Thrown in case the request information could not be
 *             evaluated.
 */
private Properties extractPSPParameters(HttpServletRequest request)
        throws IOException {

    Properties props = new Properties();
    ServletInputStream inputStream = request.getInputStream();
    if (inputStream == null) {
        return props;
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(
            inputStream, "UTF-8"));
    String line = br.readLine();
    StringBuffer sb = new StringBuffer();
    while (line != null) {
        sb.append(line);
        line = br.readLine();
    }
    String params = sb.toString();
    StringTokenizer st = new StringTokenizer(params, "&");
    while (st.hasMoreTokens()) {
        String nextToken = st.nextToken();
        String[] splitResult = nextToken.split("=");
        String key = splitResult[0];
        String value = "";
        if (splitResult.length > 1) {
            value = URLDecoder.decode(splitResult[1], "UTF-8");
        }
        props.setProperty(key, value);
    }

    return props;
}
PSPResponse.java 文件源码 项目:oscm 阅读 44 收藏 0 点赞 0 评论 0
/**
 * Converts the input given in the request to a properties object.
 * 
 * @param request
 *            The received request.
 * @return The properties contained in the request.
 * @throws IOException
 *             Thrown in case the request information could not be
 *             evaluated.
 */
private boolean determinePSPParams(HttpServletRequest request, Properties p) {


    try {
        ServletInputStream inputStream = request.getInputStream();
        if (inputStream == null) {
            return false;
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(
                inputStream, "UTF-8"));
        String line = br.readLine();
        StringBuffer sb = new StringBuffer();
        while (line != null) {
            sb.append(line);
            line = br.readLine();
        }
        String params = sb.toString();
        StringTokenizer st = new StringTokenizer(params, "&");
        while (st.hasMoreTokens()) {
            String nextToken = st.nextToken();
            String[] splitResult = nextToken.split("=");
            String key = splitResult[0];
            String value = "";
            if (splitResult.length > 1) {
                value = URLDecoder.decode(splitResult[1], "UTF-8");
            }
            p.setProperty(key, value);
        }
        return validateResponse(p);
    } catch (IOException e) {
        // if the request information cannot be read, we cannot determine
        // whether the registration worked or not. Hence we assume it
        // failed, log a warning and return the failure-URL to the PSP.
        logger.logWarn(Log4jLogger.SYSTEM_LOG, e,
                LogMessageIdentifier.WARN_HEIDELPAY_INPUT_PROCESS_FAILED);
    }

    return false;
}
HttpServletRequestStub.java 文件源码 项目:oscm 阅读 40 收藏 0 点赞 0 评论 0
@Override
public ServletInputStream getInputStream() throws IOException {

    if (throwExceptionForISAccess) {
        throw new IOException();
    }
    return new BufferedServletInputStream(new StringBufferInputStream(
            bodyContent));
}
BufferedRequestWrapper.java 文件源码 项目:crnk-framework 阅读 36 收藏 0 点赞 0 评论 0
@Override
public ServletInputStream getInputStream() throws IOException {
    if (bufferedRequest == null) {
        return null;
    }
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bufferedRequest.getBytes());
    return new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return byteArrayInputStream.read();
        }
    };
}
TestBLOBHandler.java 文件源码 项目:flume-release-1.7.0 阅读 33 收藏 0 点赞 0 评论 0
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testCSVData() throws Exception {
  Map requestParameterMap = new HashMap();
  requestParameterMap.put("param1", new String[] { "value1" });
  requestParameterMap.put("param2", new String[] { "value2" });

  HttpServletRequest req = mock(HttpServletRequest.class);
  final String csvData = "a,b,c";

  ServletInputStream servletInputStream = new DelegatingServletInputStream(
      new ByteArrayInputStream(csvData.getBytes()));

  when(req.getInputStream()).thenReturn(servletInputStream);
  when(req.getParameterMap()).thenReturn(requestParameterMap);

  Context context = mock(Context.class);
  when(
      context.getString(BLOBHandler.MANDATORY_PARAMETERS,
          BLOBHandler.DEFAULT_MANDATORY_PARAMETERS)).thenReturn(
      "param1,param2");

  handler.configure(context);
  List<Event> deserialized = handler.getEvents(req);
  assertEquals(1, deserialized.size());
  Event e = deserialized.get(0);

  assertEquals(new String(e.getBody()), csvData);
  assertEquals(e.getHeaders().get("param1"), "value1");
  assertEquals(e.getHeaders().get("param2"), "value2");
}


问题


面经


文章

微信
公众号

扫码关注公众号