You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@streampipes.apache.org by ze...@apache.org on 2026/08/13 16:04:50 UTC
(streampipes) branch dev updated: feat(client): support external HTTP requests (#4825)
This is an automated email from the ASF dual-hosted git repository.
tenthe pushed a commit to branch dev
in repository https://gitbox.apache.org/repos/asf/streampipes.git
The following commit(s) were added to refs/heads/dev by this push:
new eb2f090e35 feat(client): support external HTTP requests (#4825)
eb2f090e35 is described below
commit eb2f090e35f43ef9e27cfad8d1c28b22af8933eb
Author: Philipp Zehnder <te...@users.noreply.github.com>
AuthorDate: Thu Aug 13 18:04:43 2026 +0200
feat(client): support external HTTP requests (#4825)
---
streampipes-client-api/pom.xml | 6 +
.../client/api/IExternalRequestApi.java | 77 +++++
.../streampipes/client/api/IStreamPipesClient.java | 9 +
.../client/api/external/ExternalRequest.java | 215 ++++++++++++
.../client/api/external/ExternalRequestConfig.java | 99 ++++++
.../api/external/ExternalRequestException.java | 38 +++
.../client/api/external/ExternalRequestMethod.java | 26 ++
.../client/api/external/ExternalRequestTest.java | 134 ++++++++
streampipes-client/pom.xml | 4 +
.../streampipes/client/StreamPipesClient.java | 13 +
.../streampipes/client/api/ExternalRequestApi.java | 372 +++++++++++++++++++++
.../client/api/ExternalRequestApiTest.java | 232 +++++++++++++
12 files changed, 1225 insertions(+)
diff --git a/streampipes-client-api/pom.xml b/streampipes-client-api/pom.xml
index 46b80145d7..4caf251887 100644
--- a/streampipes-client-api/pom.xml
+++ b/streampipes-client-api/pom.xml
@@ -48,6 +48,12 @@
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
+
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
</project>
diff --git a/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/IExternalRequestApi.java b/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/IExternalRequestApi.java
new file mode 100644
index 0000000000..7ef51c0990
--- /dev/null
+++ b/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/IExternalRequestApi.java
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://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.apache.streampipes.client.api;
+
+import org.apache.streampipes.client.api.external.ExternalRequest;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Executes JSON requests against absolute external HTTP endpoints.
+ *
+ * <p>This API deliberately does not apply StreamPipes credentials or custom headers. Consumers that accept
+ * untrusted target URIs must enforce an appropriate endpoint allow list before calling this API.
+ */
+public interface IExternalRequestApi {
+
+ <T> void sendPost(String url, Map<String, String> headers, T payload);
+
+ <T> T sendPost(String url, Map<String, String> headers, Object payload, Class<T> responseClass);
+
+ default Map<String, Object> sendPostJson(String url, Object payload) {
+ return sendPostJson(url, Map.of(), payload);
+ }
+
+ Map<String, Object> sendPostJson(String url, Map<String, String> headers, Object payload);
+
+ <T> T sendGet(String url,
+ Map<String, String> headers,
+ Map<String, String> queryParameters,
+ Class<T> responseClass);
+
+ default Map<String, Object> sendGetJson(String url) {
+ return sendGetJson(url, Map.of(), Map.of());
+ }
+
+ Map<String, Object> sendGetJson(String url,
+ Map<String, String> headers,
+ Map<String, String> queryParameters);
+
+ <T> void sendPut(String url, Map<String, String> headers, T payload);
+
+ <T> T sendPut(String url, Map<String, String> headers, Object payload, Class<T> responseClass);
+
+ Map<String, Object> sendPutJson(String url, Map<String, String> headers, Object payload);
+
+ void sendDelete(String url, Map<String, String> headers);
+
+ Map<String, Object> sendDeleteJson(String url, Map<String, String> headers);
+
+ <T> List<T> getList(String url,
+ Map<String, String> headers,
+ Map<String, String> queryParameters,
+ Class<T> responseClass);
+
+ <T> T execute(ExternalRequest request, Class<T> responseClass);
+
+ Object executeJson(ExternalRequest request);
+
+ <T> List<T> getList(ExternalRequest request, Class<T> responseClass);
+}
diff --git a/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/IStreamPipesClient.java b/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/IStreamPipesClient.java
index 80a689778b..de66f56660 100644
--- a/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/IStreamPipesClient.java
+++ b/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/IStreamPipesClient.java
@@ -21,6 +21,7 @@ package org.apache.streampipes.client.api;
import org.apache.streampipes.client.api.config.ClientConnectionUrlResolver;
import org.apache.streampipes.client.api.config.IStreamPipesClientConfig;
import org.apache.streampipes.client.api.credentials.CredentialsProvider;
+import org.apache.streampipes.client.api.external.ExternalRequestConfig;
import org.apache.streampipes.messaging.SpProtocolDefinitionFactory;
import org.apache.streampipes.model.mail.SpEmail;
@@ -50,6 +51,14 @@ public interface IStreamPipesClient extends Serializable {
ICustomRequestApi customRequest();
+ default IExternalRequestApi externalRequest() {
+ return externalRequest(ExternalRequestConfig.defaults());
+ }
+
+ default IExternalRequestApi externalRequest(ExternalRequestConfig config) {
+ throw new UnsupportedOperationException("External requests are not supported by this client implementation");
+ }
+
IAdminApi adminApi();
IDataLakeMeasureApi dataLakeMeasureApi();
diff --git a/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/external/ExternalRequest.java b/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/external/ExternalRequest.java
new file mode 100644
index 0000000000..68aa779821
--- /dev/null
+++ b/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/external/ExternalRequest.java
@@ -0,0 +1,215 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://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.apache.streampipes.client.api.external;
+
+import java.net.URI;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+public final class ExternalRequest {
+
+ private static final Set<String> RESTRICTED_HEADERS = Set.of(
+ "connection", "content-length", "host", "transfer-encoding", "upgrade"
+ );
+
+ private final ExternalRequestMethod method;
+ private final URI uri;
+ private final Map<String, String> headers;
+ private final Map<String, String> queryParameters;
+ private final Object payload;
+ private final Integer connectTimeoutMillis;
+ private final Integer responseTimeoutMillis;
+ private final Long maxResponseBytes;
+
+ private ExternalRequest(Builder builder) {
+ this.method = Objects.requireNonNull(builder.method, "method must not be null");
+ this.uri = validateUri(builder.uri);
+ this.headers = Map.copyOf(builder.headers);
+ validateHeaders(headers);
+ this.queryParameters = Map.copyOf(builder.queryParameters);
+ this.payload = builder.payload;
+ validatePayload();
+ this.connectTimeoutMillis = builder.connectTimeoutMillis;
+ this.responseTimeoutMillis = builder.responseTimeoutMillis;
+ this.maxResponseBytes = builder.maxResponseBytes;
+ validateOverrides();
+ }
+
+ public static Builder builder(ExternalRequestMethod method, URI uri) {
+ return new Builder(method, uri);
+ }
+
+ public ExternalRequestMethod getMethod() {
+ return method;
+ }
+
+ public URI getUri() {
+ return uri;
+ }
+
+ public Map<String, String> getHeaders() {
+ return headers;
+ }
+
+ public Map<String, String> getQueryParameters() {
+ return queryParameters;
+ }
+
+ public Object getPayload() {
+ return payload;
+ }
+
+ public Integer getConnectTimeoutMillis() {
+ return connectTimeoutMillis;
+ }
+
+ public Integer getResponseTimeoutMillis() {
+ return responseTimeoutMillis;
+ }
+
+ public Long getMaxResponseBytes() {
+ return maxResponseBytes;
+ }
+
+ private static URI validateUri(URI uri) {
+ Objects.requireNonNull(uri, "uri must not be null");
+ if (!uri.isAbsolute() || uri.getHost() == null
+ || !("http".equalsIgnoreCase(uri.getScheme()) || "https".equalsIgnoreCase(uri.getScheme()))
+ || uri.getUserInfo() != null || uri.getFragment() != null) {
+ throw new IllegalArgumentException("uri must be an absolute HTTP(S) URI without user info or a fragment");
+ }
+ return uri;
+ }
+
+ private static void validateHeaders(Map<String, String> headers) {
+ headers.forEach((name, value) -> {
+ if (name == null || name.isBlank() || value == null) {
+ throw new IllegalArgumentException("header names and values must not be null or blank");
+ }
+ if (!isHeaderName(name) || containsControlCharacter(value)) {
+ throw new IllegalArgumentException("headers must not contain control characters");
+ }
+ if (RESTRICTED_HEADERS.stream().anyMatch(restrictedHeader -> restrictedHeader.equalsIgnoreCase(name))) {
+ throw new IllegalArgumentException("header '" + name + "' is controlled by the HTTP client");
+ }
+ });
+ }
+
+ private static boolean isHeaderName(String name) {
+ for (int index = 0; index < name.length(); index++) {
+ char character = name.charAt(index);
+ if (!((character >= '0' && character <= '9')
+ || (character >= 'A' && character <= 'Z')
+ || (character >= 'a' && character <= 'z')
+ || "!#$%&'*+-.^_`|~".indexOf(character) >= 0)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static boolean containsControlCharacter(String value) {
+ return value.chars().anyMatch(character -> character <= 31 || character == 127);
+ }
+
+ private void validatePayload() {
+ boolean supportsPayload = method == ExternalRequestMethod.POST || method == ExternalRequestMethod.PUT;
+ if (supportsPayload && payload == null) {
+ throw new IllegalArgumentException(method + " requests require a JSON payload");
+ }
+ if (!supportsPayload && payload != null) {
+ throw new IllegalArgumentException(method + " requests must not contain a payload");
+ }
+ }
+
+ private void validateOverrides() {
+ validatePositive(connectTimeoutMillis, "connectTimeoutMillis");
+ validatePositive(responseTimeoutMillis, "responseTimeoutMillis");
+ validatePositive(maxResponseBytes, "maxResponseBytes");
+ }
+
+ private static void validatePositive(Number value, String name) {
+ if (value != null && value.longValue() <= 0) {
+ throw new IllegalArgumentException(name + " must be greater than zero");
+ }
+ }
+
+ public static final class Builder {
+
+ private final ExternalRequestMethod method;
+ private final URI uri;
+ private final Map<String, String> headers = new LinkedHashMap<>();
+ private final Map<String, String> queryParameters = new LinkedHashMap<>();
+ private Object payload;
+ private Integer connectTimeoutMillis;
+ private Integer responseTimeoutMillis;
+ private Long maxResponseBytes;
+
+ private Builder(ExternalRequestMethod method, URI uri) {
+ this.method = method;
+ this.uri = uri;
+ }
+
+ public Builder header(String name, String value) {
+ headers.put(name, value);
+ return this;
+ }
+
+ public Builder headers(Map<String, String> headers) {
+ this.headers.putAll(headers);
+ return this;
+ }
+
+ public Builder queryParameter(String name, String value) {
+ queryParameters.put(name, value);
+ return this;
+ }
+
+ public Builder queryParameters(Map<String, String> queryParameters) {
+ this.queryParameters.putAll(queryParameters);
+ return this;
+ }
+
+ public Builder payload(Object payload) {
+ this.payload = payload;
+ return this;
+ }
+
+ public Builder connectTimeoutMillis(int connectTimeoutMillis) {
+ this.connectTimeoutMillis = connectTimeoutMillis;
+ return this;
+ }
+
+ public Builder responseTimeoutMillis(int responseTimeoutMillis) {
+ this.responseTimeoutMillis = responseTimeoutMillis;
+ return this;
+ }
+
+ public Builder maxResponseBytes(long maxResponseBytes) {
+ this.maxResponseBytes = maxResponseBytes;
+ return this;
+ }
+
+ public ExternalRequest build() {
+ return new ExternalRequest(this);
+ }
+ }
+}
diff --git a/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/external/ExternalRequestConfig.java b/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/external/ExternalRequestConfig.java
new file mode 100644
index 0000000000..ac17fc9cf6
--- /dev/null
+++ b/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/external/ExternalRequestConfig.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://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.apache.streampipes.client.api.external;
+
+public final class ExternalRequestConfig {
+
+ private static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 10_000;
+ private static final int DEFAULT_RESPONSE_TIMEOUT_MILLIS = 30_000;
+ private static final long DEFAULT_MAX_RESPONSE_BYTES = 10L * 1024 * 1024;
+
+ private final int connectTimeoutMillis;
+ private final int responseTimeoutMillis;
+ private final long maxResponseBytes;
+
+ private ExternalRequestConfig(Builder builder) {
+ this.connectTimeoutMillis = requirePositiveInt(builder.connectTimeoutMillis, "connectTimeoutMillis");
+ this.responseTimeoutMillis = requirePositiveInt(builder.responseTimeoutMillis, "responseTimeoutMillis");
+ this.maxResponseBytes = requirePositive(builder.maxResponseBytes, "maxResponseBytes");
+ }
+
+ public static ExternalRequestConfig defaults() {
+ return builder().build();
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public int getConnectTimeoutMillis() {
+ return connectTimeoutMillis;
+ }
+
+ public int getResponseTimeoutMillis() {
+ return responseTimeoutMillis;
+ }
+
+ public long getMaxResponseBytes() {
+ return maxResponseBytes;
+ }
+
+ private static long requirePositive(long value, String name) {
+ if (value <= 0) {
+ throw new IllegalArgumentException(name + " must be greater than zero");
+ }
+ return value;
+ }
+
+ private static int requirePositiveInt(int value, String name) {
+ if (value <= 0) {
+ throw new IllegalArgumentException(name + " must be greater than zero");
+ }
+ return value;
+ }
+
+ public static final class Builder {
+
+ private int connectTimeoutMillis = DEFAULT_CONNECT_TIMEOUT_MILLIS;
+ private int responseTimeoutMillis = DEFAULT_RESPONSE_TIMEOUT_MILLIS;
+ private long maxResponseBytes = DEFAULT_MAX_RESPONSE_BYTES;
+
+ private Builder() {
+ }
+
+ public Builder connectTimeoutMillis(int connectTimeoutMillis) {
+ this.connectTimeoutMillis = connectTimeoutMillis;
+ return this;
+ }
+
+ public Builder responseTimeoutMillis(int responseTimeoutMillis) {
+ this.responseTimeoutMillis = responseTimeoutMillis;
+ return this;
+ }
+
+ public Builder maxResponseBytes(long maxResponseBytes) {
+ this.maxResponseBytes = maxResponseBytes;
+ return this;
+ }
+
+ public ExternalRequestConfig build() {
+ return new ExternalRequestConfig(this);
+ }
+ }
+}
diff --git a/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/external/ExternalRequestException.java b/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/external/ExternalRequestException.java
new file mode 100644
index 0000000000..5f4705a4c5
--- /dev/null
+++ b/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/external/ExternalRequestException.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://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.apache.streampipes.client.api.external;
+
+public class ExternalRequestException extends RuntimeException {
+
+ private final int statusCode;
+
+ public ExternalRequestException(String message, int statusCode) {
+ super(message);
+ this.statusCode = statusCode;
+ }
+
+ public ExternalRequestException(String message, Throwable cause) {
+ super(message, cause);
+ this.statusCode = -1;
+ }
+
+ public int getStatusCode() {
+ return statusCode;
+ }
+}
diff --git a/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/external/ExternalRequestMethod.java b/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/external/ExternalRequestMethod.java
new file mode 100644
index 0000000000..af2ac1f83d
--- /dev/null
+++ b/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/external/ExternalRequestMethod.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://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.apache.streampipes.client.api.external;
+
+public enum ExternalRequestMethod {
+ GET,
+ POST,
+ PUT,
+ DELETE
+}
diff --git a/streampipes-client-api/src/test/java/org/apache/streampipes/client/api/external/ExternalRequestTest.java b/streampipes-client-api/src/test/java/org/apache/streampipes/client/api/external/ExternalRequestTest.java
new file mode 100644
index 0000000000..42a5397cb9
--- /dev/null
+++ b/streampipes-client-api/src/test/java/org/apache/streampipes/client/api/external/ExternalRequestTest.java
@@ -0,0 +1,134 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://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.apache.streampipes.client.api.external;
+
+import org.junit.jupiter.api.Test;
+
+import java.net.URI;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class ExternalRequestTest {
+
+ @Test
+ void preservesRequestDataInImmutableCopies() {
+ Map<String, String> headers = new LinkedHashMap<>();
+ headers.put("Authorization", "Bearer token");
+ Map<String, String> queryParameters = new LinkedHashMap<>();
+ queryParameters.put("page", "1");
+
+ ExternalRequest request = ExternalRequest.builder(ExternalRequestMethod.POST, URI.create("https://api.example.org/v1"))
+ .headers(headers)
+ .queryParameters(queryParameters)
+ .payload(Map.of("name", "value"))
+ .connectTimeoutMillis(1_000)
+ .responseTimeoutMillis(2_000)
+ .maxResponseBytes(3_000)
+ .build();
+ headers.put("Authorization", "changed");
+ queryParameters.put("page", "2");
+
+ assertEquals("Bearer token", request.getHeaders().get("Authorization"));
+ assertEquals("1", request.getQueryParameters().get("page"));
+ assertThrows(UnsupportedOperationException.class, () -> request.getHeaders().put("X-Test", "value"));
+ assertEquals(1_000, request.getConnectTimeoutMillis());
+ assertEquals(2_000, request.getResponseTimeoutMillis());
+ assertEquals(3_000L, request.getMaxResponseBytes());
+ }
+
+ @Test
+ void acceptsOnlyAbsoluteHttpUrisWithoutSensitiveParts() {
+ assertThrows(IllegalArgumentException.class,
+ () -> request(URI.create("/relative"), ExternalRequestMethod.GET, null));
+ assertThrows(IllegalArgumentException.class,
+ () -> request(URI.create("ftp://api.example.org"), ExternalRequestMethod.GET, null));
+ assertThrows(IllegalArgumentException.class,
+ () -> request(URI.create("https://user@api.example.org"), ExternalRequestMethod.GET, null));
+ assertThrows(IllegalArgumentException.class,
+ () -> request(URI.create("https://api.example.org#fragment"), ExternalRequestMethod.GET, null));
+ }
+
+ @Test
+ void rejectsTransportControlledHeadersCaseInsensitively() {
+ for (String header : new String[] {"Connection", "CONTENT-LENGTH", "Host", "Transfer-Encoding", "upgrade"}) {
+ assertThrows(IllegalArgumentException.class,
+ () -> ExternalRequest.builder(ExternalRequestMethod.GET, URI.create("https://api.example.org"))
+ .header(header, "value")
+ .build());
+ }
+ }
+
+ @Test
+ void rejectsHeaderInjectionCharacters() {
+ assertThrows(IllegalArgumentException.class,
+ () -> ExternalRequest.builder(ExternalRequestMethod.GET, URI.create("https://api.example.org"))
+ .header("X-Test\r\nHost", "example.org")
+ .build());
+ assertThrows(IllegalArgumentException.class,
+ () -> ExternalRequest.builder(ExternalRequestMethod.GET, URI.create("https://api.example.org"))
+ .header("X-Test", "value\r\nHost: example.org")
+ .build());
+ }
+
+ @Test
+ void requiresBodiesOnlyForPostAndPut() {
+ assertThrows(IllegalArgumentException.class,
+ () -> request(URI.create("https://api.example.org"), ExternalRequestMethod.POST, null));
+ assertThrows(IllegalArgumentException.class,
+ () -> request(URI.create("https://api.example.org"), ExternalRequestMethod.PUT, null));
+ assertThrows(IllegalArgumentException.class,
+ () -> request(URI.create("https://api.example.org"), ExternalRequestMethod.GET, Map.of()));
+ assertThrows(IllegalArgumentException.class,
+ () -> request(URI.create("https://api.example.org"), ExternalRequestMethod.DELETE, Map.of()));
+ }
+
+ @Test
+ void exposesSecureDefaultLimits() {
+ ExternalRequestConfig config = ExternalRequestConfig.defaults();
+
+ assertEquals(10_000, config.getConnectTimeoutMillis());
+ assertEquals(30_000, config.getResponseTimeoutMillis());
+ assertEquals(10L * 1024 * 1024, config.getMaxResponseBytes());
+ }
+
+ @Test
+ void rejectsNonPositiveLimits() {
+ assertThrows(IllegalArgumentException.class,
+ () -> ExternalRequestConfig.builder().connectTimeoutMillis(0).build());
+ assertThrows(IllegalArgumentException.class,
+ () -> ExternalRequestConfig.builder().responseTimeoutMillis(-1).build());
+ assertThrows(IllegalArgumentException.class,
+ () -> ExternalRequestConfig.builder().maxResponseBytes(0).build());
+ assertThrows(IllegalArgumentException.class,
+ () -> ExternalRequest.builder(ExternalRequestMethod.GET, URI.create("https://api.example.org"))
+ .maxResponseBytes(-1)
+ .build());
+ }
+
+ private ExternalRequest request(URI uri, ExternalRequestMethod method, Object payload) {
+ ExternalRequest.Builder builder = ExternalRequest.builder(method, uri);
+ if (payload != null) {
+ builder.payload(payload);
+ }
+ return builder.build();
+ }
+}
diff --git a/streampipes-client/pom.xml b/streampipes-client/pom.xml
index 6be9a4575a..b3f0250286 100644
--- a/streampipes-client/pom.xml
+++ b/streampipes-client/pom.xml
@@ -72,6 +72,10 @@
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
</dependency>
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ </dependency>
</dependencies>
<build>
diff --git a/streampipes-client/src/main/java/org/apache/streampipes/client/StreamPipesClient.java b/streampipes-client/src/main/java/org/apache/streampipes/client/StreamPipesClient.java
index 9525bb81bb..66809957e8 100644
--- a/streampipes-client/src/main/java/org/apache/streampipes/client/StreamPipesClient.java
+++ b/streampipes-client/src/main/java/org/apache/streampipes/client/StreamPipesClient.java
@@ -25,16 +25,19 @@ import org.apache.streampipes.client.api.DataLakeResourceApi;
import org.apache.streampipes.client.api.DataProcessorApi;
import org.apache.streampipes.client.api.DataSinkApi;
import org.apache.streampipes.client.api.DataStreamApi;
+import org.apache.streampipes.client.api.ExternalRequestApi;
import org.apache.streampipes.client.api.FileApi;
import org.apache.streampipes.client.api.IAdapterApi;
import org.apache.streampipes.client.api.IAdminApi;
import org.apache.streampipes.client.api.ICustomRequestApi;
+import org.apache.streampipes.client.api.IExternalRequestApi;
import org.apache.streampipes.client.api.IPipelineElementTemplateApi;
import org.apache.streampipes.client.api.IStreamPipesClient;
import org.apache.streampipes.client.api.PipelineApi;
import org.apache.streampipes.client.api.PipelineElementTemplateApi;
import org.apache.streampipes.client.api.config.ClientConnectionUrlResolver;
import org.apache.streampipes.client.api.credentials.CredentialsProvider;
+import org.apache.streampipes.client.api.external.ExternalRequestConfig;
import org.apache.streampipes.client.model.StreamPipesClientConfig;
import org.apache.streampipes.client.model.StreamPipesClientConnectionConfig;
import org.apache.streampipes.client.paths.ApiPath;
@@ -209,6 +212,16 @@ public class StreamPipesClient implements
return new CustomRequestApi(config);
}
+ @Override
+ public IExternalRequestApi externalRequest() {
+ return externalRequest(ExternalRequestConfig.defaults());
+ }
+
+ @Override
+ public IExternalRequestApi externalRequest(ExternalRequestConfig requestConfig) {
+ return new ExternalRequestApi(requestConfig);
+ }
+
@Override
@ExposedToScripts
public IAdminApi adminApi() {
diff --git a/streampipes-client/src/main/java/org/apache/streampipes/client/api/ExternalRequestApi.java b/streampipes-client/src/main/java/org/apache/streampipes/client/api/ExternalRequestApi.java
new file mode 100644
index 0000000000..76915cbb36
--- /dev/null
+++ b/streampipes-client/src/main/java/org/apache/streampipes/client/api/ExternalRequestApi.java
@@ -0,0 +1,372 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://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.apache.streampipes.client.api;
+
+import org.apache.streampipes.client.api.external.ExternalRequest;
+import org.apache.streampipes.client.api.external.ExternalRequestConfig;
+import org.apache.streampipes.client.api.external.ExternalRequestException;
+import org.apache.streampipes.client.api.external.ExternalRequestMethod;
+import org.apache.streampipes.serializers.json.JacksonSerializer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import org.apache.http.HttpEntity;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.client.methods.RequestBuilder;
+import org.apache.http.client.utils.URIBuilder;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.message.BasicHeader;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+public class ExternalRequestApi implements IExternalRequestApi {
+
+ private static final String JSON_MEDIA_TYPE = "application/json";
+ private static final int MAX_ERROR_RESPONSE_BYTES = 8 * 1024;
+ private static final ScheduledExecutorService RESPONSE_TIMEOUT_SCHEDULER = Executors.newSingleThreadScheduledExecutor(
+ runnable -> {
+ Thread thread = new Thread(runnable, "streampipes-external-request-timeout");
+ thread.setDaemon(true);
+ return thread;
+ }
+ );
+
+ private final ExternalRequestConfig config;
+
+ public ExternalRequestApi(ExternalRequestConfig config) {
+ this.config = config;
+ }
+
+ @Override
+ public <T> void sendPost(String url, Map<String, String> headers, T payload) {
+ executeWithoutResponse(request(ExternalRequestMethod.POST, url, headers, Map.of(), payload));
+ }
+
+ @Override
+ public <T> T sendPost(String url, Map<String, String> headers, Object payload, Class<T> responseClass) {
+ return execute(request(ExternalRequestMethod.POST, url, headers, Map.of(), payload), responseClass);
+ }
+
+ @Override
+ public Map<String, Object> sendPostJson(String url, Map<String, String> headers, Object payload) {
+ return sendPost(url, headers, payload, Map.class);
+ }
+
+ @Override
+ public <T> T sendGet(String url,
+ Map<String, String> headers,
+ Map<String, String> queryParameters,
+ Class<T> responseClass) {
+ return execute(request(ExternalRequestMethod.GET, url, headers, queryParameters, null), responseClass);
+ }
+
+ @Override
+ public Map<String, Object> sendGetJson(String url,
+ Map<String, String> headers,
+ Map<String, String> queryParameters) {
+ return sendGet(url, headers, queryParameters, Map.class);
+ }
+
+ @Override
+ public <T> void sendPut(String url, Map<String, String> headers, T payload) {
+ executeWithoutResponse(request(ExternalRequestMethod.PUT, url, headers, Map.of(), payload));
+ }
+
+ @Override
+ public <T> T sendPut(String url, Map<String, String> headers, Object payload, Class<T> responseClass) {
+ return execute(request(ExternalRequestMethod.PUT, url, headers, Map.of(), payload), responseClass);
+ }
+
+ @Override
+ public Map<String, Object> sendPutJson(String url, Map<String, String> headers, Object payload) {
+ return sendPut(url, headers, payload, Map.class);
+ }
+
+ @Override
+ public void sendDelete(String url, Map<String, String> headers) {
+ executeWithoutResponse(request(ExternalRequestMethod.DELETE, url, headers, Map.of(), null));
+ }
+
+ @Override
+ public Map<String, Object> sendDeleteJson(String url, Map<String, String> headers) {
+ return execute(request(ExternalRequestMethod.DELETE, url, headers, Map.of(), null), Map.class);
+ }
+
+ @Override
+ public <T> List<T> getList(String url,
+ Map<String, String> headers,
+ Map<String, String> queryParameters,
+ Class<T> responseClass) {
+ return getList(request(ExternalRequestMethod.GET, url, headers, queryParameters, null), responseClass);
+ }
+
+ @Override
+ public <T> T execute(ExternalRequest request, Class<T> responseClass) {
+ String response = executeRequest(request);
+ if (response == null || response.isBlank()) {
+ return null;
+ }
+ try {
+ return JacksonSerializer.getObjectMapper().readValue(response, responseClass);
+ } catch (JsonProcessingException e) {
+ throw new ExternalRequestException("Could not deserialize external HTTP response", e);
+ }
+ }
+
+ private void executeWithoutResponse(ExternalRequest request) {
+ executeRequest(request);
+ }
+
+ @Override
+ public Object executeJson(ExternalRequest request) {
+ return execute(request, Object.class);
+ }
+
+ @Override
+ public <T> List<T> getList(ExternalRequest request, Class<T> responseClass) {
+ String response = executeRequest(request);
+ if (response == null || response.isBlank()) {
+ return null;
+ }
+ try {
+ return JacksonSerializer.getObjectMapper().readValue(
+ response,
+ JacksonSerializer.getObjectMapper().getTypeFactory().constructCollectionType(List.class, responseClass)
+ );
+ } catch (JsonProcessingException e) {
+ throw new ExternalRequestException("Could not deserialize external HTTP response", e);
+ }
+ }
+
+ private String executeRequest(ExternalRequest request) {
+ validateRequestLimits(request);
+ HttpUriRequest httpRequest = makeRequest(request);
+ try (CloseableHttpClient client = HttpClients.custom()
+ .disableAutomaticRetries()
+ .disableRedirectHandling()
+ .build();
+ ) {
+ AtomicBoolean timedOut = new AtomicBoolean();
+ ScheduledFuture<?> timeout = RESPONSE_TIMEOUT_SCHEDULER.schedule(() -> {
+ timedOut.set(true);
+ closeQuietly(client);
+ }, effectiveResponseTimeout(request), TimeUnit.MILLISECONDS);
+ try {
+ try (CloseableHttpResponse response = client.execute(httpRequest)) {
+ int statusCode = response.getStatusLine().getStatusCode();
+ String body;
+ try {
+ body = readEntity(response.getEntity(), effectiveMaxResponseBytes(request));
+ } catch (ResponseSizeLimitException e) {
+ throw sizeLimitException(request, statusCode, e);
+ }
+ if (statusCode < 200 || statusCode >= 300) {
+ throw new ExternalRequestException(
+ "External " + request.getMethod() + " request to " + sanitizedUri(request.getUri())
+ + " failed with status " + statusCode + ": " + abbreviate(body),
+ statusCode
+ );
+ }
+ return body;
+ }
+ } catch (IOException e) {
+ if (timedOut.get()) {
+ throw new ExternalRequestException(
+ "External " + request.getMethod() + " request to " + sanitizedUri(request.getUri()) + " timed out",
+ e
+ );
+ }
+ throw new ExternalRequestException(
+ "Could not execute external " + request.getMethod() + " request to " + sanitizedUri(request.getUri()),
+ e
+ );
+ } finally {
+ timeout.cancel(false);
+ }
+ } catch (IOException e) {
+ throw new ExternalRequestException(
+ "Could not close external " + request.getMethod() + " request to " + sanitizedUri(request.getUri()),
+ e
+ );
+ }
+ }
+
+ private void closeQuietly(CloseableHttpClient client) {
+ try {
+ client.close();
+ } catch (IOException ignored) {
+ // The timeout is already being reported to the caller.
+ }
+ }
+
+ private ExternalRequest request(ExternalRequestMethod method,
+ String url,
+ Map<String, String> headers,
+ Map<String, String> queryParameters,
+ Object payload) {
+ ExternalRequest.Builder builder = ExternalRequest.builder(method, URI.create(url))
+ .headers(headers)
+ .queryParameters(queryParameters);
+ if (payload != null) {
+ builder.payload(payload);
+ }
+ return builder.build();
+ }
+
+ private HttpUriRequest makeRequest(ExternalRequest request) {
+ RequestBuilder builder = RequestBuilder.create(request.getMethod().name())
+ .setUri(withQueryParameters(request.getUri(), request.getQueryParameters()))
+ .setConfig(RequestConfig.custom()
+ .setConnectTimeout(effectiveConnectTimeout(request))
+ .setSocketTimeout(effectiveResponseTimeout(request))
+ .build());
+
+ if (request.getPayload() != null) {
+ builder.setEntity(new StringEntity(serialize(request.getPayload()), ContentType.APPLICATION_JSON));
+ }
+
+ request.getHeaders().forEach((name, value) -> builder.setHeader(new BasicHeader(name, value)));
+ if (!containsHeader(request.getHeaders(), "Accept")) {
+ builder.setHeader("Accept", JSON_MEDIA_TYPE);
+ }
+ if (request.getPayload() != null && !containsHeader(request.getHeaders(), "Content-Type")) {
+ builder.setHeader("Content-Type", JSON_MEDIA_TYPE);
+ }
+ return builder.build();
+ }
+
+ private String serialize(Object payload) {
+ try {
+ return JacksonSerializer.getObjectMapper().writeValueAsString(payload);
+ } catch (JsonProcessingException e) {
+ throw new ExternalRequestException("Could not serialize external HTTP request payload", e);
+ }
+ }
+
+ private URI withQueryParameters(URI uri, Map<String, String> queryParameters) {
+ try {
+ URIBuilder builder = new URIBuilder(uri);
+ queryParameters.forEach(builder::addParameter);
+ return builder.build();
+ } catch (URISyntaxException e) {
+ throw new IllegalArgumentException("Could not build external request URI", e);
+ }
+ }
+
+ private String readEntity(HttpEntity entity, long maxResponseBytes) throws IOException {
+ if (entity == null) {
+ return null;
+ }
+ try (InputStream input = entity.getContent(); ByteArrayOutputStream output = new ByteArrayOutputStream()) {
+ byte[] buffer = new byte[8192];
+ int bytesRead;
+ long totalBytes = 0;
+ while ((bytesRead = input.read(buffer)) != -1) {
+ totalBytes += bytesRead;
+ if (totalBytes > maxResponseBytes) {
+ throw new ResponseSizeLimitException(output.toString(StandardCharsets.UTF_8));
+ }
+ output.write(buffer, 0, bytesRead);
+ }
+ return output.toString(StandardCharsets.UTF_8);
+ }
+ }
+
+ private int effectiveConnectTimeout(ExternalRequest request) {
+ return request.getConnectTimeoutMillis() == null
+ ? config.getConnectTimeoutMillis() : request.getConnectTimeoutMillis();
+ }
+
+ private int effectiveResponseTimeout(ExternalRequest request) {
+ return request.getResponseTimeoutMillis() == null
+ ? config.getResponseTimeoutMillis() : request.getResponseTimeoutMillis();
+ }
+
+ private long effectiveMaxResponseBytes(ExternalRequest request) {
+ return request.getMaxResponseBytes() == null
+ ? config.getMaxResponseBytes() : request.getMaxResponseBytes();
+ }
+
+ private void validateRequestLimits(ExternalRequest request) {
+ validateLimit(request.getConnectTimeoutMillis(), config.getConnectTimeoutMillis(), "connectTimeoutMillis");
+ validateLimit(request.getResponseTimeoutMillis(), config.getResponseTimeoutMillis(), "responseTimeoutMillis");
+ validateLimit(request.getMaxResponseBytes(), config.getMaxResponseBytes(), "maxResponseBytes");
+ }
+
+ private void validateLimit(Number requestedLimit, Number configuredLimit, String limitName) {
+ if (requestedLimit != null && requestedLimit.longValue() > configuredLimit.longValue()) {
+ throw new IllegalArgumentException(limitName + " must not exceed the configured external request limit");
+ }
+ }
+
+ private ExternalRequestException sizeLimitException(ExternalRequest request,
+ int statusCode,
+ ResponseSizeLimitException exception) {
+ return new ExternalRequestException(
+ "External " + request.getMethod() + " request to " + sanitizedUri(request.getUri())
+ + " exceeded the configured response size limit with status " + statusCode + ": "
+ + abbreviate(exception.responsePrefix),
+ statusCode
+ );
+ }
+
+ private boolean containsHeader(Map<String, String> headers, String name) {
+ return headers.keySet().stream().anyMatch(header -> header.equalsIgnoreCase(name));
+ }
+
+ private String sanitizedUri(URI uri) {
+ try {
+ return new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getRawPath(), null, null).toString();
+ } catch (URISyntaxException e) {
+ return uri.getScheme() + "://" + uri.getHost();
+ }
+ }
+
+ private String abbreviate(String body) {
+ if (body == null || body.isBlank()) {
+ return "no response body";
+ }
+ return body.length() <= MAX_ERROR_RESPONSE_BYTES ? body : body.substring(0, MAX_ERROR_RESPONSE_BYTES) + "...";
+ }
+
+ private static final class ResponseSizeLimitException extends IOException {
+
+ private final String responsePrefix;
+
+ private ResponseSizeLimitException(String responsePrefix) {
+ this.responsePrefix = responsePrefix;
+ }
+ }
+}
diff --git a/streampipes-client/src/test/java/org/apache/streampipes/client/api/ExternalRequestApiTest.java b/streampipes-client/src/test/java/org/apache/streampipes/client/api/ExternalRequestApiTest.java
new file mode 100644
index 0000000000..c2be7c0de6
--- /dev/null
+++ b/streampipes-client/src/test/java/org/apache/streampipes/client/api/ExternalRequestApiTest.java
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ * http://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.apache.streampipes.client.api;
+
+import org.apache.streampipes.client.StreamPipesClient;
+import org.apache.streampipes.client.api.config.ClientConnectionUrlResolver;
+import org.apache.streampipes.client.api.external.ExternalRequestConfig;
+import org.apache.streampipes.client.api.external.ExternalRequestException;
+import org.apache.streampipes.client.credentials.StreamPipesApiKeyCredentials;
+
+import com.sun.net.httpserver.HttpServer;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ExternalRequestApiTest {
+
+ private HttpServer server;
+
+ @AfterEach
+ void stopServer() {
+ if (server != null) {
+ server.stop(0);
+ }
+ }
+
+ @Test
+ void sendsJsonGetWithoutStreamPipesCredentialsOrCustomHeaders() throws Exception {
+ AtomicReference<String> authorization = new AtomicReference<>();
+ AtomicReference<String> customHeader = new AtomicReference<>();
+ server = HttpServer.create(new InetSocketAddress(0), 0);
+ server.createContext("/resource", exchange -> {
+ authorization.set(exchange.getRequestHeaders().getFirst("Authorization"));
+ customHeader.set(exchange.getRequestHeaders().getFirst("X-On-Behalf-Of"));
+ byte[] body = "{\"name\":\"external\"}".getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().set("Content-Type", "application/json");
+ exchange.sendResponseHeaders(200, body.length);
+ exchange.getResponseBody().write(body);
+ exchange.close();
+ });
+ server.start();
+
+ var client = client();
+ client.getConfig().addCustomHeader("X-On-Behalf-Of", "user-id");
+ Map<?, ?> response = client.externalRequest(ExternalRequestConfig.defaults())
+ .sendGet(resourceUri("/resource"), Map.of(), Map.of(), Map.class);
+
+ assertEquals("external", response.get("name"));
+ assertNull(authorization.get());
+ assertNull(customHeader.get());
+ }
+
+ @Test
+ void sendsPostPutAndDeleteWithCallerHeadersAndQueryParameters() throws Exception {
+ AtomicReference<String> requestMethod = new AtomicReference<>();
+ AtomicReference<String> requestBody = new AtomicReference<>();
+ AtomicReference<String> authorization = new AtomicReference<>();
+ server = HttpServer.create(new InetSocketAddress(0), 0);
+ server.createContext("/resource", exchange -> {
+ requestMethod.set(exchange.getRequestMethod());
+ requestBody.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
+ authorization.set(exchange.getRequestHeaders().getFirst("Authorization"));
+ if ("POST".equals(exchange.getRequestMethod())) {
+ writeJson(exchange, 200, "{\"created\":true}");
+ } else if ("PUT".equals(exchange.getRequestMethod())) {
+ writeJson(exchange, 200, "{\"updated\":true}");
+ } else {
+ exchange.sendResponseHeaders(204, -1);
+ exchange.close();
+ }
+ });
+ server.start();
+
+ var api = client().externalRequest();
+ api.sendPost(resourceUri("/resource").toString(), Map.of("Authorization", "Bearer external-token"), Map.of("value", 1));
+ assertEquals("POST", requestMethod.get());
+ assertTrue(requestBody.get().contains("\"value\" : 1"));
+ assertEquals("Bearer external-token", authorization.get());
+
+ api.sendPut(resourceUri("/resource"), Map.of(), Map.of("value", 2));
+ assertEquals("PUT", requestMethod.get());
+
+ api.sendDelete(resourceUri("/resource"), Map.of());
+ assertEquals("DELETE", requestMethod.get());
+
+ Map<String, Object> postResponse = api.sendPostJson(resourceUri("/resource").toString(), Map.of("value", 3));
+ assertEquals(true, postResponse.get("created"));
+
+ Map<String, Object> putResponse = api.sendPutJson(resourceUri("/resource"), Map.of(), Map.of("value", 4));
+ assertEquals(true, putResponse.get("updated"));
+ }
+
+ @Test
+ void sendsVoidRequestsWithoutRequiringJsonResponses() throws Exception {
+ server = HttpServer.create(new InetSocketAddress(0), 0);
+ server.createContext("/acknowledged", exchange -> {
+ byte[] body = "accepted".getBytes(StandardCharsets.UTF_8);
+ exchange.sendResponseHeaders(202, body.length);
+ exchange.getResponseBody().write(body);
+ exchange.close();
+ });
+ server.start();
+
+ var api = client().externalRequest();
+ api.sendPost(resourceUri("/acknowledged"), Map.of(), Map.of("value", 1));
+ api.sendPut(resourceUri("/acknowledged"), Map.of(), Map.of("value", 2));
+ }
+
+ @Test
+ void preservesExistingUriQueriesWhenAddingQueryParameters() throws Exception {
+ AtomicReference<String> query = new AtomicReference<>();
+ server = HttpServer.create(new InetSocketAddress(0), 0);
+ server.createContext("/query", exchange -> {
+ query.set(exchange.getRequestURI().getRawQuery());
+ writeJson(exchange, 200, "{}");
+ });
+ server.start();
+
+ client().externalRequest().sendGetJson(
+ resourceUri("/query").toString() + "?existing=value",
+ Map.of(),
+ Map.of("added", "another value")
+ );
+
+ assertEquals("existing=value&added=another+value", query.get());
+ }
+
+ @Test
+ void deserializesListsAndDoesNotFollowRedirects() throws Exception {
+ server = HttpServer.create(new InetSocketAddress(0), 0);
+ server.createContext("/list", exchange -> writeJson(exchange, 200, "[{\"name\":\"one\"}]"));
+ server.createContext("/redirect", exchange -> {
+ exchange.getResponseHeaders().set("Location", resourceUri("/list").toString());
+ exchange.sendResponseHeaders(302, -1);
+ exchange.close();
+ });
+ server.start();
+
+ List<Map> response = client().externalRequest().getList(resourceUri("/list"), Map.of(), Map.of(), Map.class);
+ assertEquals("one", response.get(0).get("name"));
+
+ ExternalRequestException exception = assertThrows(ExternalRequestException.class,
+ () -> client().externalRequest().sendGetJson(resourceUri("/redirect").toString()));
+ assertEquals(302, exception.getStatusCode());
+ }
+
+ @Test
+ void rejectsInvalidRequestsAndBoundsResponseBodies() throws Exception {
+ assertThrows(IllegalArgumentException.class, () -> client().externalRequest().sendGetJson("/relative"));
+ assertThrows(IllegalArgumentException.class,
+ () -> client().externalRequest().sendGetJson("https://user@example.org"));
+ assertThrows(IllegalArgumentException.class,
+ () -> client().externalRequest().sendGetJson("https://example.org#fragment"));
+ assertThrows(IllegalArgumentException.class,
+ () -> client().externalRequest().sendGetJson(
+ "https://example.org", Map.of("hOsT", "other.example"), Map.of()));
+
+ server = HttpServer.create(new InetSocketAddress(0), 0);
+ server.createContext("/large", exchange -> writeJson(exchange, 200, "\"" + "x".repeat(128) + "\""));
+ server.start();
+ var api = client().externalRequest(ExternalRequestConfig.builder().maxResponseBytes(64).build());
+ assertThrows(ExternalRequestException.class, () -> api.sendGetJson(resourceUri("/large").toString()));
+ }
+
+ @Test
+ void sanitizesFailureUrisAndIncludesStatusCode() throws Exception {
+ server = HttpServer.create(new InetSocketAddress(0), 0);
+ server.createContext("/failure", exchange -> writeJson(exchange, 418, "{\"error\":\"unavailable\"}"));
+ server.start();
+
+ ExternalRequestException exception = assertThrows(ExternalRequestException.class,
+ () -> client().externalRequest().sendGetJson(resourceUri("/failure").toString() + "?apiKey=secret"));
+
+ assertEquals(418, exception.getStatusCode());
+ assertTrue(exception.getMessage().contains("unavailable"));
+ assertFalse(exception.getMessage().contains("apiKey=secret"));
+ }
+
+ private String resourceUri(String path) {
+ return "http://localhost:" + server.getAddress().getPort() + path;
+ }
+
+ private StreamPipesClient client() {
+ return StreamPipesClient.create(new ClientConnectionUrlResolver() {
+ @Override
+ public StreamPipesApiKeyCredentials getCredentials() {
+ return new StreamPipesApiKeyCredentials("service", "secret");
+ }
+
+ @Override
+ public String getBaseUrl() {
+ return "https://streampipes.example";
+ }
+ });
+ }
+
+ private void writeJson(com.sun.net.httpserver.HttpExchange exchange, int statusCode, String response) throws IOException {
+ byte[] body = response.getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().set("Content-Type", "application/json");
+ exchange.sendResponseHeaders(statusCode, body.length);
+ exchange.getResponseBody().write(body);
+ exchange.close();
+ }
+}