Search in sources :

Example 61 with ServletInputStream

use of javax.servlet.ServletInputStream in project jetty.project by eclipse.

the class ProxyServletTest method testExpect100ContinueRespond100Continue.

@Test
public void testExpect100ContinueRespond100Continue() throws Exception {
    CountDownLatch serverLatch1 = new CountDownLatch(1);
    CountDownLatch serverLatch2 = new CountDownLatch(1);
    startServer(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            serverLatch1.countDown();
            try {
                serverLatch2.await(5, TimeUnit.SECONDS);
            } catch (Throwable x) {
                throw new InterruptedIOException();
            }
            // Send the 100 Continue.
            ServletInputStream input = request.getInputStream();
            // Echo the content.
            IO.copy(input, response.getOutputStream());
        }
    });
    startProxy();
    startClient();
    byte[] content = new byte[1024];
    CountDownLatch contentLatch = new CountDownLatch(1);
    CountDownLatch clientLatch = new CountDownLatch(1);
    client.newRequest("localhost", serverConnector.getLocalPort()).header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()).content(new BytesContentProvider(content)).onRequestContent((request, buffer) -> contentLatch.countDown()).send(new BufferingResponseListener() {

        @Override
        public void onComplete(Result result) {
            if (result.isSucceeded()) {
                if (result.getResponse().getStatus() == HttpStatus.OK_200) {
                    if (Arrays.equals(content, getContent()))
                        clientLatch.countDown();
                }
            }
        }
    });
    // Wait until we arrive on the server.
    Assert.assertTrue(serverLatch1.await(5, TimeUnit.SECONDS));
    // The client should not send the content yet.
    Assert.assertFalse(contentLatch.await(1, TimeUnit.SECONDS));
    // Make the server send the 100 Continue.
    serverLatch2.countDown();
    // The client has sent the content.
    Assert.assertTrue(contentLatch.await(5, TimeUnit.SECONDS));
    Assert.assertTrue(clientLatch.await(5, TimeUnit.SECONDS));
}
Also used : ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Arrays(java.util.Arrays) FilterChain(javax.servlet.FilterChain) ServletException(javax.servlet.ServletException) TimeoutException(java.util.concurrent.TimeoutException) Random(java.util.Random) AsyncEvent(javax.servlet.AsyncEvent) Request(org.eclipse.jetty.client.api.Request) ByteBuffer(java.nio.ByteBuffer) HttpClient(org.eclipse.jetty.client.HttpClient) HttpCookie(java.net.HttpCookie) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) AsyncListener(javax.servlet.AsyncListener) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) Map(java.util.Map) HttpProxy(org.eclipse.jetty.client.HttpProxy) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) After(org.junit.After) Filter(javax.servlet.Filter) HttpStatus(org.eclipse.jetty.http.HttpStatus) Path(java.nio.file.Path) Response(org.eclipse.jetty.client.api.Response) Server(org.eclipse.jetty.server.Server) Callback(org.eclipse.jetty.util.Callback) EnumSet(java.util.EnumSet) Parameterized(org.junit.runners.Parameterized) PrintWriter(java.io.PrintWriter) HttpServlet(javax.servlet.http.HttpServlet) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) StandardOpenOption(java.nio.file.StandardOpenOption) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) TestTracker(org.eclipse.jetty.toolchain.test.TestTracker) IO(org.eclipse.jetty.util.IO) EOFException(java.io.EOFException) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) ServletResponse(javax.servlet.ServletResponse) GZIPOutputStream(java.util.zip.GZIPOutputStream) Result(org.eclipse.jetty.client.api.Result) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MavenTestingUtils(org.eclipse.jetty.toolchain.test.MavenTestingUtils) ServletInputStream(javax.servlet.ServletInputStream) DuplexConnectionPool(org.eclipse.jetty.client.DuplexConnectionPool) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) InterruptedIOException(java.io.InterruptedIOException) BytesContentProvider(org.eclipse.jetty.client.util.BytesContentProvider) LinkedHashMap(java.util.LinkedHashMap) AsyncContext(javax.servlet.AsyncContext) HttpHeader(org.eclipse.jetty.http.HttpHeader) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) ServletOutputStream(javax.servlet.ServletOutputStream) ConnectException(java.net.ConnectException) Cookie(javax.servlet.http.Cookie) OutputStream(java.io.OutputStream) ServletRequest(javax.servlet.ServletRequest) HttpHeaderValue(org.eclipse.jetty.http.HttpHeaderValue) Files(java.nio.file.Files) HttpServletResponse(javax.servlet.http.HttpServletResponse) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) Test(org.junit.Test) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) HttpDestinationOverHTTP(org.eclipse.jetty.client.http.HttpDestinationOverHTTP) HttpMethod(org.eclipse.jetty.http.HttpMethod) ServerConnector(org.eclipse.jetty.server.ServerConnector) Rule(org.junit.Rule) FilterConfig(javax.servlet.FilterConfig) DispatcherType(javax.servlet.DispatcherType) InputStreamResponseListener(org.eclipse.jetty.client.util.InputStreamResponseListener) Assert(org.junit.Assert) Collections(java.util.Collections) InputStream(java.io.InputStream) InterruptedIOException(java.io.InterruptedIOException) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) BytesContentProvider(org.eclipse.jetty.client.util.BytesContentProvider) Result(org.eclipse.jetty.client.api.Result) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) Test(org.junit.Test)

Example 62 with ServletInputStream

use of javax.servlet.ServletInputStream in project jetty.project by eclipse.

the class ProxyServletTest method testExpect100ContinueRespond100ContinueSomeRequestContentThenFailure.

@Test
public void testExpect100ContinueRespond100ContinueSomeRequestContentThenFailure() throws Exception {
    CountDownLatch serverLatch = new CountDownLatch(1);
    startServer(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // Send the 100 Continue.
            ServletInputStream input = request.getInputStream();
            try {
                // Echo the content.
                IO.copy(input, response.getOutputStream());
            } catch (IOException x) {
                serverLatch.countDown();
            }
        }
    });
    startProxy();
    startClient();
    long idleTimeout = 1000;
    client.setIdleTimeout(idleTimeout);
    byte[] content = new byte[1024];
    new Random().nextBytes(content);
    int chunk1 = content.length / 2;
    DeferredContentProvider contentProvider = new DeferredContentProvider();
    contentProvider.offer(ByteBuffer.wrap(content, 0, chunk1));
    CountDownLatch clientLatch = new CountDownLatch(1);
    client.newRequest("localhost", serverConnector.getLocalPort()).header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()).content(contentProvider).send(result -> {
        if (result.isFailed())
            clientLatch.countDown();
    });
    // Wait more than the idle timeout to break the connection.
    Thread.sleep(2 * idleTimeout);
    Assert.assertTrue(serverLatch.await(555, TimeUnit.SECONDS));
    Assert.assertTrue(clientLatch.await(555, TimeUnit.SECONDS));
}
Also used : HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) Random(java.util.Random) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) Test(org.junit.Test)

Example 63 with ServletInputStream

use of javax.servlet.ServletInputStream in project Openfire by igniterealtime.

the class WebDAVLiteServlet method doPut.

/**
     * 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());
    }
}
Also used : ServletInputStream(javax.servlet.ServletInputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 64 with ServletInputStream

use of javax.servlet.ServletInputStream in project iosched by google.

the class SendMessageServlet method readBody.

private String readBody(HttpServletRequest req) throws IOException {
    ServletInputStream inputStream = req.getInputStream();
    java.util.Scanner s = new java.util.Scanner(inputStream).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}
Also used : ServletInputStream(javax.servlet.ServletInputStream)

Example 65 with ServletInputStream

use of javax.servlet.ServletInputStream in project appengine-angular-guestbook-java by googlearchive.

the class TestUtil method getMockedJsonRequest.

public static HttpServletRequest getMockedJsonRequest(final String requestBody) throws IOException {
    // Since jersey looks up the HTTP method and headers from the request, we mock those 2 calls
    // and the ServletInputStream.
    HttpServletRequest mockedJsonRequest = mock(HttpServletRequest.class);
    when(mockedJsonRequest.getMethod()).thenReturn("POST");
    Vector<String> headers = new Vector<String>();
    headers.add("Content-Type");
    when(mockedJsonRequest.getHeaderNames()).thenReturn(headers.elements());
    Vector<String> contentTypes = new Vector<String>();
    contentTypes.add("application/json; charset=UTF-8");
    when(mockedJsonRequest.getHeaders("Content-Type")).thenReturn(contentTypes.elements());
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    outputStream.write(requestBody.getBytes());
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    when(mockedJsonRequest.getInputStream()).thenReturn(new ServletInputStream() {

        @Override
        public int read() throws IOException {
            return inputStream.read();
        }
    });
    return mockedJsonRequest;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletInputStream(javax.servlet.ServletInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Vector(java.util.Vector)

Aggregations

ServletInputStream (javax.servlet.ServletInputStream)79 IOException (java.io.IOException)51 HttpServletRequest (javax.servlet.http.HttpServletRequest)43 Test (org.junit.Test)43 ServletException (javax.servlet.ServletException)41 HttpServletResponse (javax.servlet.http.HttpServletResponse)40 CountDownLatch (java.util.concurrent.CountDownLatch)26 HttpServlet (javax.servlet.http.HttpServlet)20 DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)20 InterruptedIOException (java.io.InterruptedIOException)18 AsyncContext (javax.servlet.AsyncContext)17 ReadListener (javax.servlet.ReadListener)17 ServletOutputStream (javax.servlet.ServletOutputStream)16 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)16 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)15 Request (org.eclipse.jetty.server.Request)14 Response (org.eclipse.jetty.client.api.Response)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 PrintWriter (java.io.PrintWriter)8 Matchers.containsString (org.hamcrest.Matchers.containsString)8