Search in sources :

Example 71 with AtomicReference

use of java.util.concurrent.atomic.AtomicReference in project vert.x by eclipse.

the class BareCommand method startVertx.

/**
   * Starts the vert.x instance.
   *
   * @return the created instance of vert.x
   */
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
protected Vertx startVertx() {
    MetricsOptions metricsOptions = getMetricsOptions();
    options = new VertxOptions().setMetricsOptions(metricsOptions);
    configureFromSystemProperties(options, VERTX_OPTIONS_PROP_PREFIX);
    beforeStartingVertx(options);
    Vertx instance;
    if (isClustered()) {
        log.info("Starting clustering...");
        if (clusterHost == null) {
            clusterHost = getDefaultAddress();
            if (clusterHost == null) {
                log.error("Unable to find a default network interface for clustering. Please specify one using -cluster-host");
                return null;
            } else {
                log.info("No cluster-host specified so using address " + clusterHost);
            }
        }
        CountDownLatch latch = new CountDownLatch(1);
        AtomicReference<AsyncResult<Vertx>> result = new AtomicReference<>();
        options.setClusterHost(clusterHost).setClusterPort(clusterPort).setClustered(true);
        if (getHA()) {
            options.setHAEnabled(true);
            if (haGroup != null) {
                options.setHAGroup(haGroup);
            }
            if (quorum != -1) {
                options.setQuorumSize(quorum);
            }
        }
        create(options, ar -> {
            result.set(ar);
            latch.countDown();
        });
        try {
            if (!latch.await(2, TimeUnit.MINUTES)) {
                log.error("Timed out in starting clustered Vert.x");
                return null;
            }
        } catch (InterruptedException e) {
            log.error("Thread interrupted in startup");
            Thread.currentThread().interrupt();
            return null;
        }
        if (result.get().failed()) {
            log.error("Failed to form cluster");
            result.get().cause().printStackTrace();
            return null;
        }
        instance = result.get().result();
    } else {
        instance = create(options);
    }
    addShutdownHook();
    afterStartingVertx(instance);
    return instance;
}
Also used : MetricsOptions(io.vertx.core.metrics.MetricsOptions) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 72 with AtomicReference

use of java.util.concurrent.atomic.AtomicReference in project jetty.project by eclipse.

the class HttpClientTLSTest method testHandshakeSucceededWithSessionResumption.

@Test
public void testHandshakeSucceededWithSessionResumption() throws Exception {
    SslContextFactory serverTLSFactory = createSslContextFactory();
    startServer(serverTLSFactory, new EmptyServerHandler());
    AtomicReference<byte[]> serverSession = new AtomicReference<>();
    connector.addBean(new SslHandshakeListener() {

        @Override
        public void handshakeSucceeded(Event event) {
            serverSession.set(event.getSSLEngine().getSession().getId());
        }
    });
    SslContextFactory clientTLSFactory = createSslContextFactory();
    startClient(clientTLSFactory);
    AtomicReference<byte[]> clientSession = new AtomicReference<>();
    client.addBean(new SslHandshakeListener() {

        @Override
        public void handshakeSucceeded(Event event) {
            clientSession.set(event.getSSLEngine().getSession().getId());
        }
    });
    // First request primes the TLS session.
    ContentResponse response = client.newRequest("localhost", connector.getLocalPort()).scheme(HttpScheme.HTTPS.asString()).header(HttpHeader.CONNECTION, "close").timeout(5, TimeUnit.SECONDS).send();
    Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    Assert.assertNotNull(serverSession.get());
    Assert.assertNotNull(clientSession.get());
    connector.removeBean(connector.getBean(SslHandshakeListener.class));
    client.removeBean(client.getBean(SslHandshakeListener.class));
    CountDownLatch serverLatch = new CountDownLatch(1);
    connector.addBean(new SslHandshakeListener() {

        @Override
        public void handshakeSucceeded(Event event) {
            if (Arrays.equals(serverSession.get(), event.getSSLEngine().getSession().getId()))
                serverLatch.countDown();
        }
    });
    CountDownLatch clientLatch = new CountDownLatch(1);
    client.addBean(new SslHandshakeListener() {

        @Override
        public void handshakeSucceeded(Event event) {
            if (Arrays.equals(clientSession.get(), event.getSSLEngine().getSession().getId()))
                clientLatch.countDown();
        }
    });
    // Second request should have the same session ID.
    response = client.newRequest("localhost", connector.getLocalPort()).scheme(HttpScheme.HTTPS.asString()).header(HttpHeader.CONNECTION, "close").timeout(5, TimeUnit.SECONDS).send();
    Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    Assert.assertTrue(serverLatch.await(1, TimeUnit.SECONDS));
    Assert.assertTrue(clientLatch.await(1, TimeUnit.SECONDS));
}
Also used : SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) SslHandshakeListener(org.eclipse.jetty.io.ssl.SslHandshakeListener) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 73 with AtomicReference

use of java.util.concurrent.atomic.AtomicReference in project jetty.project by eclipse.

the class HttpClientAuthenticationTest method test_BasicAuthentication_WithAuthenticationRemoved.

@Test
public void test_BasicAuthentication_WithAuthenticationRemoved() throws Exception {
    startBasic(new EmptyServerHandler());
    final AtomicReference<CountDownLatch> requests = new AtomicReference<>(new CountDownLatch(2));
    Request.Listener.Adapter requestListener = new Request.Listener.Adapter() {

        @Override
        public void onSuccess(Request request) {
            requests.get().countDown();
        }
    };
    client.getRequestListeners().add(requestListener);
    AuthenticationStore authenticationStore = client.getAuthenticationStore();
    URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort());
    BasicAuthentication authentication = new BasicAuthentication(uri, realm, "basic", "basic");
    authenticationStore.addAuthentication(authentication);
    Request request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
    ContentResponse response = request.timeout(5, TimeUnit.SECONDS).send();
    Assert.assertNotNull(response);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));
    authenticationStore.removeAuthentication(authentication);
    requests.set(new CountDownLatch(1));
    request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
    response = request.timeout(5, TimeUnit.SECONDS).send();
    Assert.assertNotNull(response);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));
    Authentication.Result result = authenticationStore.findAuthenticationResult(request.getURI());
    Assert.assertNotNull(result);
    authenticationStore.removeAuthenticationResult(result);
    requests.set(new CountDownLatch(1));
    request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
    response = request.timeout(5, TimeUnit.SECONDS).send();
    Assert.assertNotNull(response);
    Assert.assertEquals(401, response.getStatus());
    Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) Authentication(org.eclipse.jetty.client.api.Authentication) DigestAuthentication(org.eclipse.jetty.client.util.DigestAuthentication) BasicAuthentication(org.eclipse.jetty.client.util.BasicAuthentication) BasicAuthentication(org.eclipse.jetty.client.util.BasicAuthentication) AuthenticationStore(org.eclipse.jetty.client.api.AuthenticationStore) Test(org.junit.Test)

Example 74 with AtomicReference

use of java.util.concurrent.atomic.AtomicReference in project jetty.project by eclipse.

the class HttpClientFailureTest method testFailureBeforeRequestCommit.

@Test
public void testFailureBeforeRequestCommit() throws Exception {
    startServer(new EmptyServerHandler());
    final AtomicReference<HttpConnectionOverHTTP> connectionRef = new AtomicReference<>();
    client = new HttpClient(new HttpClientTransportOverHTTP() {

        @Override
        protected HttpConnectionOverHTTP newHttpConnection(EndPoint endPoint, HttpDestination destination, Promise<Connection> promise) {
            HttpConnectionOverHTTP connection = super.newHttpConnection(endPoint, destination, promise);
            connectionRef.set(connection);
            return connection;
        }
    }, null);
    client.start();
    try {
        client.newRequest("localhost", connector.getLocalPort()).onRequestHeaders(request -> connectionRef.get().getEndPoint().close()).timeout(5, TimeUnit.SECONDS).send();
        Assert.fail();
    } catch (ExecutionException x) {
    // Expected.
    }
    DuplexConnectionPool connectionPool = (DuplexConnectionPool) connectionRef.get().getHttpDestination().getConnectionPool();
    Assert.assertEquals(0, connectionPool.getConnectionCount());
    Assert.assertEquals(0, connectionPool.getActiveConnections().size());
    Assert.assertEquals(0, connectionPool.getIdleConnections().size());
}
Also used : Promise(org.eclipse.jetty.util.Promise) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpClientTransportOverHTTP(org.eclipse.jetty.client.http.HttpClientTransportOverHTTP) EndPoint(org.eclipse.jetty.io.EndPoint) ExecutionException(java.util.concurrent.ExecutionException) HttpConnectionOverHTTP(org.eclipse.jetty.client.http.HttpConnectionOverHTTP) Test(org.junit.Test)

Example 75 with AtomicReference

use of java.util.concurrent.atomic.AtomicReference in project jetty.project by eclipse.

the class HttpClientAsyncContentTest method testSmallAsyncContent.

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

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            ServletOutputStream output = response.getOutputStream();
            output.write(65);
            output.flush();
            output.write(66);
        }
    });
    final AtomicInteger contentCount = new AtomicInteger();
    final AtomicReference<Callback> callbackRef = new AtomicReference<>();
    final AtomicReference<CountDownLatch> contentLatch = new AtomicReference<>(new CountDownLatch(1));
    final CountDownLatch completeLatch = new CountDownLatch(1);
    client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).onResponseContentAsync(new Response.AsyncContentListener() {

        @Override
        public void onContent(Response response, ByteBuffer content, Callback callback) {
            contentCount.incrementAndGet();
            callbackRef.set(callback);
            contentLatch.get().countDown();
        }
    }).send(new Response.CompleteListener() {

        @Override
        public void onComplete(Result result) {
            completeLatch.countDown();
        }
    });
    Assert.assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS));
    Callback callback = callbackRef.get();
    // Wait a while to be sure that the parsing does not proceed.
    TimeUnit.MILLISECONDS.sleep(1000);
    Assert.assertEquals(1, contentCount.get());
    // Succeed the content callback to proceed with parsing.
    callbackRef.set(null);
    contentLatch.set(new CountDownLatch(1));
    callback.succeeded();
    Assert.assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS));
    callback = callbackRef.get();
    // Wait a while to be sure that the parsing does not proceed.
    TimeUnit.MILLISECONDS.sleep(1000);
    Assert.assertEquals(2, contentCount.get());
    Assert.assertEquals(1, completeLatch.getCount());
    // Succeed the content callback to proceed with parsing.
    callbackRef.set(null);
    contentLatch.set(new CountDownLatch(1));
    callback.succeeded();
    Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
    Assert.assertEquals(2, contentCount.get());
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) Result(org.eclipse.jetty.client.api.Result) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.eclipse.jetty.client.api.Response) Callback(org.eclipse.jetty.util.Callback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Aggregations

AtomicReference (java.util.concurrent.atomic.AtomicReference)1331 Test (org.junit.Test)668 CountDownLatch (java.util.concurrent.CountDownLatch)437 IOException (java.io.IOException)263 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)205 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)159 ArrayList (java.util.ArrayList)108 HashMap (java.util.HashMap)105 List (java.util.List)95 Map (java.util.Map)77 Test (org.testng.annotations.Test)76 File (java.io.File)64 ExecutionException (java.util.concurrent.ExecutionException)60 HashSet (java.util.HashSet)54 URI (java.net.URI)48 TimeoutException (java.util.concurrent.TimeoutException)48 HttpServletRequest (javax.servlet.http.HttpServletRequest)48 HttpServletResponse (javax.servlet.http.HttpServletResponse)46 MockResponse (okhttp3.mockwebserver.MockResponse)46 ByteBuffer (java.nio.ByteBuffer)44