Search in sources :

Example 1 with APPLICATION_JSON

use of org.apache.http.entity.ContentType.APPLICATION_JSON 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)

Example 2 with APPLICATION_JSON

use of org.apache.http.entity.ContentType.APPLICATION_JSON in project data-prep by Talend.

the class DiffMetadata method onExecute.

private HttpRequestBase onExecute(final String dataSetId, final String preparationId, final List<Action> actionsToAdd) {
    // original actions (currently applied on the preparation)
    final List<Action> originalActions;
    try {
        originalActions = objectMapper.readerFor(new TypeReference<List<Action>>() {
        }).readValue(getInput());
    } catch (final IOException e) {
        throw new TDPException(UNABLE_TO_READ_PREPARATION, e, withBuilder().put("id", preparationId).build());
    }
    // prepare the preview parameters out of the preparation actions
    final List<PreviewParameters> previewParameters = IntStream.range(0, actionsToAdd.size()).mapToObj((index) -> {
        try {
            // base actions = original actions + actions to add from 0 to index
            final List<Action> previousActionsToAdd = actionsToAdd.subList(0, index);
            final List<Action> baseActions = new ArrayList<>(originalActions);
            baseActions.addAll(previousActionsToAdd);
            // diff actions actions = base actions + the action to add for diff
            final Action singleActionToAdd = actionsToAdd.get(index);
            final List<Action> diffActions = new ArrayList<>(baseActions);
            diffActions.add(singleActionToAdd);
            return new // 
            PreviewParameters(// 
            serializeActions(baseActions), // 
            serializeActions(diffActions), // 
            dataSetId, // 
            null, // 
            null, HEAD);
        } catch (IOException e) {
            throw new TDPException(UNABLE_TO_READ_PREPARATION, e, withBuilder().put("id", preparationId).build());
        }
    }).collect(toList());
    // create the http action to perform
    try {
        final String uri = transformationServiceUrl + "/transform/diff/metadata";
        final HttpPost transformationCall = new HttpPost(uri);
        transformationCall.setEntity(new StringEntity(objectMapper.writer().writeValueAsString(previewParameters), APPLICATION_JSON));
        return transformationCall;
    } catch (JsonProcessingException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }
}
Also used : IntStream(java.util.stream.IntStream) HttpPost(org.apache.http.client.methods.HttpPost) GenericCommand(org.talend.dataprep.command.GenericCommand) TDPException(org.talend.dataprep.exception.TDPException) PreviewParameters(org.talend.dataprep.transformation.preview.api.PreviewParameters) SCOPE_PROTOTYPE(org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE) Scope(org.springframework.context.annotation.Scope) UNABLE_TO_READ_PREPARATION(org.talend.dataprep.exception.error.PreparationErrorCodes.UNABLE_TO_READ_PREPARATION) ArrayList(java.util.ArrayList) ChainedCommand(org.talend.dataprep.api.service.command.common.ChainedCommand) Action(org.talend.dataprep.api.preparation.Action) TypeReference(com.fasterxml.jackson.core.type.TypeReference) APPLICATION_JSON(org.apache.http.entity.ContentType.APPLICATION_JSON) HEAD(org.talend.dataprep.api.export.ExportParameters.SourceType.HEAD) Defaults.pipeStream(org.talend.dataprep.command.Defaults.pipeStream) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) StringEntity(org.apache.http.entity.StringEntity) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) HttpStatus(org.springframework.http.HttpStatus) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) Component(org.springframework.stereotype.Component) PreparationGetActions(org.talend.dataprep.command.preparation.PreparationGetActions) CommonErrorCodes(org.talend.dataprep.exception.error.CommonErrorCodes) ExceptionContext.withBuilder(org.talend.daikon.exception.ExceptionContext.withBuilder) InputStream(java.io.InputStream) HttpPost(org.apache.http.client.methods.HttpPost) Action(org.talend.dataprep.api.preparation.Action) IOException(java.io.IOException) TDPException(org.talend.dataprep.exception.TDPException) PreviewParameters(org.talend.dataprep.transformation.preview.api.PreviewParameters) StringEntity(org.apache.http.entity.StringEntity) ArrayList(java.util.ArrayList) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

List (java.util.List)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 Serializable (java.io.Serializable)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 HTTP_INTERNAL_ERROR (java.net.HttpURLConnection.HTTP_INTERNAL_ERROR)1 UTF_8 (java.nio.charset.StandardCharsets.UTF_8)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 Objects (java.util.Objects)1 Optional (java.util.Optional)1 UUID (java.util.UUID)1 Function (java.util.function.Function)1 Pattern (java.util.regex.Pattern)1 Collectors.toList (java.util.stream.Collectors.toList)1