Search in sources :

Example 91 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 92 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 93 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 94 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 95 with ServletInputStream

use of javax.servlet.ServletInputStream in project OpenRefine by OpenRefine.

the class RefineBrokerTests method call.

private JSONObject call(boolean successful, RefineBroker broker, HttpServletRequest request, HttpServletResponse response, String service, String... params) throws Exception {
    if (params != null) {
        for (int i = 0; i < params.length; ) {
            String name = params[i++];
            String value = params[i++];
            if ("data".equals(name)) {
                final ByteArrayInputStream inputStream = new ByteArrayInputStream(value.getBytes("UTF-8"));
                when(request.getInputStream()).thenReturn(new ServletInputStream() {

                    public int read() throws IOException {
                        return inputStream.read();
                    }
                });
            } else {
                when(request.getParameter(name)).thenReturn(value);
            }
        }
    }
    StringWriter writer = new StringWriter();
    when(response.getWriter()).thenReturn(new PrintWriter(writer));
    broker.process(service, request, response);
    JSONObject result = new JSONObject(writer.toString());
    if (successful) {
        assertJSON(result, "status", "ok");
    } else {
        assertJSON(result, "status", "error");
    }
    logger.info(result.toString());
    return result;
}
Also used : ServletInputStream(javax.servlet.ServletInputStream) StringWriter(java.io.StringWriter) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) IOException(java.io.IOException) PrintWriter(java.io.PrintWriter)

Aggregations

ServletInputStream (javax.servlet.ServletInputStream)148 IOException (java.io.IOException)73 HttpServletRequest (javax.servlet.http.HttpServletRequest)60 Test (org.junit.Test)59 HttpServletResponse (javax.servlet.http.HttpServletResponse)50 ServletException (javax.servlet.ServletException)42 ByteArrayInputStream (java.io.ByteArrayInputStream)32 ReadListener (javax.servlet.ReadListener)28 CountDownLatch (java.util.concurrent.CountDownLatch)26 HttpServlet (javax.servlet.http.HttpServlet)21 DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)20 InterruptedIOException (java.io.InterruptedIOException)18 AsyncContext (javax.servlet.AsyncContext)18 ServletOutputStream (javax.servlet.ServletOutputStream)18 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)18 ByteArrayOutputStream (java.io.ByteArrayOutputStream)17 PrintWriter (java.io.PrintWriter)16 Request (org.eclipse.jetty.server.Request)16 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)15 Test (org.junit.jupiter.api.Test)11