Search in sources :

Example 26 with HttpStatus

use of org.springframework.http.HttpStatus in project spring-integration by spring-projects.

the class WebFluxRequestExecutingMessageHandler method exchange.

@Override
protected Object exchange(Supplier<URI> uriSupplier, HttpMethod httpMethod, HttpEntity<?> httpRequest, Object expectedResponseType, Message<?> requestMessage) {
    WebClient.RequestBodySpec requestSpec = this.webClient.method(httpMethod).uri(b -> uriSupplier.get()).headers(headers -> headers.putAll(httpRequest.getHeaders()));
    if (httpRequest.hasBody()) {
        requestSpec.body(BodyInserters.fromObject(httpRequest.getBody()));
    }
    Mono<ClientResponse> responseMono = requestSpec.exchange().flatMap(response -> {
        HttpStatus httpStatus = response.statusCode();
        if (httpStatus.isError()) {
            return response.body(BodyExtractors.toDataBuffers()).reduce(DataBuffer::write).map(dataBuffer -> {
                byte[] bytes = new byte[dataBuffer.readableByteCount()];
                dataBuffer.read(bytes);
                DataBufferUtils.release(dataBuffer);
                return bytes;
            }).defaultIfEmpty(new byte[0]).map(bodyBytes -> {
                throw new WebClientResponseException("ClientResponse has erroneous status code: " + httpStatus.value() + " " + httpStatus.getReasonPhrase(), httpStatus.value(), httpStatus.getReasonPhrase(), response.headers().asHttpHeaders(), bodyBytes, response.headers().contentType().map(MimeType::getCharset).orElse(StandardCharsets.ISO_8859_1));
            });
        } else {
            return Mono.just(response);
        }
    });
    if (isExpectReply()) {
        return responseMono.flatMap(response -> {
            ResponseEntity.BodyBuilder httpEntityBuilder = ResponseEntity.status(response.statusCode()).headers(response.headers().asHttpHeaders());
            Mono<?> bodyMono;
            if (expectedResponseType != null) {
                if (this.replyPayloadToFlux) {
                    BodyExtractor<? extends Flux<?>, ReactiveHttpInputMessage> extractor;
                    if (expectedResponseType instanceof ParameterizedTypeReference<?>) {
                        extractor = BodyExtractors.toFlux((ParameterizedTypeReference<?>) expectedResponseType);
                    } else {
                        extractor = BodyExtractors.toFlux((Class<?>) expectedResponseType);
                    }
                    Flux<?> flux = response.body(extractor);
                    bodyMono = Mono.just(flux);
                } else {
                    BodyExtractor<? extends Mono<?>, ReactiveHttpInputMessage> extractor;
                    if (expectedResponseType instanceof ParameterizedTypeReference<?>) {
                        extractor = BodyExtractors.toMono((ParameterizedTypeReference<?>) expectedResponseType);
                    } else {
                        extractor = BodyExtractors.toMono((Class<?>) expectedResponseType);
                    }
                    bodyMono = response.body(extractor);
                }
            } else if (this.bodyExtractor != null) {
                Object body = response.body(this.bodyExtractor);
                if (body instanceof Mono) {
                    bodyMono = (Mono<?>) body;
                } else {
                    bodyMono = Mono.just(body);
                }
            } else {
                bodyMono = Mono.empty();
            }
            return bodyMono.map(httpEntityBuilder::body).defaultIfEmpty(httpEntityBuilder.build());
        }).map(this::getReply);
    } else {
        responseMono.subscribe(v -> {
        }, ex -> sendErrorMessage(requestMessage, ex));
        return null;
    }
}
Also used : ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) LiteralExpression(org.springframework.expression.common.LiteralExpression) WebClient(org.springframework.web.reactive.function.client.WebClient) Supplier(java.util.function.Supplier) ClientHttpResponse(org.springframework.http.client.reactive.ClientHttpResponse) MimeType(org.springframework.util.MimeType) ValueExpression(org.springframework.integration.expression.ValueExpression) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Message(org.springframework.messaging.Message) URI(java.net.URI) ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) HttpMethod(org.springframework.http.HttpMethod) Mono(reactor.core.publisher.Mono) AbstractHttpRequestExecutingMessageHandler(org.springframework.integration.http.outbound.AbstractHttpRequestExecutingMessageHandler) BodyExtractor(org.springframework.web.reactive.function.BodyExtractor) DataBuffer(org.springframework.core.io.buffer.DataBuffer) StandardCharsets(java.nio.charset.StandardCharsets) HttpStatus(org.springframework.http.HttpStatus) Flux(reactor.core.publisher.Flux) HttpEntity(org.springframework.http.HttpEntity) BodyExtractors(org.springframework.web.reactive.function.BodyExtractors) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) MessageHandler(org.springframework.messaging.MessageHandler) BeanFactory(org.springframework.beans.factory.BeanFactory) Expression(org.springframework.expression.Expression) ResponseEntity(org.springframework.http.ResponseEntity) BodyInserters(org.springframework.web.reactive.function.BodyInserters) WebClientResponseException(org.springframework.web.reactive.function.client.WebClientResponseException) Assert(org.springframework.util.Assert) ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) HttpStatus(org.springframework.http.HttpStatus) Mono(reactor.core.publisher.Mono) Flux(reactor.core.publisher.Flux) WebClient(org.springframework.web.reactive.function.client.WebClient) MimeType(org.springframework.util.MimeType) WebClientResponseException(org.springframework.web.reactive.function.client.WebClientResponseException) BodyExtractor(org.springframework.web.reactive.function.BodyExtractor)

Example 27 with HttpStatus

use of org.springframework.http.HttpStatus in project spring-cloud-function by spring-cloud.

the class MessageController method function.

@PostMapping("/**")
public ResponseEntity<Object> function(@RequestAttribute("org.springframework.web.servlet.HandlerMapping.pathWithinHandlerMapping") String path, @RequestBody Object body, @RequestHeader HttpHeaders headers) {
    Route route = input(path);
    String channel = route.getChannel();
    if (!inputs.containsKey(channel)) {
        return ResponseEntity.notFound().build();
    }
    Collection<Object> collection;
    boolean single = false;
    if (body instanceof String) {
        body = extract((String) body);
    }
    if (body instanceof Collection) {
        @SuppressWarnings("unchecked") Collection<Object> list = (Collection<Object>) body;
        collection = list;
    } else {
        if (ObjectUtils.isArray(body)) {
            collection = Arrays.asList(ObjectUtils.toObjectArray(body));
        } else {
            single = true;
            collection = Arrays.asList(body);
        }
    }
    Map<String, Object> messageHeaders = new HashMap<>(HeaderUtils.fromHttp(headers));
    if (route.getKey() != null) {
        messageHeaders.put(ROUTE_KEY, route.getKey());
    }
    MessageChannel input = inputs.get(channel);
    Map<String, Object> outputHeaders = null;
    List<Object> results = new ArrayList<>();
    HttpStatus status = HttpStatus.ACCEPTED;
    // one of them.
    if (this.outputs.containsKey(channel)) {
        for (Object payload : collection) {
            Message<?> result = template.sendAndReceive(input, MessageBuilder.withPayload(payload).copyHeadersIfAbsent(messageHeaders).setHeader(MessageHeaders.REPLY_CHANNEL, outputs.get(channel)).build());
            if (result != null) {
                if (outputHeaders == null) {
                    outputHeaders = new LinkedHashMap<>(result.getHeaders());
                }
                results.add(result.getPayload());
            }
        }
        status = HttpStatus.OK;
        if (results.isEmpty()) {
            // If nothing came back, just assume it was intentional, and say that
            // we accepted the inputs.
            status = HttpStatus.ACCEPTED;
            results.addAll(collection);
        }
    } else {
        for (Object payload : collection) {
            template.send(input, MessageBuilder.withPayload(payload).copyHeadersIfAbsent(messageHeaders).build());
        }
        outputHeaders = messageHeaders;
        results.addAll(collection);
    }
    if (outputHeaders == null) {
        outputHeaders = new LinkedHashMap<>();
    }
    outputHeaders.put(ROUTE_KEY, route.getKey());
    if (single && results.size() == 1) {
        body = results.get(0);
    } else {
        body = results;
    }
    if (headers.getContentType() != null && headers.getContentType().includes(MediaType.APPLICATION_JSON) && body.toString().contains("\"")) {
        body = body.toString();
    }
    return convert(status, MessageBuilder.withPayload(body).copyHeadersIfAbsent(outputHeaders).build(), headers);
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HttpStatus(org.springframework.http.HttpStatus) ArrayList(java.util.ArrayList) MessageChannel(org.springframework.messaging.MessageChannel) Collection(java.util.Collection) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 28 with HttpStatus

use of org.springframework.http.HttpStatus in project spring-cloud-gateway by spring-cloud.

the class ServerWebExchangeUtils method parse.

public static HttpStatus parse(String statusString) {
    HttpStatus httpStatus;
    try {
        int status = Integer.parseInt(statusString);
        httpStatus = HttpStatus.valueOf(status);
    } catch (NumberFormatException e) {
        // try the enum string
        httpStatus = HttpStatus.valueOf(statusString.toUpperCase());
    }
    return httpStatus;
}
Also used : HttpStatus(org.springframework.http.HttpStatus)

Example 29 with HttpStatus

use of org.springframework.http.HttpStatus in project thingsboard by thingsboard.

the class HttpSessionCtx method reply.

private void reply(RuleEngineErrorMsg msg) {
    HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
    switch(msg.getError()) {
        case PLUGIN_TIMEOUT:
            status = HttpStatus.REQUEST_TIMEOUT;
            break;
        default:
            if (msg.getInMsgType() == MsgType.TO_SERVER_RPC_REQUEST) {
                status = HttpStatus.BAD_REQUEST;
            }
            break;
    }
    responseWriter.setResult(new ResponseEntity<>(JsonConverter.toErrorJson(msg.getErrorMsg()).toString(), status));
}
Also used : HttpStatus(org.springframework.http.HttpStatus)

Example 30 with HttpStatus

use of org.springframework.http.HttpStatus in project thingsboard by thingsboard.

the class AuthController method checkResetToken.

@RequestMapping(value = "/noauth/resetPassword", params = { "resetToken" }, method = RequestMethod.GET)
public ResponseEntity<String> checkResetToken(@RequestParam(value = "resetToken") String resetToken) {
    HttpHeaders headers = new HttpHeaders();
    HttpStatus responseStatus;
    String resetURI = "/login/resetPassword";
    UserCredentials userCredentials = userService.findUserCredentialsByResetToken(resetToken);
    if (userCredentials != null) {
        try {
            URI location = new URI(resetURI + "?resetToken=" + resetToken);
            headers.setLocation(location);
            responseStatus = HttpStatus.SEE_OTHER;
        } catch (URISyntaxException e) {
            log.error("Unable to create URI with address [{}]", resetURI);
            responseStatus = HttpStatus.BAD_REQUEST;
        }
    } else {
        responseStatus = HttpStatus.CONFLICT;
    }
    return new ResponseEntity<>(headers, responseStatus);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) HttpStatus(org.springframework.http.HttpStatus) UserCredentials(org.thingsboard.server.common.data.security.UserCredentials) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Aggregations

HttpStatus (org.springframework.http.HttpStatus)161 ResponseEntity (org.springframework.http.ResponseEntity)39 HttpHeaders (org.springframework.http.HttpHeaders)35 Test (org.junit.jupiter.api.Test)26 MediaType (org.springframework.http.MediaType)17 Mono (reactor.core.publisher.Mono)17 IOException (java.io.IOException)16 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)14 Collections (java.util.Collections)13 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)13 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)13 URI (java.net.URI)12 List (java.util.List)11 Optional (java.util.Optional)11 Test (org.junit.Test)11 Map (java.util.Map)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 ClassPathResource (org.springframework.core.io.ClassPathResource)9 Resource (org.springframework.core.io.Resource)9 HashMap (java.util.HashMap)8