Search in sources :

Example 56 with Request

use of org.eclipse.jetty.client.api.Request in project jetty.project by eclipse.

the class IdleSessionTest method testSessionIdle.

/**
     * @throws Exception
     */
@Test
public void testSessionIdle() throws Exception {
    String contextPath = "";
    String servletMapping = "/server";
    int inactivePeriod = 20;
    int scavengePeriod = 3;
    int evictionSec = 5;
    DefaultSessionCacheFactory cacheFactory = new DefaultSessionCacheFactory();
    cacheFactory.setEvictionPolicy(evictionSec);
    SessionDataStoreFactory storeFactory = new TestSessionDataStoreFactory();
    _server1 = new TestServer(0, inactivePeriod, scavengePeriod, cacheFactory, storeFactory);
    ServletHolder holder = new ServletHolder(_servlet);
    ServletContextHandler contextHandler = _server1.addContext(contextPath);
    contextHandler.addServlet(holder, servletMapping);
    _server1.start();
    int port1 = _server1.getPort();
    try (StacklessLogging stackless = new StacklessLogging(Log.getLogger("org.eclipse.jetty.server.session"))) {
        HttpClient client = new HttpClient();
        client.start();
        String url = "http://localhost:" + port1 + contextPath + servletMapping;
        //make a request to set up a session on the server
        ContentResponse response = client.GET(url + "?action=init");
        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
        String sessionCookie = response.getHeaders().get("Set-Cookie");
        assertTrue(sessionCookie != null);
        // Mangle the cookie, replacing Path with $Path, etc.
        sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
        //and wait until the session should be idled out
        pause(evictionSec * 3);
        //check that the session has been idled
        String id = TestServer.extractSessionId(sessionCookie);
        assertFalse(contextHandler.getSessionHandler().getSessionCache().contains(id));
        assertTrue(contextHandler.getSessionHandler().getSessionCache().getSessionDataStore().exists(id));
        //make another request to de-idle the session
        Request request = client.newRequest(url + "?action=test");
        request.getHeaders().add("Cookie", sessionCookie);
        ContentResponse response2 = request.send();
        assertEquals(HttpServletResponse.SC_OK, response2.getStatus());
        //check session de-idled
        assertTrue(contextHandler.getSessionHandler().getSessionCache().contains(id));
        //wait again for the session to be idled
        pause(evictionSec * 3);
        //check that it is
        assertFalse(contextHandler.getSessionHandler().getSessionCache().contains(id));
        assertTrue(contextHandler.getSessionHandler().getSessionCache().getSessionDataStore().exists(id));
        //While idle, take some action to ensure that a deidle won't work, like
        //deleting the sessions in the store
        ((TestSessionDataStore) contextHandler.getSessionHandler().getSessionCache().getSessionDataStore())._map.clear();
        //make a request
        request = client.newRequest(url + "?action=testfail");
        request.getHeaders().add("Cookie", sessionCookie);
        response2 = request.send();
        assertEquals(HttpServletResponse.SC_OK, response2.getStatus());
        //Test trying to de-idle an expired session (ie before the scavenger can get to it)
        //make a request to set up a session on the server
        response = client.GET(url + "?action=init");
        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
        sessionCookie = response.getHeaders().get("Set-Cookie");
        assertTrue(sessionCookie != null);
        // Mangle the cookie, replacing Path with $Path, etc.
        sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
        id = TestServer.extractSessionId(sessionCookie);
        //and wait until the session should be idled out
        pause(evictionSec * 3);
        //stop the scavenger
        if (_server1.getHouseKeeper() != null)
            _server1.getHouseKeeper().stop();
        //check that the session is idle
        assertFalse(contextHandler.getSessionHandler().getSessionCache().contains(id));
        assertTrue(contextHandler.getSessionHandler().getSessionCache().getSessionDataStore().exists(id));
        //wait until the session should be expired
        pause(inactivePeriod + (3 * scavengePeriod));
        //make another request to de-idle the session
        request = client.newRequest(url + "?action=testfail");
        request.getHeaders().add("Cookie", sessionCookie);
        response2 = request.send();
        assertEquals(HttpServletResponse.SC_OK, response2.getStatus());
        assertFalse(contextHandler.getSessionHandler().getSessionCache().contains(id));
        assertFalse(contextHandler.getSessionHandler().getSessionCache().getSessionDataStore().exists(id));
    } finally {
        _server1.stop();
    }
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) HttpClient(org.eclipse.jetty.client.HttpClient) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Test(org.junit.Test)

Example 57 with Request

use of org.eclipse.jetty.client.api.Request in project jetty.project by eclipse.

the class JdbcLoginServiceTest method testHead.

//Head requests to jetty-client are not working: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=394552
@Ignore
public void testHead() throws Exception {
    try {
        startClient();
        Request request = _client.newRequest(_baseUri.resolve("input.txt"));
        request.method(HttpMethod.HEAD);
        ContentResponse response = request.send();
        int responseStatus = response.getStatus();
        assertEquals(HttpStatus.OK_200, responseStatus);
    } finally {
        stopClient();
    }
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Request(org.eclipse.jetty.client.api.Request) Ignore(org.junit.Ignore)

Example 58 with Request

use of org.eclipse.jetty.client.api.Request in project druid by druid-io.

the class KerberosJettyHttpClientProvider method get.

@Override
public HttpClient get() {
    final HttpClient httpClient = delegateProvider.get();
    httpClient.getAuthenticationStore().addAuthentication(new Authentication() {

        @Override
        public boolean matches(String type, URI uri, String realm) {
            return true;
        }

        @Override
        public Result authenticate(final Request request, ContentResponse response, Authentication.HeaderInfo headerInfo, Attributes context) {
            return new Result() {

                @Override
                public URI getURI() {
                    return request.getURI();
                }

                @Override
                public void apply(Request request) {
                    try {
                        // No need to set cookies as they are handled by Jetty Http Client itself.
                        URI uri = request.getURI();
                        if (DruidKerberosUtil.needToSendCredentials(httpClient.getCookieStore(), uri)) {
                            log.debug("No Auth Cookie found for URI[%s]. Existing Cookies[%s] Authenticating... ", uri, httpClient.getCookieStore().getCookies());
                            final String host = request.getHost();
                            DruidKerberosUtil.authenticateIfRequired(config);
                            UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
                            String challenge = currentUser.doAs(new PrivilegedExceptionAction<String>() {

                                @Override
                                public String run() throws Exception {
                                    return DruidKerberosUtil.kerberosChallenge(host);
                                }
                            });
                            request.getHeaders().add(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challenge);
                        } else {
                            log.debug("Found Auth Cookie found for URI[%s].", uri);
                        }
                    } catch (Throwable e) {
                        Throwables.propagate(e);
                    }
                }
            };
        }
    });
    return httpClient;
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Request(org.eclipse.jetty.client.api.Request) Attributes(org.eclipse.jetty.util.Attributes) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) URI(java.net.URI) Authentication(org.eclipse.jetty.client.api.Authentication) HttpClient(org.eclipse.jetty.client.HttpClient) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation)

Example 59 with Request

use of org.eclipse.jetty.client.api.Request in project jetty.project by eclipse.

the class HttpClientTest method test_QueuedRequest_IsSent_WhenPreviousRequestSucceeded.

@Test
public void test_QueuedRequest_IsSent_WhenPreviousRequestSucceeded() throws Exception {
    start(new EmptyServerHandler());
    client.setMaxConnectionsPerDestination(1);
    final CountDownLatch latch = new CountDownLatch(1);
    final CountDownLatch successLatch = new CountDownLatch(2);
    client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).onRequestBegin(request -> {
        try {
            latch.await();
        } catch (InterruptedException x) {
            x.printStackTrace();
        }
    }).send(new Response.Listener.Adapter() {

        @Override
        public void onSuccess(Response response) {
            Assert.assertEquals(200, response.getStatus());
            successLatch.countDown();
        }
    });
    client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).onRequestQueued(request -> latch.countDown()).send(new Response.Listener.Adapter() {

        @Override
        public void onSuccess(Response response) {
            Assert.assertEquals(200, response.getStatus());
            successLatch.countDown();
        }
    });
    Assert.assertTrue(successLatch.await(5, TimeUnit.SECONDS));
}
Also used : Arrays(java.util.Arrays) EndPoint(org.eclipse.jetty.io.EndPoint) TestingDir(org.eclipse.jetty.toolchain.test.TestingDir) ServletException(javax.servlet.ServletException) TimeoutException(java.util.concurrent.TimeoutException) Random(java.util.Random) Request(org.eclipse.jetty.client.api.Request) ByteBuffer(java.nio.ByteBuffer) Assert.assertThat(org.junit.Assert.assertThat) ServerSocket(java.net.ServerSocket) HttpCookie(java.net.HttpCookie) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FutureResponseListener(org.eclipse.jetty.client.util.FutureResponseListener) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) URI(java.net.URI) Path(java.nio.file.Path) Response(org.eclipse.jetty.client.api.Response) Callback(org.eclipse.jetty.util.Callback) SocketAddressResolver(org.eclipse.jetty.util.SocketAddressResolver) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) Slow(org.eclipse.jetty.toolchain.test.annotation.Slow) StandardOpenOption(java.nio.file.StandardOpenOption) IO(org.eclipse.jetty.util.IO) AbstractConnection(org.eclipse.jetty.io.AbstractConnection) InetSocketAddress(java.net.InetSocketAddress) StandardCharsets(java.nio.charset.StandardCharsets) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) FuturePromise(org.eclipse.jetty.util.FuturePromise) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) HttpConnectionOverHTTP(org.eclipse.jetty.client.http.HttpConnectionOverHTTP) BadMessageException(org.eclipse.jetty.http.BadMessageException) Connection(org.eclipse.jetty.client.api.Connection) Result(org.eclipse.jetty.client.api.Result) Socket(java.net.Socket) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) HttpVersion(org.eclipse.jetty.http.HttpVersion) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) AtomicReference(java.util.concurrent.atomic.AtomicReference) BytesContentProvider(org.eclipse.jetty.client.util.BytesContentProvider) ArrayList(java.util.ArrayList) HttpClientTransportOverHTTP(org.eclipse.jetty.client.http.HttpClientTransportOverHTTP) HttpHeader(org.eclipse.jetty.http.HttpHeader) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletOutputStream(javax.servlet.ServletOutputStream) Assume(org.junit.Assume) NoSuchElementException(java.util.NoSuchElementException) OutputStream(java.io.OutputStream) HttpHeaderValue(org.eclipse.jetty.http.HttpHeaderValue) Iterator(java.util.Iterator) Files(java.nio.file.Files) HttpServletResponse(javax.servlet.http.HttpServletResponse) Promise(org.eclipse.jetty.util.Promise) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) Test(org.junit.Test) UnknownHostException(java.net.UnknownHostException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) HttpDestinationOverHTTP(org.eclipse.jetty.client.http.HttpDestinationOverHTTP) AtomicLong(java.util.concurrent.atomic.AtomicLong) URLEncoder(java.net.URLEncoder) HttpMethod(org.eclipse.jetty.http.HttpMethod) Rule(org.junit.Rule) Paths(java.nio.file.Paths) HttpField(org.eclipse.jetty.http.HttpField) ContentProvider(org.eclipse.jetty.client.api.ContentProvider) Destination(org.eclipse.jetty.client.api.Destination) Assert(org.junit.Assert) Collections(java.util.Collections) InputStream(java.io.InputStream) Exchanger(java.util.concurrent.Exchanger) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) FutureResponseListener(org.eclipse.jetty.client.util.FutureResponseListener) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 60 with Request

use of org.eclipse.jetty.client.api.Request in project jetty.project by eclipse.

the class HttpClientTest method test_POST_WithContent_NotifiesRequestContentListener.

@Test
public void test_POST_WithContent_NotifiesRequestContentListener() throws Exception {
    start(new AbstractHandler() {

        @Override
        public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            consume(request.getInputStream(), true);
        }
    });
    final byte[] content = { 0, 1, 2, 3 };
    ContentResponse response = client.POST(scheme + "://localhost:" + connector.getLocalPort()).onRequestContent((request, buffer) -> {
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        if (!Arrays.equals(content, bytes))
            request.abort(new Exception());
    }).content(new BytesContentProvider(content)).timeout(5, TimeUnit.SECONDS).send();
    Assert.assertNotNull(response);
    Assert.assertEquals(200, response.getStatus());
}
Also used : Arrays(java.util.Arrays) EndPoint(org.eclipse.jetty.io.EndPoint) TestingDir(org.eclipse.jetty.toolchain.test.TestingDir) ServletException(javax.servlet.ServletException) TimeoutException(java.util.concurrent.TimeoutException) Random(java.util.Random) Request(org.eclipse.jetty.client.api.Request) ByteBuffer(java.nio.ByteBuffer) Assert.assertThat(org.junit.Assert.assertThat) ServerSocket(java.net.ServerSocket) HttpCookie(java.net.HttpCookie) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FutureResponseListener(org.eclipse.jetty.client.util.FutureResponseListener) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) URI(java.net.URI) Path(java.nio.file.Path) Response(org.eclipse.jetty.client.api.Response) Callback(org.eclipse.jetty.util.Callback) SocketAddressResolver(org.eclipse.jetty.util.SocketAddressResolver) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) Slow(org.eclipse.jetty.toolchain.test.annotation.Slow) StandardOpenOption(java.nio.file.StandardOpenOption) IO(org.eclipse.jetty.util.IO) AbstractConnection(org.eclipse.jetty.io.AbstractConnection) InetSocketAddress(java.net.InetSocketAddress) StandardCharsets(java.nio.charset.StandardCharsets) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) FuturePromise(org.eclipse.jetty.util.FuturePromise) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) HttpConnectionOverHTTP(org.eclipse.jetty.client.http.HttpConnectionOverHTTP) BadMessageException(org.eclipse.jetty.http.BadMessageException) Connection(org.eclipse.jetty.client.api.Connection) Result(org.eclipse.jetty.client.api.Result) Socket(java.net.Socket) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) HttpVersion(org.eclipse.jetty.http.HttpVersion) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) AtomicReference(java.util.concurrent.atomic.AtomicReference) BytesContentProvider(org.eclipse.jetty.client.util.BytesContentProvider) ArrayList(java.util.ArrayList) HttpClientTransportOverHTTP(org.eclipse.jetty.client.http.HttpClientTransportOverHTTP) HttpHeader(org.eclipse.jetty.http.HttpHeader) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletOutputStream(javax.servlet.ServletOutputStream) Assume(org.junit.Assume) NoSuchElementException(java.util.NoSuchElementException) OutputStream(java.io.OutputStream) HttpHeaderValue(org.eclipse.jetty.http.HttpHeaderValue) Iterator(java.util.Iterator) Files(java.nio.file.Files) HttpServletResponse(javax.servlet.http.HttpServletResponse) Promise(org.eclipse.jetty.util.Promise) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) Test(org.junit.Test) UnknownHostException(java.net.UnknownHostException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) HttpDestinationOverHTTP(org.eclipse.jetty.client.http.HttpDestinationOverHTTP) AtomicLong(java.util.concurrent.atomic.AtomicLong) URLEncoder(java.net.URLEncoder) HttpMethod(org.eclipse.jetty.http.HttpMethod) Rule(org.junit.Rule) Paths(java.nio.file.Paths) HttpField(org.eclipse.jetty.http.HttpField) ContentProvider(org.eclipse.jetty.client.api.ContentProvider) Destination(org.eclipse.jetty.client.api.Destination) Assert(org.junit.Assert) Collections(java.util.Collections) InputStream(java.io.InputStream) Exchanger(java.util.concurrent.Exchanger) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) BytesContentProvider(org.eclipse.jetty.client.util.BytesContentProvider) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) ServletException(javax.servlet.ServletException) TimeoutException(java.util.concurrent.TimeoutException) BadMessageException(org.eclipse.jetty.http.BadMessageException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) ExecutionException(java.util.concurrent.ExecutionException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Test(org.junit.Test)

Aggregations

Request (org.eclipse.jetty.client.api.Request)223 Test (org.junit.Test)137 HttpServletRequest (javax.servlet.http.HttpServletRequest)121 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)118 HttpServletResponse (javax.servlet.http.HttpServletResponse)63 IOException (java.io.IOException)62 CountDownLatch (java.util.concurrent.CountDownLatch)58 ServletException (javax.servlet.ServletException)53 HttpClient (org.eclipse.jetty.client.HttpClient)48 Response (org.eclipse.jetty.client.api.Response)37 Result (org.eclipse.jetty.client.api.Result)37 InputStream (java.io.InputStream)36 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)35 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)30 FutureResponseListener (org.eclipse.jetty.client.util.FutureResponseListener)28 ByteBuffer (java.nio.ByteBuffer)27 SalesforceException (org.apache.camel.component.salesforce.api.SalesforceException)26 Connection (org.eclipse.jetty.client.api.Connection)26 BytesContentProvider (org.eclipse.jetty.client.util.BytesContentProvider)25 URI (java.net.URI)24