@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()); }
@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); }
/** * 获取客户端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; }
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; }
/** * 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; }
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; }
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; }
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()); } }
@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())); }
@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); }
@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(); } }
/** * 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); } }
@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(); } }; }
@Override public ServletInputStream getInputStream() throws IOException { if (inputStream == null) { inputStream = new BufferInputStream(context.getBody().getByteBuf()); } return inputStream; }
@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; }
@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(); } }; }
/** * 处理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()); } }
@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(); } }; }
@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) { } }
@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; }
@Override public ServletInputStream getInputStream() throws IOException { if (this.inputStream == null) { this.inputStream = new ContentCachingInputStream(getRequest().getInputStream()); } return this.inputStream; }
/** * 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; }
@Override public ServletInputStream getInputStream() throws IOException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getInputStream(); }
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; }
/** * 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; }
/** * 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; }
@Override public ServletInputStream getInputStream() throws IOException { if (throwExceptionForISAccess) { throw new IOException(); } return new BufferedServletInputStream(new StringBufferInputStream( bodyContent)); }
@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(); } }; }
@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"); }
@SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testTabData() throws Exception { Map requestParameterMap = new HashMap(); requestParameterMap.put("param1", new String[] { "value1" }); 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); List<Event> deserialized = handler.getEvents(req); assertEquals(1, deserialized.size()); Event e = deserialized.get(0); assertEquals(new String(e.getBody()), tabData); assertEquals(e.getHeaders().get("param1"), "value1"); }
public FlumeHttpServletRequestWrapper(final byte[] data) { stream = new ServletInputStream() { private final InputStream in = new ByteArrayInputStream(data); @Override public int read() throws IOException { return in.read(); } }; }
public RewriteIvcInputStream(ServletInputStream inputStream, String encoding) { this.inputStream = inputStream; this.encoding = StringHelper.isEmpty(encoding) ? "utf-8" : encoding; if ("iso-8859-1".equalsIgnoreCase(encoding)) { this.encoding = "utf-8"; } }
public ServletInputStream getInputStream() throws IOException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getInputStream(); }
@Override public ServletInputStream getInputStream() throws IOException { if (reader != null) { throw UndertowServletMessages.MESSAGES.getReaderAlreadyCalled(); } if(servletInputStream == null) { servletInputStream = new ServletInputStreamImpl(this); } readStarted = true; return servletInputStream; }
/** * 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 */ public ServletInputStream getInputStream() throws IOException { if (reader != null) throw new IllegalStateException (sm.getString("requestBase.getInputStream.ise")); if (stream == null) stream = createInputStream(); return (stream); }
/** * Adds an encrypted 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 encryption The encryption type. * @param kmsKeyId The KMS encryption key id. * @param request http servlet request. * * @return {@link ResponseEntity} with Status Code and empty ETag. * * @throws IOException in case of an error on storing the object. */ @RequestMapping( value = "/{bucketName:.+}/**", headers = { SERVER_SIDE_ENCRYPTION, SERVER_SIDE_ENCRYPTION_AWS_KMS_KEYID }, method = RequestMethod.PUT) public ResponseEntity<String> putObjectEncrypted(@PathVariable final String bucketName, @RequestHeader(value = SERVER_SIDE_ENCRYPTION) final String encryption, @RequestHeader(value = SERVER_SIDE_ENCRYPTION_AWS_KMS_KEYID) final String kmsKeyId, final HttpServletRequest request) throws IOException { final String filename = filenameFrom(bucketName, request); final S3Object s3Object; try (ServletInputStream inputStream = request.getInputStream()) { s3Object = fileStore.putS3ObjectWithKMSEncryption(bucketName, filename, request.getContentType(), inputStream, isV4SigningEnabled(request), encryption, kmsKeyId); final HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setETag("\"" + s3Object.getMd5() + "\""); responseHeaders.setLastModified(s3Object.getLastModified()); responseHeaders.add(SERVER_SIDE_ENCRYPTION_AWS_KMS_KEYID, kmsKeyId); return new ResponseEntity<>(responseHeaders, HttpStatus.CREATED); } }
/** * 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; }
@Override public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取请求资源 String proName = req.getServletContext().getContextPath(); String requestSource = req.getRequestURI(); requestSource = requestSource.substring(requestSource.indexOf(proName) + proName.length()); if (requestSource.startsWith("/es")) { requestSource = requestSource.substring(3); } /** * get url */ Map<String, ConnectionFailoverMgr> connectionMgrPool = EsResource.getConnMgr(); String forwarUrl = connectionMgrPool.get("es.info.forwar.url").getConnection() + requestSource; /** * get method */ String method = req.getMethod(); /** * get body */ ServletInputStream input = req.getInputStream(); EsResource.getHttpAsyncClient().doAsyncHttpMethodWithReqAsync(method, forwarUrl, null, input, null, null, "application/json", "utf-8", new EsRestServletCallBack(), req); }