Prefix function names with spring-

* Add `spring-` prefix to function names

Fixes: #9

This commit renames each sub-module in the common, consumer, function
and supplier groups with a prefix of `spring-`.

* Update README.adoc links to new prefixed names
This commit is contained in:
Chris Bono
2024-01-02 13:07:00 -06:00
committed by GitHub
parent b9a3e59074
commit 84e732da08
596 changed files with 146 additions and 147 deletions

View File

@@ -0,0 +1,127 @@
/*
* Copyright 2018-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.fn.http.request;
import java.time.Duration;
import java.util.Map;
import java.util.function.Function;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.integration.config.IntegrationConverter;
import org.springframework.messaging.Message;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.DefaultUriBuilderFactory;
import org.springframework.web.util.UriBuilderFactory;
/**
* Configuration for a {@link Function} that makes HTTP requests to a resource and for
* each request, returns a {@link ResponseEntity}.
*
* @author David Turanski
* @author Sunny Hemdev
* @author Corneil du Plessis
**/
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(HttpRequestFunctionProperties.class)
public class HttpRequestFunctionConfiguration {
@Bean
public HttpRequestFunction httpRequestFunction(WebClient.Builder webClientBuilder, HttpRequestFunctionProperties properties) {
return new HttpRequestFunction(webClientBuilder.build(), properties);
}
@Bean
@IntegrationConverter
public Converter<String, HttpMethod> httpMethodConverter() {
return new HttpMethodConverter();
}
/**
* Function that accepts a {@code Flux<Message<?>>} containing body and headers and
* returns a {@code Flux<ResponseEntity<?>>}.
*/
public static class HttpRequestFunction implements Function<Message<?>, Object> {
private final WebClient webClient;
private final UriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory();
private final HttpRequestFunctionProperties properties;
public HttpRequestFunction(WebClient webClient, HttpRequestFunctionProperties properties) {
this.webClient = webClient;
this.properties = properties;
}
@Override
public Object apply(Message<?> message) {
return this.webClient
.method(resolveHttpMethod(message))
.uri(uriBuilderFactory.uriString(resolveUrl(message)).build())
.bodyValue(resolveBody(message))
.headers(httpHeaders -> httpHeaders.addAll(resolveHeaders(message)))
.retrieve()
.toEntity(properties.getExpectedResponseType())
.map(responseEntity -> properties.getReplyExpression().getValue(responseEntity))
.timeout(Duration.ofMillis(properties.getTimeout()))
.block();
}
private String resolveUrl(Message<?> message) {
return properties.getUrlExpression().getValue(message, String.class);
}
private HttpMethod resolveHttpMethod(Message<?> message) {
return properties.getHttpMethodExpression().getValue(message, HttpMethod.class);
}
private Object resolveBody(Message<?> message) {
return properties.getBodyExpression() != null ? properties.getBodyExpression().getValue(message)
: message.getPayload();
}
private HttpHeaders resolveHeaders(Message<?> message) {
HttpHeaders headers = new HttpHeaders();
if (properties.getHeadersExpression() != null) {
Map<?, ?> headersMap = properties.getHeadersExpression().getValue(message, Map.class);
for (Map.Entry<?, ?> header : headersMap.entrySet()) {
if (header.getKey() != null && header.getValue() != null) {
headers.add(header.getKey().toString(),
header.getValue().toString());
}
}
}
return headers;
}
}
public static class HttpMethodConverter implements Converter<String, HttpMethod> {
@Override
public HttpMethod convert(String source) {
return HttpMethod.valueOf(source);
}
}
}

View File

@@ -0,0 +1,140 @@
/*
* Copyright 2015-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.fn.http.request;
import jakarta.validation.constraints.NotNull;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.expression.Expression;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.integration.expression.FunctionExpression;
import org.springframework.integration.expression.ValueExpression;
import org.springframework.validation.annotation.Validated;
/**
* Configuration properties for the Http Client Processor module.
*
* @author Waldemar Hummer
* @author Mark Fisher
* @author Christian Tzolov
* @author Artem Bilan
* @author David Turanski
* @author Sunny Hemdev
*/
@Validated
@ConfigurationProperties("http.request")
public class HttpRequestFunctionProperties {
private static final Class<?> DEFAULT_RESPONSE_TYPE = String.class;
/**
* The type used to interpret the response.
*/
private Class<?> expectedResponseType = DEFAULT_RESPONSE_TYPE;
/**
* Request timeout in milliseconds.
*/
private long timeout = 30_000;
/**
* A SpEL expression against incoming message to determine the URL to use.
*/
private Expression urlExpression;
/**
* A SpEL expression to derive the request method from the incoming message.
*/
private Expression httpMethodExpression = new ValueExpression(HttpMethod.GET);
/**
* A SpEL expression to derive the request body from the incoming message.
*/
private Expression bodyExpression;
/**
* A SpEL expression used to derive the http headers map to use.
*/
private Expression headersExpression;
/**
* A SpEL expression used to compute the final result, applied against the whole http
* {@link org.springframework.http.ResponseEntity}.
*/
private Expression replyExpression = new FunctionExpression<ResponseEntity>(ResponseEntity::getBody);
@NotNull
public Expression getUrlExpression() {
return urlExpression;
}
public void setUrlExpression(Expression urlExpression) {
this.urlExpression = urlExpression;
}
public Expression getHttpMethodExpression() {
return httpMethodExpression;
}
public void setHttpMethodExpression(Expression httpMethodExpression) {
this.httpMethodExpression = httpMethodExpression;
}
@NotNull
public Class<?> getExpectedResponseType() {
return expectedResponseType;
}
public void setExpectedResponseType(Class<?> expectedResponseType) {
this.expectedResponseType = expectedResponseType;
}
public long getTimeout() {
return this.timeout;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
public Expression getBodyExpression() {
return bodyExpression;
}
public void setBodyExpression(Expression bodyExpression) {
this.bodyExpression = bodyExpression;
}
public Expression getHeadersExpression() {
return headersExpression;
}
public void setHeadersExpression(Expression headersExpression) {
this.headersExpression = headersExpression;
}
@NotNull
public Expression getReplyExpression() {
return replyExpression;
}
public void setReplyExpression(Expression replyExpression) {
this.replyExpression = replyExpression;
}
}

View File

@@ -0,0 +1,262 @@
/*
* Copyright 2020-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.fn.http.request;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.cloud.fn.http.request.HttpRequestFunctionConfiguration.HttpRequestFunction;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.messaging.support.MessageBuilder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
public class HttpRequestFunctionTestApplicationTests {
private MockWebServer server = new MockWebServer();
private ApplicationContextRunner runner;
@BeforeEach
void setup() {
this.runner = new ApplicationContextRunner()
.withUserConfiguration(HttpRequestFunctionTestApplication.class)
.withPropertyValues(
"http.request.reply-expression=#root",
"http.request.url-expression='" + url() + "'");
}
@Test
void shouldReturnString() {
server.enqueue(new MockResponse()
.setResponseCode(HttpStatus.OK.value())
.setBody("hello"));
runner.withPropertyValues("http.request.http-method-expression='POST'").run(context -> {
HttpRequestFunction httpRequestFunction = context.getBean(HttpRequestFunction.class);
Message<?> message = MessageBuilder.withPayload("").build();
ResponseEntity r = (ResponseEntity) httpRequestFunction.apply(message);
assertThat(r.getBody()).isEqualTo("hello");
assertThat(r.getStatusCode().is2xxSuccessful()).isTrue();
});
}
@Test
void shouldPostJson() {
server.setDispatcher(new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest recordedRequest) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE,
recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
.setBody(recordedRequest.getBody())
.setResponseCode(HttpStatus.CREATED.value());
}
});
runner.withPropertyValues("http.request.http-method-expression='POST'",
"http.request.headers-expression={'Content-Type':'application/json'}").run(context -> {
HttpRequestFunction httpRequestFunction = context.getBean(HttpRequestFunction.class);
String json = "{\"hello\":\"world\"}";
Message<?> message = MessageBuilder.withPayload(json)
.build();
ResponseEntity r = (ResponseEntity) httpRequestFunction.apply(message);
assertThat(r.getBody()).isEqualTo(json);
assertThat(r.getStatusCode().is2xxSuccessful()).isTrue();
assertThat(r.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
RecordedRequest request = server.takeRequest(100, TimeUnit.MILLISECONDS);
assertThat(request.getMethod()).isEqualTo("POST");
});
}
@Test
void shouldPostPojoAsJson() {
server.setDispatcher(new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest recordedRequest) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE,
recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
.setBody(recordedRequest.getBody())
.setResponseCode(HttpStatus.CREATED.value());
}
});
runner.withPropertyValues("http.request.http-method-expression='POST'",
"http.request.expected-response-type=" + Map.class.getName()).run(context -> {
HttpRequestFunction httpRequestFunction = context.getBean(HttpRequestFunction.class);
Map<String, String> json = Collections.singletonMap("hello", "world");
Message<?> message = MessageBuilder.withPayload(json)
.build();
ResponseEntity r = (ResponseEntity) httpRequestFunction.apply(message);
assertThat(r.getBody()).isEqualTo(json);
assertThat(r.getStatusCode().is2xxSuccessful()).isTrue();
assertThat(r.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
RecordedRequest request = server.takeRequest(100, TimeUnit.MILLISECONDS);
assertThat(request.getMethod()).isEqualTo("POST");
});
}
@Test
void shouldDelete() {
server.setDispatcher(new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest recordedRequest) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE,
recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
.setBody(recordedRequest.getBody())
.setResponseCode(HttpStatus.ACCEPTED.value());
}
});
runner.withPropertyValues("http.request.http-method-expression='DELETE'",
"http.request.expected-response-type=" + Void.class.getName()).run(context -> {
HttpRequestFunction httpRequestFunction = context.getBean(HttpRequestFunction.class);
Message<?> message = MessageBuilder.withPayload("")
.build();
ResponseEntity r = (ResponseEntity) httpRequestFunction.apply(message);
assertThat(r.getBody()).isNull();
assertThat(r.getStatusCode().is2xxSuccessful()).isTrue();
RecordedRequest request = server.takeRequest(100, TimeUnit.MILLISECONDS);
assertThat(request.getMethod()).isEqualTo("DELETE");
});
}
@Test
void shouldThrowErrorIfCannotConnect() throws IOException {
server.shutdown();
runner.run(context -> {
HttpRequestFunction httpRequestFunction = context.getBean(HttpRequestFunction.class);
try {
httpRequestFunction.apply(new GenericMessage(""));
fail("Expected exception");
}
catch (Throwable throwable) {
assertThat(throwable.getMessage()).contains("Connection refused");
}
});
}
@Test
void requestUsingExpressions() {
server.setDispatcher(new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest recordedRequest) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE,
recordedRequest.getHeader(HttpHeaders.ACCEPT))
.setBody(recordedRequest.getBody())
.setResponseCode(HttpStatus.OK.value());
}
});
runner.withPropertyValues(
"http.request.url-expression=headers['url']",
"http.request.http-method-expression=headers['method']",
"http.request.body-expression=headers['body']",
"http.request.headers-expression={Accept:'application/json'}")
.run(context -> {
Message<?> message = MessageBuilder.withPayload("")
.setHeader("url", url())
.setHeader("method", "POST")
.setHeader("body", "{\"hello\":\"world\"}")
.build();
HttpRequestFunction httpRequestFunction = context.getBean(HttpRequestFunction.class);
ResponseEntity responseEntity = (ResponseEntity) httpRequestFunction.apply(message);
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(responseEntity.getBody()).isEqualTo(message.getHeaders().get("body"));
assertThat(responseEntity.getHeaders().getContentType())
.isEqualTo(MediaType.APPLICATION_JSON);
});
}
@Test
void requestUsingReturnType() {
server.setDispatcher(new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest recordedRequest) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE,
recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
.setBody(recordedRequest.getBody())
.setResponseCode(HttpStatus.OK.value());
}
});
runner.withPropertyValues(
"http.request..http-method-expression='POST'",
"http.request.headers-expression={'Content-Type':'application/octet-stream'}",
"http.request.expected-response-type=byte[]")
.run(context -> {
Message<?> message = MessageBuilder.withPayload("hello")
.build();
HttpRequestFunction httpRequestFunction = context.getBean(HttpRequestFunction.class);
ResponseEntity responseEntity = (ResponseEntity) httpRequestFunction.apply(message);
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(responseEntity.getBody()).isEqualTo("hello".getBytes());
assertThat(responseEntity.getHeaders().getContentType())
.isEqualTo(MediaType.APPLICATION_OCTET_STREAM);
});
}
@Test
void requestUsingJsonPathMethodExpression() {
server.setDispatcher(new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest recordedRequest) {
return new MockResponse()
.setBody(recordedRequest.getBody())
.setHeader("method", recordedRequest.getMethod())
.setResponseCode(HttpStatus.OK.value());
}
});
runner.withPropertyValues(
"http.request.http-method-expression=#jsonPath(payload,'$.myMethod')")
.run(context -> {
Message<?> message = MessageBuilder
.withPayload("{\"name\":\"Fred\",\"age\":41, \"myMethod\":\"POST\"}")
.build();
HttpRequestFunction httpRequestFunction = context.getBean(HttpRequestFunction.class);
ResponseEntity responseEntity = (ResponseEntity) httpRequestFunction.apply(message);
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(responseEntity.getBody()).isEqualTo(message.getPayload());
});
}
private String url() {
return String.format("http://localhost:%d", server.getPort());
}
@SpringBootApplication
static class HttpRequestFunctionTestApplication {
}
}