Java Code Examples for javax.servlet.ServletInputStream#read()

The following examples show how to use javax.servlet.ServletInputStream#read() . 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: TestNonBlockingAPI.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void onDataAvailable() throws IOException {
    ServletInputStream in = ctx.getRequest().getInputStream();
    String s = "";
    byte[] b = new byte[8192];
    int read = 0;
    do {
        read = in.read(b);
        if (read == -1) {
            break;
        }
        s += new String(b, 0, read);
    } while (in.isReady());
    log.info("Read [" + s + "]");
    body.append(s);
}
 
Example 2
Source File: TestNonBlockingAPI.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void onDataAvailable() throws IOException {
    ServletInputStream in = ctx.getRequest().getInputStream();
    String s = "";
    byte[] b = new byte[8192];
    int read = 0;
    do {
        read = in.read(b);
        if (read == -1) {
            break;
        }
        s += new String(b, 0, read);
    } while (ignoreIsReady || in.isReady());
    log.info(s);
    body.append(s);
}
 
Example 3
Source File: SockJsServletRequest.java    From AngularBeans with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void onDataAvailable() throws IOException {
	ServletInputStream inputStream = request.getInputStream();
	do {
		while (!inputStream.isReady()) {
			//
		}

		byte[] buffer = new byte[1024 * 4];
		int length = inputStream.read(buffer);
		if (length > 0) {
			if (onDataHandler != null) {
				try {
					onDataHandler.handle(Arrays.copyOf(buffer, length));
				} catch (SockJsException e) {
					throw new IOException(e);
				}
			}
		}
	} while (inputStream.isReady());
}
 
Example 4
Source File: PingServlet30Async.java    From sample.daytrader7 with Apache License 2.0 6 votes vote down vote up
/**
 * forwards post requests to the doGet method Creation date: (11/6/2000
 * 10:52:39 AM)
 *
 * @param res
 *            javax.servlet.http.HttpServletRequest
 * @param res2
 *            javax.servlet.http.HttpServletResponse
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
                    
    AsyncContext ac = req.startAsync();
    StringBuilder sb = new StringBuilder();
    
    ServletInputStream input = req.getInputStream();
    byte[] b = new byte[1024];
    int len = -1;
    while ((len = input.read(b)) != -1) {
        String data = new String(b, 0, len);
        sb.append(data);
    }

    ServletOutputStream output = res.getOutputStream();
    
    output.println("<html><head><title>Ping Servlet 3.0 Async</title></head>"
            + "<body><hr/><br/><font size=\"+2\" color=\"#000066\">Ping Servlet 3.0 Async</font><br/>"
            + "<font size=\"+1\" color=\"#000066\">Init time : " + initTime
            + "</font><br/><br/><b>Hit Count: " + ++hitCount + "</b><br/>Data Received: "+ sb.toString() + "</body></html>");
    
    ac.complete();
}
 
Example 5
Source File: WebUtils.java    From open-cloud with MIT License 6 votes vote down vote up
/**
 * 复制输入流
 *
 * @param inputStream
 * @return</br>
 */
public static InputStream cloneInputStream(ServletInputStream inputStream) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len;
    try {
        while ((len = inputStream.read(buffer)) > -1) {
            byteArrayOutputStream.write(buffer, 0, len);
        }
        byteArrayOutputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
    InputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    return byteArrayInputStream;
}
 
Example 6
Source File: LoginAuthenticationFilter.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
private String getStringFromStream(HttpServletRequest req) {
    ServletInputStream is;
    try {
        is = req.getInputStream();
        int nRead = 1;
        int nTotalRead = 0;
        byte[] bytes = new byte[10240];
        while (nRead > 0) {
            nRead = is.read(bytes, nTotalRead, bytes.length - nTotalRead);
            if (nRead > 0) {
                nTotalRead = nTotalRead + nRead;
            }
        }
        return new String(bytes, 0, nTotalRead, StandardCharsets.UTF_8);
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example 7
Source File: LoginAuthenticationFilter.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
private String getStringFromStream(HttpServletRequest req) {
    ServletInputStream is;
    try {
        is = req.getInputStream();
        int nRead = 1;
        int nTotalRead = 0;
        byte[] bytes = new byte[10240];
        while (nRead > 0) {
            nRead = is.read(bytes, nTotalRead, bytes.length - nTotalRead);
            if (nRead > 0) {
                nTotalRead = nTotalRead + nRead;
            }
        }
        return new String(bytes, 0, nTotalRead, StandardCharsets.UTF_8);
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example 8
Source File: ServletWebSocketHttpExchange.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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();
    }
}
 
Example 9
Source File: WebUtil.java    From hdw-dubbo with Apache License 2.0 6 votes vote down vote up
/**
 * 复制输入流
 *
 * @param inputStream
 * @return</br>
 */
public static InputStream cloneInputStream(ServletInputStream inputStream) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len;
    try {
        while ((len = inputStream.read(buffer)) > -1) {
            byteArrayOutputStream.write(buffer, 0, len);
        }
        byteArrayOutputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
    InputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    return byteArrayInputStream;
}
 
Example 10
Source File: ServletUtils.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Map<String, String> getRequestParams(HttpServletRequest request) throws IOException {
    ServletInputStream in = request.getInputStream();

            // read spec into a byte array wrapped in a ByteBuffer - can't do it in
            // one read because of a buffer size limit in the InputStream
            byte[] contents = new byte[request.getContentLength()];
            ByteBuffer bytes = ByteBuffer.wrap(contents);
            byte[] buffer = new byte[8192];

            // read chunks from the stream and append them to the ByteBuffer
            int bytesRead;
            while ((bytesRead = in.read(buffer, 0, buffer.length)) > 0) {
                bytes.put(buffer, 0, bytesRead);
            }

            // convert the bytes to a string with the right charset
            String paramStr = new String(contents, "UTF-8");

    // split into params & rebuild map
    Map<String, String> result = new HashMap<String, String>();
    String[] params = paramStr.split("&");
    for (String param : params) {
        String[] parts = param.split("=");
        if (parts.length == 2) {
            result.put(parts[0], parts[1]);
        }
    }
    return result;
}
 
Example 11
Source File: ExampleController.java    From logbook with MIT License 5 votes vote down vote up
@RequestMapping(path = "/read-byte", produces = TEXT_PLAIN_VALUE)
public void readByte(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    final ServletInputStream input = request.getInputStream();
    final ServletOutputStream output = response.getOutputStream();

    while (true) {
        final int read = input.read();
        if (read == -1) {
            break;
        }
        output.write(read);
    }
}
 
Example 12
Source File: cfFormData.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
protected void init( cfSession _session, String enc ) throws UnsupportedEncodingException {
	encoding = enc;

	// --[ if combined, then decode the URI string first of all
	if ( combined ) {
		decodeURIString( _session );
	}

	int contentLength = _session.REQ.getContentLength();
	String contentType = _session.REQ.getContentType();
	if ( contentType == null ) {
		contentType = "";
	}

	isMultipartData = (contentType.indexOf( "multipart/form-data" ) == 0 );
	
	if ( // _session.REQ.getMethod().equals( "POST" ) && // see bug #2696 for why this is commented-out
			( contentLength > 0 ) 
			&& ( !isMultipartData ) ) {
		try {
			int max = contentLength;
			int len = 0;
			incomingRequest = new byte[ contentLength ];
			ServletInputStream is = _session.REQ.getInputStream();
			while ( len < max ) {
				int next = is.read( incomingRequest, len, max - len );
				if (next < 0) {
					break;
				}
				len += next;
			}
			is.close();
		} catch ( IOException ignoreIOexcption ) {}
		
		if ( contentType.indexOf( "application/x-www-form-urlencoded" ) == 0 ) {
			readParams();
		}
	}
}
 
Example 13
Source File: Filter6XmlHttpDecode.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
private static String getRequestBody(ServletInputStream sis) throws IOException, UnsupportedEncodingException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[8 * 1024];
    int bLen = sis.read(buffer);
    while ( bLen > 0 ) {
        baos.write(buffer, 0, bLen);
        bLen = sis.read(buffer);
    }
    return new String(baos.toByteArray(), "UTF-8");
}
 
Example 14
Source File: TestWebApp.java    From spring-boot-starter-netty with GNU General Public License v3.0 5 votes vote down vote up
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String upload(HttpServletRequest request) throws IOException {
    ServletInputStream inputStream = request.getInputStream();
    int total = 0;
    while (true) {
        byte[] bytes = new byte[8192];
        int read = inputStream.read(bytes);
        if (read == -1) {
            break;
        }
        total += read;
    }
    return "Total bytes received: " + total;
}
 
Example 15
Source File: CoreMethodArgumentResolver.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 16
Source File: AccessLogFilter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@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();
    }
  };
}
 
Example 17
Source File: ProxyController.java    From FATE-Serving with Apache License 2.0 5 votes vote down vote up
String binaryReader(HttpServletRequest request) throws IOException {
    int len = request.getContentLength();
    ServletInputStream iii = request.getInputStream();
    byte[] buffer = new byte[len];
    iii.read(buffer, 0, len);
    return new String(buffer);
}
 
Example 18
Source File: BodyReaderHttpServletRequestWrapper.java    From Spirng-Boot-Sign with MIT License 5 votes vote down vote up
/**
 * Description: 复制输入流</br>
 *
 * @param inputStream
 * @return</br>
 */
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 19
Source File: DummyServlet.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	arrived = true;
	ServletInputStream stream = req.getInputStream();
	int c;
	List<Byte> bytes = new ArrayList<Byte>();
	while ((c = stream.read()) != -1) {
		bytes.add((byte) c);
	}
	body = new byte[bytes.size()];
	for (int i = 0; i < body.length; i++) {
		body[i] = bytes.get(i);
	}
}
 
Example 20
Source File: WebDAVLiteServlet.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Handles a PUT request for uploading files.
 *
 * @param request Object representing the HTTP request.
 * @param response Object representing the HTTP response.
 * @throws ServletException If there was a servlet related exception.
 * @throws IOException If there was an IO error while setting the error.
 */
@Override
protected void doPut(HttpServletRequest request,
                     HttpServletResponse response) throws
            ServletException, IOException {
    // Verify authentication
    if (!isAuthenticated(request, response)) return;

    String path = request.getPathInfo();
    Log.debug("WebDAVLiteServlet: PUT with path = "+path);
    if (request.getContentLength() <= 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    if (path == null || !path.startsWith("/rooms/")) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    String[] pathPcs = path.split("/");
    if (pathPcs.length != 5) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    String service = pathPcs[2];
    String room = pathPcs[3];
    String filename = pathPcs[4];

    // Verify authorization
    if (!isAuthorized(request, response, service, room)) return;

    Log.debug("WebDAVListServlet: Service = "+service+", room = "+room+", file = "+filename);
    File file = getFileReference(service, room, filename);
    Boolean overwriteFile = file.exists();
    FileOutputStream fileStream = new FileOutputStream(file, false);
    ServletInputStream inputStream = request.getInputStream();
    byte[] byteArray = new byte[request.getContentLength()];
    int bytesRead = 0;
    while (bytesRead != -1) {
        bytesRead = inputStream.read(byteArray, bytesRead, request.getContentLength());   
    }
    fileStream.write(byteArray);
    fileStream.close();
    inputStream.close();
    if (overwriteFile) {
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        response.setHeader("Location", request.getRequestURI());
    }
    else {
        response.setStatus(HttpServletResponse.SC_CREATED);
        response.setHeader("Location", request.getRequestURI());
    }
}