Example usage for io.vertx.core Vertx currentContext

List of usage examples for io.vertx.core Vertx currentContext

Introduction

In this page you can find the example usage for io.vertx.core Vertx currentContext.

Prototype

static @Nullable Context currentContext() 

Source Link

Document

Gets the current context

Usage

From source file:com.chibchasoft.vertx.util.VertxUtil.java

License:Open Source License

/**
 * <p>Similar to {@link Context#executeBlocking(Handler, Handler)} but when this method is called several times on
 * the same {@link Context} for the same {@code identifier}, executions associated to that value for that context
 * will be executed serially. However, there will be no ordering guarantees in relation to executions for different
 * identifiers for the same context or even for the same identifier but for different contexts.</p>
 *
 * <p><b>NOTES:</b></p>
 *
 * - This method needs to be called within the scope of a Vertx Context.<br>
 * - This method relies on a Vertx internal API method
 * {@link ContextInternal#executeBlocking(Handler, TaskQueue, Handler)}.<br>
 *
 * @param identifier          Object used to group and serialize executions
 * @param blockingCodeHandler handler representing the blocking code to run
 * @param resultHandler       handler that will be called when the blocking code is complete
 * @param <T>                 the type of the result
 *///from   w w w  . jav a  2  s  . com
static <T> void executeBlocking(Object identifier, Handler<Future<T>> blockingCodeHandler,
        Handler<AsyncResult<T>> resultHandler) {
    executeBlocking(Vertx.currentContext(), identifier, blockingCodeHandler, resultHandler);
}

From source file:com.hurence.logisland.engine.vanilla.stream.amqp.ConnectionControl.java

License:Apache License

void scheduleReconnect(ReconnectHandler reconnectHandler) {
    currentDelay = nextDelay();//from  w w  w. j  a v a 2s.  c o m
    final Handler timerHandler = ignored -> {
        try {
            reconnectHandler.reconnect(Vertx.currentContext().owner());
        } catch (Exception e) {
            logger.warn("Reconnection failed: {}", e.getMessage());
            scheduleReconnect(reconnectHandler);
        }
    };

    if (currentDelay <= 0) {
        Vertx.currentContext().runOnContext(timerHandler);
    } else {
        logger.info("Scheduling connect attempt in  {} ms at {}", currentDelay,
                Instant.now().plusMillis(currentDelay));
        Vertx.currentContext().owner().setTimer(currentDelay, timerHandler);
    }
}

From source file:examples.VertxProtonExamples.java

License:Apache License

@SuppressWarnings("unused")
public void example4(ProtonClient client) {
    client.connect("hostname", 5672, connectResult -> {
        // In this case the context will be either the one used to call connect
        // or one created during the process if there was none originally.
        Context connectionCtx = Vertx.currentContext();
    });//from w w w . j  a va 2 s . c  o  m
}

From source file:io.gravitee.fetcher.http.vertx.VertxCompletableFuture.java

License:Apache License

/**
 * Creates a new {@link VertxCompletableFuture} using the current {@link Context}. This method
 * <strong>must</strong> be used from a Vert.x thread, or fails.
 *///from w  w w.ja v  a 2s.c o  m
public VertxCompletableFuture() {
    this(Vertx.currentContext());
}

From source file:io.gravitee.fetcher.http.vertx.VertxCompletableFuture.java

License:Apache License

/**
 * Creates a {@link VertxCompletableFuture} from the given {@link Context} and {@link CompletableFuture}.
 * <p>// w  w  w.j a v  a2 s .  c om
 * The created {@link VertxCompletableFuture} is completed successfully or not when the given future
 * completes successfully or not. The completion is called on the given {@link Context}, immediately if it is
 * already executing on the right context, asynchronously if not.
 *
 * @param context the context
 * @param future  the future
 * @param <T>     the type of result
 * @return the creation {@link VertxCompletableFuture}
 */
public static <T> VertxCompletableFuture<T> from(Context context, CompletableFuture<T> future) {
    VertxCompletableFuture<T> res = new VertxCompletableFuture<>(Objects.requireNonNull(context));
    Objects.requireNonNull(future).whenComplete((result, error) -> {
        if (context == Vertx.currentContext()) {
            res.complete(result, error);
        } else {
            res.context.runOnContext(v -> res.complete(result, error));
        }
    });
    return res;
}

From source file:io.gravitee.fetcher.http.vertx.VertxCompletableFuture.java

License:Apache License

/**
 * Creates a new {@link VertxCompletableFuture} from the given {@link Context} instance and given
 * {@link Future}. The returned future uses the current Vert.x context, or creates a new one.
 * <p>/* w  ww  . jav a  2s  .c o m*/
 * The created {@link VertxCompletableFuture} is completed successfully or not when the given future
 * completes successfully or not. The created {@link VertxCompletableFuture} is completed successfully or not
 * when the given future completes successfully or not. The completion is called on the given {@link Context},
 * immediately if it is already executing on the right context, asynchronously if not.
 *
 * @param context the context
 * @param future  the Vert.x future
 * @param <T>     the type of the result
 * @return the new {@link VertxCompletableFuture}
 */
public static <T> VertxCompletableFuture<T> from(Context context, Future<T> future) {
    VertxCompletableFuture<T> res = new VertxCompletableFuture<>(Objects.requireNonNull(context));
    Objects.requireNonNull(future).setHandler(ar -> {
        if (context == Vertx.currentContext()) {
            res.completeFromAsyncResult(ar);
        } else {
            res.context.runOnContext(v -> res.completeFromAsyncResult(ar));
        }
    });
    return res;
}

From source file:io.gravitee.fetcher.http.vertx.VertxCompletableFuture.java

License:Apache License

/**
 * Creates a new {@link VertxCompletableFuture} using the current context. This method is used to switch between
 * Vert.x contexts.//from   w w  w .ja v  a2  s .  c o m
 *
 * @return the created {@link VertxCompletableFuture}
 */
public VertxCompletableFuture<T> withContext() {
    Context context = Objects.requireNonNull(Vertx.currentContext());
    return withContext(context);
}

From source file:io.gravitee.gateway.http.connector.VertxHttpClient.java

License:Apache License

@Override
public ProxyConnection request(ProxyRequest proxyRequest) {
    HttpClient httpClient = httpClients.computeIfAbsent(Vertx.currentContext(), createHttpClient());

    // Remove hop-by-hop headers.
    if (!proxyRequest.isWebSocket()) {
        for (CharSequence header : HOP_HEADERS) {
            proxyRequest.headers().remove(header);
        }/*  w  w  w.j  a v a  2 s. c o m*/
    } else {
        for (CharSequence header : WS_HOP_HEADERS) {
            proxyRequest.headers().remove(header);
        }
    }

    final URI uri = proxyRequest.uri();
    final int port = uri.getPort() != -1 ? uri.getPort() : (HTTPS_SCHEME.equals(uri.getScheme()) ? 443 : 80);

    final String host = (port == DEFAULT_HTTP_PORT || port == DEFAULT_HTTPS_PORT) ? uri.getHost()
            : uri.getHost() + ':' + port;

    proxyRequest.headers().set(HttpHeaders.HOST, host);

    // Apply headers from endpoint
    if (endpoint.getHeaders() != null && !endpoint.getHeaders().isEmpty()) {
        endpoint.getHeaders().forEach(proxyRequest.headers()::set);
    }

    String relativeUri = (uri.getRawQuery() == null) ? uri.getRawPath()
            : uri.getRawPath() + '?' + uri.getRawQuery();

    if (proxyRequest.isWebSocket()) {
        VertxWebSocketProxyConnection webSocketProxyConnection = new VertxWebSocketProxyConnection();
        WebSocketProxyRequest wsProxyRequest = (WebSocketProxyRequest) proxyRequest;

        httpClient.websocket(port, uri.getHost(), relativeUri, new Handler<WebSocket>() {
            @Override
            public void handle(WebSocket event) {
                // The client -> gateway connection must be upgraded now that the one between gateway -> upstream
                // has been accepted
                wsProxyRequest.upgrade();

                // From server to client
                wsProxyRequest.frameHandler(frame -> {
                    if (frame.type() == io.gravitee.gateway.api.ws.WebSocketFrame.Type.BINARY) {
                        event.writeBinaryMessage(io.vertx.core.buffer.Buffer.buffer(frame.data().getBytes()));
                    } else if (frame.type() == io.gravitee.gateway.api.ws.WebSocketFrame.Type.TEXT) {
                        event.writeTextMessage(frame.data().toString());
                    }
                });

                wsProxyRequest.closeHandler(result -> event.close());

                // From client to server
                event.frameHandler(frame -> wsProxyRequest.write(new VertxWebSocketFrame(frame)));

                event.closeHandler(event1 -> wsProxyRequest.close());

                event.exceptionHandler(new Handler<Throwable>() {
                    @Override
                    public void handle(Throwable throwable) {
                        wsProxyRequest.reject(HttpStatusCode.BAD_REQUEST_400);
                        ProxyResponse clientResponse = new EmptyProxyResponse(HttpStatusCode.BAD_REQUEST_400);

                        clientResponse.headers().set(HttpHeaders.CONNECTION,
                                HttpHeadersValues.CONNECTION_CLOSE);
                        webSocketProxyConnection.handleResponse(clientResponse);
                    }
                });

                // Tell the reactor that the request has been handled by the HTTP client
                webSocketProxyConnection.handleResponse(new SwitchProtocolProxyResponse());
            }
        }, throwable -> {
            if (throwable instanceof WebsocketRejectedException) {
                wsProxyRequest.reject(((WebsocketRejectedException) throwable).getStatus());
                ProxyResponse clientResponse = new EmptyProxyResponse(
                        ((WebsocketRejectedException) throwable).getStatus());

                clientResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE);
                webSocketProxyConnection.handleResponse(clientResponse);
            } else {
                wsProxyRequest.reject(HttpStatusCode.BAD_GATEWAY_502);
                ProxyResponse clientResponse = new EmptyProxyResponse(HttpStatusCode.BAD_GATEWAY_502);

                clientResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE);
                webSocketProxyConnection.handleResponse(clientResponse);
            }
        });

        return webSocketProxyConnection;
    } else {
        // Prepare HTTP request
        HttpClientRequest clientRequest = httpClient.request(HttpMethod.valueOf(proxyRequest.method().name()),
                port, uri.getHost(), relativeUri);
        clientRequest.setTimeout(endpoint.getHttpClientOptions().getReadTimeout());
        clientRequest.setFollowRedirects(endpoint.getHttpClientOptions().isFollowRedirects());

        if (proxyRequest.method() == io.gravitee.common.http.HttpMethod.OTHER) {
            clientRequest.setRawMethod(proxyRequest.rawMethod());
        }

        VertxProxyConnection proxyConnection = new VertxProxyConnection(proxyRequest, clientRequest);
        clientRequest.handler(
                clientResponse -> handleClientResponse(proxyConnection, clientResponse, clientRequest));

        clientRequest.connectionHandler(connection -> {
            connection.exceptionHandler(ex -> {
                // I don't want to fill my logs with error
            });
        });

        clientRequest.exceptionHandler(event -> {
            if (!proxyConnection.isCanceled() && !proxyConnection.isTransmitted()) {
                proxyRequest.metrics().setMessage(event.getMessage());

                if (proxyConnection.timeoutHandler() != null && (event instanceof ConnectException
                        || event instanceof TimeoutException || event instanceof NoRouteToHostException
                        || event instanceof UnknownHostException)) {
                    proxyConnection.handleConnectTimeout(event);
                } else {
                    ProxyResponse clientResponse = new EmptyProxyResponse(
                            ((event instanceof ConnectTimeoutException) || (event instanceof TimeoutException))
                                    ? HttpStatusCode.GATEWAY_TIMEOUT_504
                                    : HttpStatusCode.BAD_GATEWAY_502);

                    clientResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE);
                    proxyConnection.handleResponse(clientResponse);
                }
            }
        });

        return proxyConnection;
    }
}

From source file:io.gravitee.gateway.http.vertx.VertxHttpClient.java

License:Apache License

@Override
public ClientRequest request(io.gravitee.common.http.HttpMethod method, URI uri, HttpHeaders headers,
        Handler<ClientResponse> responseHandler) {
    HttpClient httpClient = httpClients.computeIfAbsent(Vertx.currentContext(), createHttpClient());

    final int port = uri.getPort() != -1 ? uri.getPort() : (HTTPS_SCHEME.equals(uri.getScheme()) ? 443 : 80);

    String relativeUri = (uri.getRawQuery() == null) ? uri.getRawPath()
            : uri.getRawPath() + '?' + uri.getRawQuery();

    HttpClientRequest clientRequest = httpClient.request(convert(method), port, uri.getHost(), relativeUri,
            clientResponse -> handleClientResponse(clientResponse, responseHandler));

    clientRequest.setTimeout(endpoint.getHttpClientOptions().getReadTimeout());

    VertxClientRequest invokerRequest = new VertxClientRequest(clientRequest);

    clientRequest.exceptionHandler(event -> {
        LOGGER.error("Server proxying failed: {}", event.getMessage());

        if (invokerRequest.connectTimeoutHandler() != null && event instanceof ConnectTimeoutException) {
            invokerRequest.connectTimeoutHandler().handle(event);
        } else {/*from  w  ww .java  2 s .co m*/
            VertxClientResponse clientResponse = new VertxClientResponse(
                    ((event instanceof ConnectTimeoutException) || (event instanceof TimeoutException))
                            ? HttpStatusCode.GATEWAY_TIMEOUT_504
                            : HttpStatusCode.BAD_GATEWAY_502);

            clientResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE);

            Buffer buffer = null;

            if (event.getMessage() != null) {
                // Create body content with error message
                buffer = Buffer.buffer(event.getMessage());
                clientResponse.headers().set(HttpHeaders.CONTENT_LENGTH, Integer.toString(buffer.length()));
            }

            responseHandler.handle(clientResponse);

            if (buffer != null) {
                clientResponse.bodyHandler().handle(buffer);
            }

            clientResponse.endHandler().handle(null);
        }
    });

    // Copy headers to final API
    copyRequestHeaders(headers, clientRequest,
            (port == 80 || port == 443) ? uri.getHost() : uri.getHost() + ':' + port);

    // Check chunk flag on the request if there are some content to push and if transfer_encoding is set
    // with chunk value
    if (hasContent(headers)) {
        String transferEncoding = headers.getFirst(HttpHeaders.TRANSFER_ENCODING);
        if (HttpHeadersValues.TRANSFER_ENCODING_CHUNKED.equalsIgnoreCase(transferEncoding)) {
            clientRequest.setChunked(true);
        }
    }

    // Send HTTP head as soon as possible
    clientRequest.sendHead();

    return invokerRequest;
}

From source file:io.gravitee.resource.oauth2.am.OAuth2AMResource.java

License:Apache License

@Override
public void introspect(String accessToken, Handler<OAuth2Response> responseHandler) {
    HttpClient httpClient = httpClients.computeIfAbsent(Vertx.currentContext(),
            context -> vertx.createHttpClient(httpClientOptions));

    logger.debug("Introspect access token by requesting {}", introspectionEndpointURI);

    HttpClientRequest request = httpClient.post(introspectionEndpointURI);

    request.headers().add(HttpHeaders.AUTHORIZATION, introspectionEndpointAuthorization);
    request.headers().add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
    request.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);

    request.handler(response -> response.bodyHandler(buffer -> {
        logger.debug("AM Introspection endpoint returns a response with a {} status code",
                response.statusCode());//from  w  w w  . j a va 2  s.  com
        if (response.statusCode() == HttpStatusCode.OK_200) {
            // Introspection Response for AM v2 always returns HTTP 200
            // with an "active" boolean indicator of whether or not the presented token is currently active.
            if (configuration().getVersion() == OAuth2ResourceConfiguration.Version.V2_X) {
                // retrieve active indicator
                JsonObject jsonObject = buffer.toJsonObject();
                boolean active = jsonObject.getBoolean(INTROSPECTION_ACTIVE_INDICATOR, false);
                responseHandler.handle(new OAuth2Response(active,
                        (active) ? buffer.toString() : "{\"error\": \"Invalid Access Token\"}"));
            } else {
                responseHandler.handle(new OAuth2Response(true, buffer.toString()));
            }
        } else {
            responseHandler.handle(new OAuth2Response(false, buffer.toString()));
        }
    }));

    request.exceptionHandler(event -> {
        logger.error("An error occurs while checking access_token", event);
        responseHandler.handle(new OAuth2Response(false, event.getMessage()));
    });

    request.end("token=" + accessToken);
}