Java Code Examples for org.apache.tomcat.util.buf.ByteChunk#append()

The following examples show how to use org.apache.tomcat.util.buf.ByteChunk#append() . 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: TestCoyoteOutputStream.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testWriteWithByteBuffer() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    Context root = tomcat.addContext("", TEMP_DIR);
    Tomcat.addServlet(root, "testServlet", new TestServlet());
    root.addServletMappingDecoded("/", "testServlet");

    tomcat.start();

    ByteChunk bc = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() + "/", bc, null, null);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    File file = new File("test/org/apache/catalina/connector/test_content.txt");
    try (RandomAccessFile raf = new RandomAccessFile(file, "r");) {
        ByteChunk expected = new ByteChunk();
        expected.append(raf.getChannel().map(MapMode.READ_ONLY, 0, file.length()));
        Assert.assertTrue(expected.equals(bc));
    }
}
 
Example 2
Source File: TestBasicAuthParser.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private void prefix(String method) {
    authHeader = new ByteChunk();
    authHeader.setBytes(HEADER, 0, HEADER.length);
    initialOffset = HEADER.length;

    String methodX = method + " ";
    byte[] methodBytes = methodX.getBytes(StandardCharsets.ISO_8859_1);

    try {
        authHeader.append(methodBytes, 0, methodBytes.length);
    }
    catch (IOException ioe) {
        throw new IllegalStateException("unable to extend ByteChunk:"
                + ioe.getMessage());
    }
}
 
Example 3
Source File: FormAuthenticator.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Save the original request information into our session.
 *
 * @param request The request to be saved
 * @param session The session to contain the saved information
 * @throws IOException if an IO error occurred during the process
 */
protected void saveRequest(Request request, Session session)
    throws IOException {

    // Create and populate a SavedRequest object for this request
    SavedRequest saved = new SavedRequest();
    Cookie cookies[] = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            saved.addCookie(cookies[i]);
        }
    }
    Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        Enumeration<String> values = request.getHeaders(name);
        while (values.hasMoreElements()) {
            String value = values.nextElement();
            saved.addHeader(name, value);
        }
    }
    Enumeration<Locale> locales = request.getLocales();
    while (locales.hasMoreElements()) {
        Locale locale = locales.nextElement();
        saved.addLocale(locale);
    }

    // May need to acknowledge a 100-continue expectation
    request.getResponse().sendAcknowledgement();

    int maxSavePostSize = request.getConnector().getMaxSavePostSize();
    if (maxSavePostSize != 0) {
        ByteChunk body = new ByteChunk();
        body.setLimit(maxSavePostSize);

        byte[] buffer = new byte[4096];
        int bytesRead;
        InputStream is = request.getInputStream();

        while ( (bytesRead = is.read(buffer) ) >= 0) {
            body.append(buffer, 0, bytesRead);
        }

        // Only save the request body if there is something to save
        if (body.getLength() > 0) {
            saved.setContentType(request.getContentType());
            saved.setBody(body);
        }
    }

    saved.setMethod(request.getMethod());
    saved.setQueryString(request.getQueryString());
    saved.setRequestURI(request.getRequestURI());
    saved.setDecodedRequestURI(request.getDecodedRequestURI());

    // Stash the SavedRequest in our session for later use
    session.setNote(Constants.FORM_REQUEST_NOTE, saved);
}
 
Example 4
Source File: TesterAjpNonBlockingClient.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testNonBlockingWrite() throws Exception {

    SocketFactory factory = SocketFactory.getDefault();
    Socket s = factory.createSocket("localhost", 80);

    ByteChunk result = new ByteChunk();
    OutputStream os = s.getOutputStream();
    os.write(("GET /examples/servlets/nonblocking/numberwriter HTTP/1.1\r\n" +
            "Host: localhost\r\n" +
            "Connection: close\r\n" +
            "\r\n").getBytes(StandardCharsets.ISO_8859_1));
    os.flush();

    InputStream is = s.getInputStream();
    byte[] buffer = new byte[8192];

    int read = 0;
    int readSinceLastPause = 0;
    while (read != -1) {
        read = is.read(buffer);
        if (read > 0) {
            result.append(buffer, 0, read);
        }
        readSinceLastPause += read;
        if (readSinceLastPause > 40000) {
            readSinceLastPause = 0;
            Thread.sleep(500);
        }
    }

    os.close();
    is.close();
    s.close();

    // Validate the result
    String resultString = result.toString();
    log.info("Client read " + resultString.length() + " bytes");

    System.out.println(resultString);

    Assert.assertTrue(resultString.contains("00000000000000010000"));
}
 
Example 5
Source File: TomcatBaseTest.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
public static int postUrl(boolean stream, BytesStreamer streamer, String path, ByteChunk out,
            Map<String, List<String>> reqHead,
            Map<String, List<String>> resHead) throws IOException {

    URL url = new URL(path);
    HttpURLConnection connection =
        (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setReadTimeout(1000000);
    if (reqHead != null) {
        for (Map.Entry<String, List<String>> entry : reqHead.entrySet()) {
            StringBuilder valueList = new StringBuilder();
            for (String value : entry.getValue()) {
                if (valueList.length() > 0) {
                    valueList.append(',');
                }
                valueList.append(value);
            }
            connection.setRequestProperty(entry.getKey(),
                    valueList.toString());
        }
    }
    if (streamer != null && stream) {
        if (streamer.getLength()>0) {
            connection.setFixedLengthStreamingMode(streamer.getLength());
        } else {
            connection.setChunkedStreamingMode(1024);
        }
    }

    connection.connect();

    // Write the request body
    try (OutputStream os = connection.getOutputStream()) {
        while (streamer != null && streamer.available() > 0) {
            byte[] next = streamer.next();
            os.write(next);
            os.flush();
        }
    }

    int rc = connection.getResponseCode();
    if (resHead != null) {
        Map<String, List<String>> head = connection.getHeaderFields();
        resHead.putAll(head);
    }
    InputStream is;
    if (rc < 400) {
        is = connection.getInputStream();
    } else {
        is = connection.getErrorStream();
    }

    try (BufferedInputStream bis = new BufferedInputStream(is)) {
        byte[] buf = new byte[2048];
        int rd = 0;
        while((rd = bis.read(buf)) > 0) {
            out.append(buf, 0, rd);
        }
    }
    return rc;
}
 
Example 6
Source File: FormAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Save the original request information into our session.
 *
 * @param request The request to be saved
 * @param session The session to contain the saved information
 * @throws IOException
 */
protected void saveRequest(Request request, Session session)
    throws IOException {

    // Create and populate a SavedRequest object for this request
    SavedRequest saved = new SavedRequest();
    Cookie cookies[] = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            saved.addCookie(cookies[i]);
        }
    }
    Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        Enumeration<String> values = request.getHeaders(name);
        while (values.hasMoreElements()) {
            String value = values.nextElement();
            saved.addHeader(name, value);
        }
    }
    Enumeration<Locale> locales = request.getLocales();
    while (locales.hasMoreElements()) {
        Locale locale = locales.nextElement();
        saved.addLocale(locale);
    }

    // May need to acknowledge a 100-continue expectation
    request.getResponse().sendAcknowledgement();

    ByteChunk body = new ByteChunk();
    body.setLimit(request.getConnector().getMaxSavePostSize());

    byte[] buffer = new byte[4096];
    int bytesRead;
    InputStream is = request.getInputStream();

    while ( (bytesRead = is.read(buffer) ) >= 0) {
        body.append(buffer, 0, bytesRead);
    }

    // Only save the request body if there is something to save
    if (body.getLength() > 0) {
        saved.setContentType(request.getContentType());
        saved.setBody(body);
    }

    saved.setMethod(request.getMethod());
    saved.setQueryString(request.getQueryString());
    saved.setRequestURI(request.getRequestURI());
    saved.setDecodedRequestURI(request.getDecodedRequestURI());

    // Stash the SavedRequest in our session for later use
    session.setNote(Constants.FORM_REQUEST_NOTE, saved);
}
 
Example 7
Source File: TestGzipOutputFilter.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Test the interaction betwen gzip and flushing. The idea is to: 1. create
 * a internal output buffer, response, and attach an active gzipoutputfilter
 * to the output buffer 2. set the output stream of the internal buffer to
 * be a ByteArrayOutputStream so we can inspect the output bytes 3. write a
 * chunk out using the gzipoutputfilter and invoke a flush on the
 * InternalOutputBuffer 4. read from the ByteArrayOutputStream to find out
 * what's being written out (flushed) 5. find out what's expected by wrting
 * to GZIPOutputStream and close it (to force flushing) 6. Compare the size
 * of the two arrays, they should be close (instead of one being much
 * shorter than the other one)
 *
 * @throws Exception
 */
@Test
public void testFlushingWithGzip() throws Exception {
    // set up response, InternalOutputBuffer, and ByteArrayOutputStream
    Response res = new Response();
    InternalOutputBuffer iob = new InternalOutputBuffer(res, 8 * 1024);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    iob.outputStream = bos;
    res.setOutputBuffer(iob);

    // set up GzipOutputFilter to attach to the InternalOutputBuffer
    GzipOutputFilter gf = new GzipOutputFilter();
    iob.addFilter(gf);
    iob.addActiveFilter(gf);

    // write a chunk out
    ByteChunk chunk = new ByteChunk(1024);
    byte[] d = "Hello there tomcat developers, there is a bug in JDK".getBytes();
    chunk.append(d, 0, d.length);
    iob.doWrite(chunk, res);

    // flush the InternalOutputBuffer
    iob.flush();

    // read from the ByteArrayOutputStream to find out what's being written
    // out (flushed)
    byte[] dataFound = bos.toByteArray();

    // find out what's expected by wrting to GZIPOutputStream and close it
    // (to force flushing)
    ByteArrayOutputStream gbos = new ByteArrayOutputStream(1024);
    GZIPOutputStream gos = new GZIPOutputStream(gbos);
    gos.write(d);
    gos.close();

    // read the expected data
    byte[] dataExpected = gbos.toByteArray();

    // most of the data should have been flushed out
    assertTrue(dataFound.length >= (dataExpected.length - 20));
}
 
Example 8
Source File: FormAuthenticator.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Save the original request information into our session.
 *
 * @param request The request to be saved
 * @param session The session to contain the saved information
 * @throws IOException
 */
protected void saveRequest(Request request, Session session)
    throws IOException {

    // Create and populate a SavedRequest object for this request
    SavedRequest saved = new SavedRequest();
    Cookie cookies[] = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            saved.addCookie(cookies[i]);
        }
    }
    Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        Enumeration<String> values = request.getHeaders(name);
        while (values.hasMoreElements()) {
            String value = values.nextElement();
            saved.addHeader(name, value);
        }
    }
    Enumeration<Locale> locales = request.getLocales();
    while (locales.hasMoreElements()) {
        Locale locale = locales.nextElement();
        saved.addLocale(locale);
    }

    // May need to acknowledge a 100-continue expectation
    request.getResponse().sendAcknowledgement();

    ByteChunk body = new ByteChunk();
    body.setLimit(request.getConnector().getMaxSavePostSize());

    byte[] buffer = new byte[4096];
    int bytesRead;
    InputStream is = request.getInputStream();

    while ( (bytesRead = is.read(buffer) ) >= 0) {
        body.append(buffer, 0, bytesRead);
    }

    // Only save the request body if there is something to save
    if (body.getLength() > 0) {
        saved.setContentType(request.getContentType());
        saved.setBody(body);
    }

    saved.setMethod(request.getMethod());
    saved.setQueryString(request.getQueryString());
    saved.setRequestURI(request.getRequestURI());
    saved.setDecodedRequestURI(request.getDecodedRequestURI());

    // Stash the SavedRequest in our session for later use
    session.setNote(Constants.FORM_REQUEST_NOTE, saved);
}
 
Example 9
Source File: TestGzipOutputFilter.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Test the interaction betwen gzip and flushing. The idea is to: 1. create
 * a internal output buffer, response, and attach an active gzipoutputfilter
 * to the output buffer 2. set the output stream of the internal buffer to
 * be a ByteArrayOutputStream so we can inspect the output bytes 3. write a
 * chunk out using the gzipoutputfilter and invoke a flush on the
 * InternalOutputBuffer 4. read from the ByteArrayOutputStream to find out
 * what's being written out (flushed) 5. find out what's expected by wrting
 * to GZIPOutputStream and close it (to force flushing) 6. Compare the size
 * of the two arrays, they should be close (instead of one being much
 * shorter than the other one)
 *
 * @throws Exception
 */
@Test
public void testFlushingWithGzip() throws Exception {
    // set up response, InternalOutputBuffer, and ByteArrayOutputStream
    Response res = new Response();
    InternalOutputBuffer iob = new InternalOutputBuffer(res, 8 * 1024);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    iob.outputStream = bos;
    res.setOutputBuffer(iob);

    // set up GzipOutputFilter to attach to the InternalOutputBuffer
    GzipOutputFilter gf = new GzipOutputFilter();
    iob.addFilter(gf);
    iob.addActiveFilter(gf);

    // write a chunk out
    ByteChunk chunk = new ByteChunk(1024);
    byte[] d = "Hello there tomcat developers, there is a bug in JDK".getBytes();
    chunk.append(d, 0, d.length);
    iob.doWrite(chunk, res);

    // flush the InternalOutputBuffer
    iob.flush();

    // read from the ByteArrayOutputStream to find out what's being written
    // out (flushed)
    byte[] dataFound = bos.toByteArray();

    // find out what's expected by wrting to GZIPOutputStream and close it
    // (to force flushing)
    ByteArrayOutputStream gbos = new ByteArrayOutputStream(1024);
    GZIPOutputStream gos = new GZIPOutputStream(gbos);
    gos.write(d);
    gos.close();

    // read the expected data
    byte[] dataExpected = gbos.toByteArray();

    // most of the data should have been flushed out
    assertTrue(dataFound.length >= (dataExpected.length - 20));
}
 
Example 10
Source File: LoginToContinueMechanism.java    From tomee with Apache License 2.0 4 votes vote down vote up
static void saveRequest(final HttpServletRequest request) throws IOException {
    SavedRequest saved = new SavedRequest();
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            saved.addCookie(cookies[i]);
        }
    }
    Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        Enumeration<String> values = request.getHeaders(name);
        while (values.hasMoreElements()) {
            String value = values.nextElement();
            saved.addHeader(name, value);
        }
    }
    Enumeration<Locale> locales = request.getLocales();
    while (locales.hasMoreElements()) {
        Locale locale = locales.nextElement();
        saved.addLocale(locale);
    }

    int maxSavePostSize = MAX_SAVE_POST_SIZE;
    if (maxSavePostSize != 0) {
        ByteChunk body = new ByteChunk();
        body.setLimit(maxSavePostSize);

        byte[] buffer = new byte[4096];
        int bytesRead;
        InputStream is = request.getInputStream();

        while ( (bytesRead = is.read(buffer) ) >= 0) {
            body.append(buffer, 0, bytesRead);
        }

        // Only save the request body if there is something to save
        if (body.getLength() > 0) {
            saved.setContentType(request.getContentType());
            saved.setBody(body);
        }
    }

    saved.setMethod(request.getMethod());
    saved.setQueryString(request.getQueryString());
    saved.setRequestURI(request.getRequestURI());
    saved.setRequestURL(request.getRequestURL().toString());

    // Stash the SavedRequest in our session for later use
    request.getSession().setAttribute(ORIGINAL_REQUEST, saved);
}