Search in sources :

Example 1 with Response

use of oap.http.Response in project oap by oaplatform.

the class NioHandlerAdapter method handle.

@Override
public void handle(final HttpRequest httpRequest, final HttpAsyncExchange httpAsyncExchange, final HttpContext httpContext) throws HttpException, IOException {
    LOGGER.trace("handling [{}]", httpRequest);
    final HttpInetConnection connection = (HttpInetConnection) httpContext.getAttribute(HttpCoreContext.HTTP_CONNECTION);
    final InetAddress remoteAddress = connection.getRemoteAddress();
    final HttpResponse response = httpAsyncExchange.getResponse();
    final String httpContextProtocol = String.valueOf(httpContext.getAttribute("protocol"));
    if (Protocol.LOCAL.equals(this.protocol) && !Inet.isLocalAddress(remoteAddress)) {
        response.setStatusCode(HTTP_FORBIDDEN);
    } else {
        Request request = new Request(httpRequest, new Context(location, remoteAddress, httpContextProtocol));
        handler.handle(request, new Response(response, corsPolicy.getCors(request)));
    }
    httpAsyncExchange.submitResponse();
}
Also used : Context(oap.http.Context) HttpCoreContext(org.apache.http.protocol.HttpCoreContext) HttpContext(org.apache.http.protocol.HttpContext) Response(oap.http.Response) HttpResponse(org.apache.http.HttpResponse) HttpRequest(org.apache.http.HttpRequest) Request(oap.http.Request) HttpResponse(org.apache.http.HttpResponse) HttpInetConnection(org.apache.http.HttpInetConnection) InetAddress(java.net.InetAddress)

Example 2 with Response

use of oap.http.Response in project oap by oaplatform.

the class WsService method handle.

@Override
public void handle(Request request, Response response) {
    try {
        val method = reflection.method(m -> methodMatches(request.requestLine, request.httpMethod, m), (o1, o2) -> {
            val path1 = o1.findAnnotation(WsMethod.class).map(WsMethod::path).orElse(o1.name());
            val path2 = o2.findAnnotation(WsMethod.class).map(WsMethod::path).orElse(o1.name());
            return path1.compareTo(path2);
        }).orElse(null);
        if (method == null)
            response.respond(NOT_FOUND);
        else {
            Name name = Metrics.name("rest_timer").tag("service", service()).tag("method", method.name());
            if (!sessionAware) {
                handleInternal(request, response, method, name, null);
            } else {
                String cookieId = request.cookie(SessionManager.COOKIE_ID).orElse(null);
                val authToken = Interceptor.getSessionToken(request);
                Session session;
                if (cookieId != null && (session = sessionManager.getSessionById(cookieId)) != null && Objects.equals(authToken, session.get(Interceptor.AUTHORIZATION).orElse(null))) {
                    log.debug("{}: Valid SID [{}] found in cookie", service(), cookieId);
                    handleInternal(request, response, method, name, __(cookieId, session));
                } else {
                    cookieId = UUID.randomUUID().toString();
                    log.debug("{}: Creating new session with SID [{}]", service(), cookieId);
                    session = new Session();
                    if (authToken != null)
                        session.set(Interceptor.AUTHORIZATION, authToken);
                    sessionManager.put(cookieId, session);
                    handleInternal(request, response, method, name, __(cookieId, session));
                }
            }
        }
    } catch (Throwable e) {
        wsError(response, e);
    }
}
Also used : lombok.val(lombok.val) Pair(oap.util.Pair) Result(oap.util.Result) Binder(oap.json.Binder) Metrics(oap.metrics.Metrics) NOT_FOUND(oap.http.HttpResponse.NOT_FOUND) Reflection(oap.reflect.Reflection) Pair.__(oap.util.Pair.__) HashMap(java.util.HashMap) Strings(oap.util.Strings) Function(java.util.function.Function) NO_CONTENT(oap.http.HttpResponse.NO_CONTENT) Reflect(oap.reflect.Reflect) LinkedHashMap(java.util.LinkedHashMap) HTTP_INTERNAL_ERROR(java.net.HttpURLConnection.HTTP_INTERNAL_ERROR) Map(java.util.Map) Session(oap.http.Session) TEXT_PLAIN(oap.http.ContentTypes.TEXT_PLAIN) Stream(oap.util.Stream) ReflectException(oap.reflect.ReflectException) APPLICATION_JSON(org.apache.http.entity.ContentType.APPLICATION_JSON) Name(oap.metrics.Name) Collectors.toLinkedHashMap(oap.util.Collectors.toLinkedHashMap) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Handler(oap.http.Handler) Collection(java.util.Collection) lombok.val(lombok.val) ContentType(org.apache.http.entity.ContentType) DateTime(org.joda.time.DateTime) Response(oap.http.Response) JsonException(oap.json.JsonException) UUID(java.util.UUID) Request(oap.http.Request) TEXT(oap.ws.WsResponse.TEXT) Serializable(java.io.Serializable) InvocationTargetException(java.lang.reflect.InvocationTargetException) Validators(oap.ws.validate.Validators) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) WrappingRuntimeException(oap.util.WrappingRuntimeException) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) Throwables(oap.util.Throwables) HttpResponse(oap.http.HttpResponse) ValidationErrors(oap.ws.validate.ValidationErrors) Name(oap.metrics.Name) Session(oap.http.Session)

Example 3 with Response

use of oap.http.Response in project oap by oaplatform.

the class WsService method handleInternal.

private void handleInternal(Request request, Response response, Reflection.Method method, Name name, Pair<String, Session> session) {
    log.trace("{}: Internal session status: [{}]", service(), session);
    Optional<WsMethod> wsMethod = method.findAnnotation(WsMethod.class);
    Function<Reflection.Parameter, Object> func = (p) -> {
        val ret = getValue(session, request, wsMethod, p).orElse(Optional.empty());
        if (ret instanceof Optional)
            return ((Optional<?>) ret).orElse(null);
        return ret;
    };
    HttpResponse interceptorResponse = session != null ? runInterceptors(request, session._2, method, func) : null;
    if (interceptorResponse != null) {
        response.respond(interceptorResponse);
    } else {
        Metrics.measureTimer(name, () -> {
            List<Reflection.Parameter> parameters = method.parameters;
            LinkedHashMap<Reflection.Parameter, Object> originalValues = getOriginalValues(session, parameters, request, wsMethod);
            ValidationErrors paramValidation = ValidationErrors.empty();
            originalValues.forEach((parameter, value) -> paramValidation.merge(Validators.forParameter(method, parameter, impl, true).validate(value, originalValues)));
            paramValidation.throwIfInvalid();
            Validators.forMethod(method, impl, true).validate(originalValues.values().toArray(new Object[originalValues.size()]), originalValues).throwIfInvalid();
            LinkedHashMap<Reflection.Parameter, Object> values = getValues(originalValues);
            Object[] paramValues = values.values().toArray(new Object[values.size()]);
            values.forEach((parameter, value) -> paramValidation.merge(Validators.forParameter(method, parameter, impl, false).validate(value, values)));
            paramValidation.throwIfInvalid();
            Validators.forMethod(method, impl, false).validate(paramValues, values).throwIfInvalid();
            Object result = method.invoke(impl, paramValues);
            Boolean isRaw = wsMethod.map(WsMethod::raw).orElse(false);
            ContentType produces = wsMethod.map(wsm -> ContentType.create(wsm.produces()).withCharset(UTF_8)).orElse(APPLICATION_JSON);
            String cookie = session != null ? new HttpResponse.CookieBuilder().withSID(session._1).withPath(sessionManager.cookiePath).withExpires(DateTime.now().plusMinutes(sessionManager.cookieExpiration)).withDomain(sessionManager.cookieDomain).withDomain(sessionManager.cookieDomain).build() : null;
            if (method.isVoid())
                response.respond(NO_CONTENT);
            else if (result instanceof HttpResponse)
                response.respond(((HttpResponse) result).withCookie(cookie));
            else if (result instanceof Optional<?>) {
                response.respond(((Optional<?>) result).map(r -> HttpResponse.ok(runPostInterceptors(r, session, method), isRaw, produces).withCookie(cookie)).orElse(NOT_FOUND));
            } else if (result instanceof Result<?, ?>) {
                Result<HttpResponse, HttpResponse> resp = ((Result<?, ?>) result).mapSuccess(r -> HttpResponse.ok(r, isRaw, produces).withCookie(cookie)).mapFailure(r -> HttpResponse.status(HTTP_INTERNAL_ERROR, "", r).withCookie(cookie));
                response.respond(resp.isSuccess() ? ((Result<?, ?>) result).mapSuccess(r -> HttpResponse.ok(runPostInterceptors(r, session, method), isRaw, produces).withCookie(cookie)).successValue : ((Result<?, ?>) result).mapFailure(r -> HttpResponse.status(HTTP_INTERNAL_ERROR, "", r).withCookie(cookie)).failureValue);
            } else if (result instanceof Stream<?>) {
                response.respond(HttpResponse.stream(((Stream<?>) result).map(v -> runPostInterceptors(v, session, method)), isRaw, produces).withCookie(cookie));
            } else
                response.respond(HttpResponse.ok(runPostInterceptors(result, session, method), isRaw, produces).withCookie(cookie));
        });
    }
}
Also used : Pair(oap.util.Pair) Result(oap.util.Result) Binder(oap.json.Binder) Metrics(oap.metrics.Metrics) NOT_FOUND(oap.http.HttpResponse.NOT_FOUND) Reflection(oap.reflect.Reflection) Pair.__(oap.util.Pair.__) HashMap(java.util.HashMap) Strings(oap.util.Strings) Function(java.util.function.Function) NO_CONTENT(oap.http.HttpResponse.NO_CONTENT) Reflect(oap.reflect.Reflect) LinkedHashMap(java.util.LinkedHashMap) HTTP_INTERNAL_ERROR(java.net.HttpURLConnection.HTTP_INTERNAL_ERROR) Map(java.util.Map) Session(oap.http.Session) TEXT_PLAIN(oap.http.ContentTypes.TEXT_PLAIN) Stream(oap.util.Stream) ReflectException(oap.reflect.ReflectException) APPLICATION_JSON(org.apache.http.entity.ContentType.APPLICATION_JSON) Name(oap.metrics.Name) Collectors.toLinkedHashMap(oap.util.Collectors.toLinkedHashMap) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Handler(oap.http.Handler) Collection(java.util.Collection) lombok.val(lombok.val) ContentType(org.apache.http.entity.ContentType) DateTime(org.joda.time.DateTime) Response(oap.http.Response) JsonException(oap.json.JsonException) UUID(java.util.UUID) Request(oap.http.Request) TEXT(oap.ws.WsResponse.TEXT) Serializable(java.io.Serializable) InvocationTargetException(java.lang.reflect.InvocationTargetException) Validators(oap.ws.validate.Validators) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) WrappingRuntimeException(oap.util.WrappingRuntimeException) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) Throwables(oap.util.Throwables) HttpResponse(oap.http.HttpResponse) ValidationErrors(oap.ws.validate.ValidationErrors) lombok.val(lombok.val) Optional(java.util.Optional) ContentType(org.apache.http.entity.ContentType) ValidationErrors(oap.ws.validate.ValidationErrors) HttpResponse(oap.http.HttpResponse) Result(oap.util.Result) Stream(oap.util.Stream)

Aggregations

Request (oap.http.Request)3 Response (oap.http.Response)3 Serializable (java.io.Serializable)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 HTTP_INTERNAL_ERROR (java.net.HttpURLConnection.HTTP_INTERNAL_ERROR)2 UTF_8 (java.nio.charset.StandardCharsets.UTF_8)2 Collection (java.util.Collection)2 HashMap (java.util.HashMap)2 LinkedHashMap (java.util.LinkedHashMap)2 List (java.util.List)2 Map (java.util.Map)2 Objects (java.util.Objects)2 Optional (java.util.Optional)2 UUID (java.util.UUID)2 Function (java.util.function.Function)2 Pattern (java.util.regex.Pattern)2 Slf4j (lombok.extern.slf4j.Slf4j)2 lombok.val (lombok.val)2 TEXT_PLAIN (oap.http.ContentTypes.TEXT_PLAIN)2 Handler (oap.http.Handler)2