javax.servlet.ServletInputStream Java Examples
The following examples show how to use
javax.servlet.ServletInputStream.
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 File: FileHandlerV1.java From orion.server with Eclipse Public License 1.0 | 6 votes |
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 #2
Source File: WeixinUrlFilter.java From weixin4j with Apache License 2.0 | 6 votes |
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 #3
Source File: WebUtil.java From hdw-dubbo with Apache License 2.0 | 6 votes |
/** * 复制输入流 * * @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 #4
Source File: HttpMock.java From wafer-java-server-sdk with MIT License | 6 votes |
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 File: Request.java From Tomcat7.0.67 with Apache License 2.0 | 6 votes |
/** * 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 #6
Source File: SoapTransportCommandProcessorTest.java From cougar with Apache License 2.0 | 6 votes |
/** * 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 #7
Source File: TestNonBlockingAPI.java From Tomcat8-Source-Read with MIT License | 6 votes |
@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
Source File: CharRequestWrapper.java From botwall4j with Apache License 2.0 | 6 votes |
@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 #9
Source File: IdentityAsserterHttpServletRequestWrapper.java From knox with Apache License 2.0 | 6 votes |
@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 #10
Source File: TestNonBlockingAPI.java From Tomcat8-Source-Read with MIT License | 6 votes |
@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 #11
Source File: TestStandardHttpServletRequestEx.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@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 #12
Source File: IngestServlet.java From realtime-analytics with GNU General Public License v2.0 | 6 votes |
@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 #13
Source File: TestVertxServerRequestToHttpServletRequest.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@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 #14
Source File: RequestWrapper.java From spring-boot-demo with MIT License | 6 votes |
/** * 复制输入流 * @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 File: CRUDServletPostTest.java From cumulusrdf with Apache License 2.0 | 6 votes |
/** * 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 File: EarlyCloseClientServlet.java From quarkus-http with Apache License 2.0 | 6 votes |
@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 File: LivyDispatch.java From knox with Apache License 2.0 | 6 votes |
@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 #18
Source File: DefaultDispatchTest.java From knox with Apache License 2.0 | 6 votes |
@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 #19
Source File: CustomHttpServletRequestWrapper.java From NFVO with Apache License 2.0 | 6 votes |
@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 #20
Source File: MockHttpServletRequest.java From spring-analysis-note with MIT License | 5 votes |
@Override public ServletInputStream getInputStream() { if (this.inputStream != null) { return this.inputStream; } else if (this.reader != null) { throw new IllegalStateException( "Cannot call getInputStream() after getReader() has already been called for the current request") ; } this.inputStream = (this.content != null ? new DelegatingServletInputStream(new ByteArrayInputStream(this.content)) : EMPTY_SERVLET_INPUT_STREAM); return this.inputStream; }
Example #21
Source File: RequestInfoForLoggingServletApiAdapterTest.java From backstopper with Apache License 2.0 | 5 votes |
@Test public void testGetBodyWithNullCharacterEncodingReturnsCorrectBody() throws Exception { String expected = "this is the expected string"; ByteArrayInputStream bais = new ByteArrayInputStream(expected.getBytes()); try (ServletInputStream is = new DelegatingServletInputStream(bais)) { doReturn(is).when(requestMock).getInputStream(); String actual = adapter.getBody(); assertThat(actual, is(expected)); } }
Example #22
Source File: RewriteIvcRequestWrapper.java From uavstack with Apache License 2.0 | 5 votes |
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 #23
Source File: ResourceUploadRequestTest.java From selenium-grid-extensions with Apache License 2.0 | 5 votes |
private Answer verifyRequestContent() { return new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { HttpServletRequest req = (HttpServletRequest) invocationOnMock.getArguments()[0]; HttpServletResponse resp = (HttpServletResponse) invocationOnMock.getArguments()[1]; File tempFile = File.createTempFile("temp_resources", ".zip"); try (ServletInputStream inputStream = req.getInputStream(); OutputStream outputStream = new FileOutputStream(tempFile)) { IOUtils.copy(inputStream, outputStream); } File tempDir = Files.createTempDir(); ZipUtil.unpack(tempFile, tempDir); File firstTxtFile = new File(tempDir, "files_for_upload/first.txt"); File secondTxtFile = new File(tempDir, "files_for_upload/directory/second.txt"); assertTrue(firstTxtFile.exists()); assertTrue(secondTxtFile.exists()); //verify content String firstFileContent = Files.toString(firstTxtFile, Charset.defaultCharset()); assertThat(firstFileContent, containsString("content1")); String secondFileContent = Files.toString(secondTxtFile, Charset.defaultCharset()); assertThat(secondFileContent, containsString("content2")); //clean temp directories FileUtils.deleteDirectory(tempDir); assertTrue("Failed to delete uploaded zip", tempFile.delete()); //form response resp.getWriter().write(EXPECTED_RETURN_FOLDER); return null; } }; }
Example #24
Source File: ContentCachingRequestWrapper.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public ServletInputStream getInputStream() throws IOException { if (this.inputStream == null) { this.inputStream = new ContentCachingInputStream(getRequest().getInputStream()); } return this.inputStream; }
Example #25
Source File: JsonApiServlet.java From BIMserver with GNU Affero General Public License v3.0 | 5 votes |
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getHeader("Origin") != null && (getBimServer().getServerInfo().getServerState() != ServerState.MIGRATION_REQUIRED && !getBimServer().getServerSettingsCache().isHostAllowed(request.getHeader("Origin")))) { response.setStatus(403); return; } response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setCharacterEncoding("UTF-8"); try { ServletInputStream inputStream = request.getInputStream(); byte[] bytes = IOUtils.toByteArray(inputStream); // Not streaming here, because we want to be able to show the request-data when it's not valid if (LOGGER.isDebugEnabled()) { LOGGER.debug("Incoming JSON " + new String(bytes, Charsets.UTF_8)); } ObjectNode parse = OBJECT_MAPPER.readValue(new ByteArrayInputStream(bytes), ObjectNode.class); if (parse instanceof ObjectNode) { ObjectNode jsonRequest = (ObjectNode) parse; response.setHeader("Content-Type", "application/json"); getBimServer().getJsonHandler().execute(jsonRequest, request, response.getWriter()); } else { LOGGER.error("Invalid JSON request: " + new String(bytes, Charsets.UTF_8)); response.setStatus(500); } } catch (IOException e) { LOGGER.error("", e); response.setStatus(500); } }
Example #26
Source File: BatchItemRequest.java From syncope with Apache License 2.0 | 5 votes |
public BatchItemRequest( final String basePath, final HttpServletRequest request, final BatchRequestItem batchItem) { super(request); this.basePath = basePath; this.batchItem = batchItem; this.inputStream = new ServletInputStream() { private final ByteArrayInputStream bais = new ByteArrayInputStream(batchItem.getContent().getBytes()); private boolean isFinished = false; private boolean isReady = true; @Override public boolean isFinished() { return isFinished; } @Override public boolean isReady() { return isReady; } @Override public void setReadListener(final ReadListener readListener) { // nope } @Override public int read() { isFinished = true; isReady = false; return bais.read(); } }; }
Example #27
Source File: WebSocketVirtualServletRequest.java From cxf with Apache License 2.0 | 5 votes |
@Override public ServletInputStream getInputStream() throws IOException { return new ServletInputStream() { @Override public int read() throws IOException { return in.read(); } @Override public int read(byte[] b, int off, int len) throws IOException { return in.read(b, off, len); } @Override public boolean isFinished() { throw new UnsupportedOperationException(); } @Override public boolean isReady() { throw new UnsupportedOperationException(); } @Override public void setReadListener(ReadListener arg0) { throw new UnsupportedOperationException(); } }; }
Example #28
Source File: FilterPre.java From roncoo-education with MIT License | 5 votes |
private HttpServletRequestWrapper requestWrapper(HttpServletRequest request, Long userNo) throws IOException { Map<String, Object> map = getParamMap(request); map.put(USERNO, userNo); String newBody = JSONUtil.toJSONString(map); logger.info("转发参数={}", newBody); final byte[] reqBodyBytes = newBody.getBytes(); return new HttpServletRequestWrapper(request) { @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream())); } @Override public ServletInputStream getInputStream() throws IOException { return new ServletInputStreamWrapper(reqBodyBytes); } @Override public int getContentLength() { return reqBodyBytes.length; } @Override public long getContentLengthLong() { return reqBodyBytes.length; } }; }
Example #29
Source File: TestHttpServletRequest.java From rack-servlet with Apache License 2.0 | 5 votes |
@Override public ServletInputStream getInputStream() throws IOException { final InputStream stream = new ByteArrayInputStream(body.getBytes()); return new ServletInputStream() { @Override public int read() throws IOException { return stream.read(); } }; }
Example #30
Source File: LittleTsaService.java From littleca with Apache License 2.0 | 5 votes |
private TimeStampRequest readRequest(HttpServletRequest req, boolean isBase64) throws Exception { byte[] requestBytes = new byte[req.getContentLength()]; ServletInputStream inputStream = req.getInputStream(); IOUtils.read(inputStream, requestBytes); if (isBase64) { return new TimeStampRequest(Base64.decode(requestBytes)); } else { return new TimeStampRequest(requestBytes); } }