Search in sources :

Example 1 with Request

use of io.gravitee.gateway.api.Request in project gravitee-gateway by gravitee-io.

the class ApiReactorHandler method doHandle.

@Override
protected void doHandle(Request serverRequest, Response serverResponse, Handler<Response> handler) {
    // Prepare request execution context
    ExecutionContext executionContext = executionContextFactory.create(serverRequest);
    executionContext.setAttribute(ExecutionContext.ATTR_CONTEXT_PATH, serverRequest.contextPath());
    try {
        // Set execution context attributes and metrics specific to this handler
        serverRequest.metrics().setApi(api.getId());
        executionContext.setAttribute(ExecutionContext.ATTR_API, api.getId());
        executionContext.setAttribute(ExecutionContext.ATTR_INVOKER, invoker);
        // Enable logging at client level
        if (api.getProxy().getLoggingMode().isClientMode()) {
            serverRequest = new LoggableClientRequest(serverRequest);
            serverResponse = new LoggableClientResponse(serverRequest, serverResponse);
        }
        Cors cors = api.getProxy().getCors();
        if (cors != null && cors.isEnabled()) {
            Request finalServerRequest = serverRequest;
            Response finalServerResponse = serverResponse;
            new CorsHandler(cors).responseHandler(new Handler<Response>() {

                @Override
                public void handle(Response response) {
                    handleClientRequest(finalServerRequest, finalServerResponse, executionContext, new CorsResponseHandler(handler));
                }
            }).handle(serverRequest, serverResponse, handler);
        } else {
            handleClientRequest(serverRequest, serverResponse, executionContext, handler);
        }
    } catch (Exception ex) {
        logger.error("An unexpected error occurs while processing request", ex);
        serverRequest.metrics().setMessage(Throwables.getStackTraceAsString(ex));
        // Send an INTERNAL_SERVER_ERROR (500)
        serverResponse.status(HttpStatusCode.INTERNAL_SERVER_ERROR_500);
        serverResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE);
        serverResponse.end();
        handler.handle(serverResponse);
    }
}
Also used : LoggableClientResponse(io.gravitee.gateway.handlers.api.logging.LoggableClientResponse) Response(io.gravitee.gateway.api.Response) ProxyResponse(io.gravitee.gateway.api.proxy.ProxyResponse) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) LoggableClientRequest(io.gravitee.gateway.handlers.api.logging.LoggableClientRequest) LoggableClientRequest(io.gravitee.gateway.handlers.api.logging.LoggableClientRequest) Request(io.gravitee.gateway.api.Request) CorsHandler(io.gravitee.gateway.handlers.api.cors.CorsHandler) Handler(io.gravitee.gateway.api.handler.Handler) CorsResponseHandler(io.gravitee.gateway.handlers.api.cors.CorsResponseHandler) AbstractReactorHandler(io.gravitee.gateway.reactor.handler.AbstractReactorHandler) CorsHandler(io.gravitee.gateway.handlers.api.cors.CorsHandler) LoggableClientResponse(io.gravitee.gateway.handlers.api.logging.LoggableClientResponse) Cors(io.gravitee.definition.model.Cors) CorsResponseHandler(io.gravitee.gateway.handlers.api.cors.CorsResponseHandler) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 2 with Request

use of io.gravitee.gateway.api.Request in project gravitee-gateway by gravitee-io.

the class AbstractPolicy method onResponse.

public void onResponse(Object... args) throws PolicyException {
    ExecutionContext executionContext = getParameterAssignableTo(ExecutionContext.class, args);
    PolicyChain policyChain = getParameterAssignableTo(PolicyChain.class, args);
    Request request = getParameterAssignableTo(Request.class, args);
    Response response = getParameterAssignableTo(Response.class, args);
    this.onResponse(request, response, policyChain, executionContext);
}
Also used : Response(io.gravitee.gateway.api.Response) PolicyChain(io.gravitee.policy.api.PolicyChain) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) Request(io.gravitee.gateway.api.Request)

Example 3 with Request

use of io.gravitee.gateway.api.Request in project gravitee-gateway by gravitee-io.

the class FailoverInvoker method invoke.

@Override
public Request invoke(ExecutionContext executionContext, Request serverRequest, ReadStream<Buffer> stream, Handler<ProxyConnection> connectionHandler) {
    final Request failoverServerRequest = new FailoverRequest(serverRequest);
    circuitBreaker.execute(new io.vertx.core.Handler<Future<ProxyConnection>>() {

        @Override
        public void handle(Future<ProxyConnection> event) {
            invoker.invoke(executionContext, failoverServerRequest, stream, proxyConnection -> {
                proxyConnection.exceptionHandler(event::fail);
                proxyConnection.responseHandler(response -> event.complete(new FailoverProxyConnection(proxyConnection, response)));
            });
        }
    }).setHandler(new io.vertx.core.Handler<AsyncResult<ProxyConnection>>() {

        @Override
        public void handle(AsyncResult<ProxyConnection> event) {
            if (event.failed()) {
                FailoverConnection connection = new FailoverConnection();
                connectionHandler.handle(connection);
                connection.sendBadGatewayResponse();
            } else {
                FailoverProxyConnection proxyConnection = (FailoverProxyConnection) event.result();
                connectionHandler.handle(proxyConnection);
                proxyConnection.sendResponse();
            }
        }
    });
    return failoverServerRequest;
}
Also used : Request(io.gravitee.gateway.api.Request) Handler(io.gravitee.gateway.api.handler.Handler) ProxyConnection(io.gravitee.gateway.api.proxy.ProxyConnection) Future(io.vertx.core.Future) AsyncResult(io.vertx.core.AsyncResult)

Example 4 with Request

use of io.gravitee.gateway.api.Request in project gravitee-gateway by gravitee-io.

the class ApiPolicyChainResolver method calculate.

@Override
protected List<Policy> calculate(StreamType streamType, Request request, Response response, ExecutionContext executionContext) {
    // Resolve the "configured" path according to the inbound request
    Path path = pathResolver.resolve(request.path());
    executionContext.setAttribute(ExecutionContext.ATTR_RESOLVED_PATH, path.getResolvedPath());
    return path.getRules().stream().filter(rule -> rule.isEnabled() && rule.getMethods().contains(request.method())).map(rule -> create(streamType, rule.getPolicy().getName(), rule.getPolicy().getConfiguration())).filter(Objects::nonNull).collect(Collectors.toList());
}
Also used : Path(io.gravitee.gateway.handlers.api.path.Path) Objects(java.util.Objects) Policy(io.gravitee.gateway.policy.Policy) List(java.util.List) Response(io.gravitee.gateway.api.Response) Path(io.gravitee.gateway.handlers.api.path.Path) StreamType(io.gravitee.gateway.policy.StreamType) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) Request(io.gravitee.gateway.api.Request) AbstractPolicyChainResolver(io.gravitee.gateway.policy.AbstractPolicyChainResolver) PathResolver(io.gravitee.gateway.handlers.api.path.PathResolver) Autowired(org.springframework.beans.factory.annotation.Autowired) Collectors(java.util.stream.Collectors)

Example 5 with Request

use of io.gravitee.gateway.api.Request in project gravitee-gateway by gravitee-io.

the class PlanPolicyChainResolver method calculate.

@Override
protected List<Policy> calculate(StreamType streamType, Request request, Response response, ExecutionContext executionContext) {
    if (streamType == StreamType.ON_REQUEST) {
        String plan = (String) executionContext.getAttribute(ExecutionContext.ATTR_PLAN);
        String application = (String) executionContext.getAttribute(ExecutionContext.ATTR_APPLICATION);
        // String user = (String) executionContext.getAttribute(ExecutionContext.ATTR_USER_ID);
        // request.metrics().setUserId(user);
        request.metrics().setPlan(plan);
        request.metrics().setApplication(application);
        Plan apiPlan = api.getPlan(plan);
        // The call is probably not relative to the same API.
        if (plan != null && apiPlan != null) {
            Map<String, Path> paths = api.getPlan(plan).getPaths();
            if (paths != null && !paths.isEmpty()) {
                // For 1.0.0, there is only a single root path defined
                // Must be reconsidered when user will be able to manage policies at the plan level by himself
                Path rootPath = paths.values().iterator().next();
                return rootPath.getRules().stream().filter(rule -> rule.isEnabled() && rule.getMethods().contains(request.method())).map(rule -> create(streamType, rule.getPolicy().getName(), rule.getPolicy().getConfiguration())).filter(Objects::nonNull).collect(Collectors.toList());
            }
        } else {
            logger.warn("No plan has been selected to process request {}. Returning an unauthorized HTTP status (401)", request.id());
            return null;
        }
    }
    return Collections.emptyList();
}
Also used : Path(io.gravitee.definition.model.Path) PolicyChain(io.gravitee.gateway.policy.impl.PolicyChain) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) RequestPolicyChain(io.gravitee.gateway.policy.impl.RequestPolicyChain) Autowired(org.springframework.beans.factory.annotation.Autowired) Plan(io.gravitee.gateway.handlers.api.definition.Plan) ResponsePolicyChain(io.gravitee.gateway.policy.impl.ResponsePolicyChain) Collectors(java.util.stream.Collectors) HttpStatusCode(io.gravitee.common.http.HttpStatusCode) Objects(java.util.Objects) List(java.util.List) Response(io.gravitee.gateway.api.Response) Request(io.gravitee.gateway.api.Request) Map(java.util.Map) Api(io.gravitee.gateway.handlers.api.definition.Api) Path(io.gravitee.definition.model.Path) io.gravitee.gateway.policy(io.gravitee.gateway.policy) PolicyResult(io.gravitee.policy.api.PolicyResult) Collections(java.util.Collections) Plan(io.gravitee.gateway.handlers.api.definition.Plan)

Aggregations

Request (io.gravitee.gateway.api.Request)51 Test (org.junit.Test)42 HttpHeaders (io.gravitee.common.http.HttpHeaders)24 Response (io.gravitee.gateway.api.Response)21 ExecutionContext (io.gravitee.gateway.api.ExecutionContext)16 PolicyChain (io.gravitee.policy.api.PolicyChain)11 ArrayList (java.util.ArrayList)8 SubscriptionRepository (io.gravitee.repository.management.api.SubscriptionRepository)7 SubscriptionCriteria (io.gravitee.repository.management.api.search.SubscriptionCriteria)7 Metrics (io.gravitee.reporter.api.http.Metrics)6 Before (org.junit.Before)6 Subscription (io.gravitee.repository.management.model.Subscription)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 UUID (io.gravitee.common.utils.UUID)4 Handler (io.gravitee.gateway.api.handler.Handler)4 TimeUnit (java.util.concurrent.TimeUnit)4 Assert.assertEquals (org.junit.Assert.assertEquals)4 Assert.assertNotNull (org.junit.Assert.assertNotNull)4 Mock (org.mockito.Mock)4 Mockito.when (org.mockito.Mockito.when)4