repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/coercion/ConnectorHubCoercionTest.java | fn-events/src/test/java/com/fnproject/events/coercion/ConnectorHubCoercionTest.java | package com.fnproject.events.coercion;
import static com.fnproject.events.coercion.APIGatewayCoercion.OM_KEY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.Collections;
import java.util.Date;
import java.util.Optional;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fnproject.events.input.ConnectorHubBatch;
import com.fnproject.events.input.sch.LoggingData;
import com.fnproject.events.input.sch.MetricData;
import com.fnproject.events.input.sch.StreamingData;
import com.fnproject.events.testfns.Animal;
import com.fnproject.events.testfns.connectorhub.GrandChildMonitorSourceTestFunction;
import com.fnproject.events.testfns.connectorhub.LoggingSourceTestFunction;
import com.fnproject.events.testfns.connectorhub.MonitorSourceTestFunction;
import com.fnproject.events.testfns.connectorhub.QueueSourceObjectTestFunction;
import com.fnproject.events.testfns.connectorhub.QueueSourceStringTestFunction;
import com.fnproject.events.testfns.connectorhub.StreamingSourceObjectTestFunction;
import com.fnproject.events.testfns.connectorhub.StreamingSourceStringTestFunction;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.api.InvocationContext;
import com.fnproject.fn.api.MethodWrapper;
import com.fnproject.fn.api.RuntimeContext;
import com.fnproject.fn.runtime.DefaultMethodWrapper;
import com.fnproject.fn.runtime.ReadOnceInputEvent;
import org.junit.Before;
import org.junit.Test;
public class ConnectorHubCoercionTest {
private ConnectorHubCoercion coercion;
private InvocationContext requestinvocationContext;
@Before
public void setUp() {
coercion = ConnectorHubCoercion.instance();
requestinvocationContext = mock(InvocationContext.class);
RuntimeContext runtimeContext = mock(RuntimeContext.class);
ObjectMapper mapper = new ObjectMapper();
when(runtimeContext.getAttribute(OM_KEY, ObjectMapper.class)).thenReturn(Optional.of(mapper));
when(requestinvocationContext.getRuntimeContext()).thenReturn(runtimeContext);
}
@Test
public void testReturnEmptyWhenNotConnectorHubEventClass() {
MethodWrapper method = new DefaultMethodWrapper(APIGatewayCoercionTest.class, "testMethod");
Headers headers = Headers.emptyHeaders();
when(requestinvocationContext.getRequestHeaders()).thenReturn(headers);
ByteArrayInputStream is = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
InputEvent inputEvent = new ReadOnceInputEvent(is, Headers.emptyHeaders(), "call", Instant.now());
Optional<ConnectorHubBatch<?>> batch = coercion.tryCoerceParam(requestinvocationContext, 0, inputEvent, method);
assertFalse(batch.isPresent());
}
@Test
public void testMonitoringSourceInput() {
MethodWrapper method = new DefaultMethodWrapper(MonitorSourceTestFunction.class, "handler");
ConnectorHubBatch<MetricData> event = coerceRequest(method, "[\n" +
" {\n" +
" \"namespace\": \"oci_objectstorage\",\n" +
" \"resourceGroup\": \"nullable\",\n" +
" \"compartmentId\": \"ocid1.tenancy.oc1..xyz\",\n" +
" \"name\": \"PutRequests\",\n" +
" \"dimensions\": {\n" +
" \"resourceID\": \"ocid1.bucket.oc1.uk-london-1.xyz\",\n" +
" \"resourceDisplayName\": \"foo\"\n" +
" },\n" +
" \"metadata\": {\n" +
" \"displayName\": \"PutObject Request Count\",\n" +
" \"unit\": \"count\"\n" +
" },\n" +
" \"datapoints\": [\n" +
" {\n" +
" \"timestamp\": 1761318377414,\n" +
" \"value\": 1.0,\n" +
" \"count\": 1\n" +
" }\n" +
" ]\n" +
" }," +
" {\n" +
" \"namespace\": \"oci_objectstorage\",\n" +
" \"resourceGroup\": null,\n" +
" \"compartmentId\": \"ocid1.tenancy.oc1..abc\",\n" +
" \"name\": \"PutRequests\",\n" +
" \"dimensions\": {\n" +
" \"resourceID\": \"ocid1.bucket.oc1.uk-london-1.abc\",\n" +
" \"resourceDisplayName\": \"bar\"\n" +
" },\n" +
" \"metadata\": {\n" +
" \"displayName\": \"PutObject Request Count\",\n" +
" \"unit\": \"count\"\n" +
" },\n" +
" \"datapoints\": [\n" +
" {\n" +
" \"timestamp\": 1761318377414,\n" +
" \"value\": 1.0,\n" +
" \"count\": 1\n" +
" },\n" +
" {\n" +
" \"timestamp\": 1761318377614,\n" +
" \"value\": 2.0,\n" +
" \"count\": 1\n" +
" }\n" +
" ]\n" +
" }" +
"]");
assertFalse(event.getBatch().isEmpty());
assertEquals(2, event.getBatch().size());
MetricData monitoringSource = event.getBatch().get(0);
assertEquals("PutRequests", monitoringSource.getName());
assertEquals("nullable", monitoringSource.getResourceGroup());
assertEquals("ocid1.tenancy.oc1..xyz", monitoringSource.getCompartmentId());
assertEquals("oci_objectstorage", monitoringSource.getNamespace());
assertEquals("ocid1.bucket.oc1.uk-london-1.xyz", monitoringSource.getDimensions().get("resourceID"));
assertEquals("foo", monitoringSource.getDimensions().get("resourceDisplayName"));
assertEquals("PutObject Request Count", monitoringSource.getMetadata().get("displayName"));
assertEquals("count", monitoringSource.getMetadata().get("unit"));
assertEquals(Integer.valueOf(1), monitoringSource.getDatapoints().get(0).getCount());
assertEquals(Double.parseDouble("1.0"), monitoringSource.getDatapoints().get(0).getValue(), 0);
assertEquals(Date.from(Instant.ofEpochMilli(Long.parseLong("1761318377414"))), monitoringSource.getDatapoints().get(0).getTimestamp());
}
@Test
public void testMonitoringSourceInputNoCount() {
MethodWrapper method = new DefaultMethodWrapper(MonitorSourceTestFunction.class, "handler");
ConnectorHubBatch<MetricData> event = coerceRequest(method, "[\n" +
" {\n" +
" \"namespace\":\"oci_computeagent\",\n" +
" \"compartmentId\":\"ocid1.tenancy.oc1..exampleuniqueID\",\n" +
" \"name\":\"DiskBytesRead\",\n" +
" \"dimensions\":{\n" +
" \"resourceId\":\"ocid1.instance.region1.phx.exampleuniqueID\"\n" +
" },\n" +
" \"metadata\":{\n" +
" \"unit\":\"bytes\"\n" +
" },\n" +
" \"datapoints\":[\n" +
" {\n" +
" \"timestamp\":\"1761318377414\",\n" +
" \"value\":10.4\n" +
" },\n" +
" {\n" +
" \"timestamp\":\"1761318377414\",\n" +
" \"value\":11.3\n" +
" }\n" +
" ]\n" +
" }\n" +
"]");
assertFalse(event.getBatch().isEmpty());
assertEquals(1, event.getBatch().size());
MetricData monitoringSource = event.getBatch().get(0);
assertEquals("DiskBytesRead", monitoringSource.getName());
assertEquals("ocid1.tenancy.oc1..exampleuniqueID", monitoringSource.getCompartmentId());
assertEquals("oci_computeagent", monitoringSource.getNamespace());
assertNull(monitoringSource.getDimensions().get("resourceID"));
assertNull(monitoringSource.getDimensions().get("resourceDisplayName"));
assertNull(monitoringSource.getMetadata().get("displayName"));
assertEquals("bytes", monitoringSource.getMetadata().get("unit"));
assertEquals(Double.parseDouble("10.4"), monitoringSource.getDatapoints().get(0).getValue(), 0);
assertEquals(Date.from(Instant.ofEpochMilli(Long.parseLong("1761318377414"))), monitoringSource.getDatapoints().get(0).getTimestamp());
}
@Test
public void testMonitoringSourceInputEmpty() {
MethodWrapper method = new DefaultMethodWrapper(MonitorSourceTestFunction.class, "handler");
ConnectorHubBatch<MetricData> event = coerceRequest(method, "[]");
assertTrue(event.getBatch().isEmpty());
}
@Test
public void testGrandChildIsCoercedInputEmpty() {
MethodWrapper method = new DefaultMethodWrapper(GrandChildMonitorSourceTestFunction.class, "handler");
ConnectorHubBatch<MetricData> event = coerceRequest(method, "[]");
assertTrue(event.getBatch().isEmpty());
}
@Test
public void testFailureToParseIsUserFriendlyError() {
MethodWrapper method = new DefaultMethodWrapper(MonitorSourceTestFunction.class, "handler");
RuntimeException exception = assertThrows(RuntimeException.class, () -> coerceRequest(method, "INVALID JSON"));
assertEquals(
"Failed to coerce event to user function parameter type [collection type; class java.util.List, contains [simple type, class com.fnproject.events.input.sch.MetricData]]",
exception.getMessage());
assertTrue(exception.getCause().getMessage().startsWith("Unrecognized token 'INVALID':"));
}
@Test
public void testLoggingSourceInput() {
MethodWrapper method = new DefaultMethodWrapper(LoggingSourceTestFunction.class, "handler");
ConnectorHubBatch<LoggingData> event = coerceRequest(method, "[\n" +
" {\n" +
" \"data\": {\n" +
" \"applicationId\": \"ocid1.fnapp.oc1.abc\",\n" +
" \"containerId\": \"n/a\",\n" +
" \"functionId\": \"ocid1.fnfunc.oc1.abc\",\n" +
" \"message\": \"Received function invocation request\",\n" +
" \"opcRequestId\": \"/abc/def\",\n" +
" \"requestId\": \"/def/abc\",\n" +
" \"src\": \"stdout\"\n" +
" },\n" +
" \"id\": \"abc-zyx\",\n" +
" \"oracle\": {\n" +
" \"compartmentid\": \"ocid1.tenancy.oc1..xyz\",\n" +
" \"ingestedtime\": \"2025-10-23T15:45:19.457Z\",\n" +
" \"loggroupid\": \"ocid1.loggroup.oc1.abc\",\n" +
" \"logid\": \"ocid1.log.oc1.def\",\n" +
" \"tenantid\": \"ocid1.tenancy.oc1..xyz\"\n" +
" },\n" +
" \"source\": \"your-log\",\n" +
" \"specversion\": \"1.0\",\n" +
" \"subject\": \"schedule\",\n" +
" \"time\": \"2025-10-24T15:06:17.000Z\",\n" +
" \"type\": \"com.oraclecloud.functions.application.functioninvoke\"\n" +
" },\n" +
" {\n" +
" \"data\": {\n" +
" \"applicationId\": \"ocid1.fnapp.oc1.def\",\n" +
" \"containerId\": \"n/a\",\n" +
" \"functionId\": \"ocid1.fnfunc.oc1.def\",\n" +
" \"message\": \"Received function invocation request\",\n" +
" \"opcRequestId\": \"/def/xyz\",\n" +
" \"requestId\": \"/foo/bar\",\n" +
" \"src\": \"stdout\"\n" +
" },\n" +
" \"id\": \"foo-zyx\",\n" +
" \"oracle\": {\n" +
" \"compartmentid\": \"ocid1.tenancy.oc1..xyz\",\n" +
" \"ingestedtime\": \"2025-11-23T15:45:19.457Z\",\n" +
" \"loggroupid\": \"ocid1.loggroup.oc1.def\",\n" +
" \"logid\": \"ocid1.log.oc1.xyz\",\n" +
" \"tenantid\": \"ocid1.tenancy.oc1..xyz\"\n" +
" },\n" +
" \"source\": \"your-log\",\n" +
" \"specversion\": \"1.0\",\n" +
" \"subject\": \"schedule\",\n" +
" \"time\": \"2025-11-23T15:45:17.239Z\",\n" +
" \"type\": \"com.oraclecloud.functions.application.functioninvoke\"\n" +
" }\n" +
"]");
assertFalse(event.getBatch().isEmpty());
assertEquals(2, event.getBatch().size());
LoggingData loggingData = event.getBatch().get(0);
assertEquals("your-log", loggingData.getSource());
assertEquals("abc-zyx", loggingData.getId());
assertEquals("schedule", loggingData.getSubject());
assertEquals("1.0", loggingData.getSpecversion());
assertEquals("ocid1.fnapp.oc1.abc", loggingData.getData().get("applicationId"));
assertEquals("n/a", loggingData.getData().get("containerId"));
assertEquals("ocid1.fnfunc.oc1.abc", loggingData.getData().get("functionId"));
assertEquals("Received function invocation request", loggingData.getData().get("message"));
assertEquals("/abc/def", loggingData.getData().get("opcRequestId"));
assertEquals("/def/abc", loggingData.getData().get("requestId"));
assertEquals("stdout", loggingData.getData().get("src"));
assertEquals("ocid1.tenancy.oc1..xyz", loggingData.getOracle().get("compartmentid"));
assertEquals("2025-10-23T15:45:19.457Z", loggingData.getOracle().get("ingestedtime"));
assertEquals("ocid1.loggroup.oc1.abc", loggingData.getOracle().get("loggroupid"));
assertEquals("ocid1.log.oc1.def", loggingData.getOracle().get("logid"));
assertEquals("ocid1.tenancy.oc1..xyz", loggingData.getOracle().get("tenantid"));
assertEquals(Date.from(Instant.ofEpochMilli(Long.parseLong("1761318377000"))), loggingData.getTime());
assertEquals("com.oraclecloud.functions.application.functioninvoke", loggingData.getType());
}
@Test
public void testStreamingSourceInput() {
MethodWrapper method = new DefaultMethodWrapper(StreamingSourceStringTestFunction.class, "handler");
ConnectorHubBatch<StreamingData<String>> event = coerceRequest(method, "[" +
"{\"stream\":\"stream-name\"," +
"\"partition\":\"0\"," +
"\"key\":null," +
"\"value\":\"U2VudCBhIHBsYWluIG1lc3NhZ2U=\"," +
"\"offset\":3," +
"\"timestamp\":1761223385480" +
"}," +
"{\"stream\":\"stream-name\"," +
"\"partition\":\"0\"," +
"\"key\":null," +
"\"value\":\"U2VudCBhIHBsYWluIG1lc3NhZ2U=\"," +
"\"offset\":3," +
"\"timestamp\":1761223385480" +
"}" +
"]");
assertFalse(event.getBatch().isEmpty());
assertEquals(2, event.getBatch().size());
StreamingData streamingData = event.getBatch().get(0);
assertEquals("stream-name", streamingData.getStream());
assertNull(streamingData.getKey());
assertEquals("3", streamingData.getOffset());
assertEquals("0", streamingData.getPartition());
assertEquals(Date.from(Instant.ofEpochMilli(Long.parseLong("1761223385480"))), streamingData.getTimestamp());
assertEquals("Sent a plain message", streamingData.getValue());
}
@Test
public void testStreamingSourceInputObject() throws JsonProcessingException {
MethodWrapper method = new DefaultMethodWrapper(StreamingSourceObjectTestFunction.class, "handler");
Animal animal = new Animal("cat", 2);
ConnectorHubBatch<StreamingData<Animal>> event = coerceRequest(method, "[" +
"{\"stream\":\"stream-name\"," +
"\"partition\":\"0\"," +
"\"key\":null," +
"\"value\":\"" + Base64.getEncoder().encodeToString(new ObjectMapper().writeValueAsBytes(animal)) + "\"," +
"\"offset\":3," +
"\"timestamp\":1761223385480" +
"}" +
"]");
assertFalse(event.getBatch().isEmpty());
assertEquals(1, event.getBatch().size());
StreamingData<Animal> streamingData = event.getBatch().get(0);
assertEquals("stream-name", streamingData.getStream());
assertNull(streamingData.getKey());
assertEquals("3", streamingData.getOffset());
assertEquals("0", streamingData.getPartition());
assertEquals(animal.getAge(), streamingData.getValue().getAge());
assertEquals(Date.from(Instant.ofEpochMilli(Long.parseLong("1761223385480"))), streamingData.getTimestamp());
}
@Test
public void testQueueSourceInputInvalidMessage() {
MethodWrapper method = new DefaultMethodWrapper(QueueSourceStringTestFunction.class, "handler");
assertThrows(RuntimeException.class, () -> coerceRequest(method, "[a plain string]"));
}
@Test
public void testQueueSourceInputString() {
MethodWrapper method = new DefaultMethodWrapper(QueueSourceStringTestFunction.class, "handler");
ConnectorHubBatch<String > event = coerceRequest(method, "[\"a plain , comma string 1\",\"a plain , comma string 2\",\"a plain , comma string 3\"]");
assertFalse(event.getBatch().isEmpty());
assertEquals(3, event.getBatch().size());
assertEquals("a plain , comma string 1", event.getBatch().get(0));
}
@Test
public void testQueueSourceInputObject() {
Animal animal = new Animal("cat", 2);
MethodWrapper method = new DefaultMethodWrapper(QueueSourceObjectTestFunction.class, "handler");
ConnectorHubBatch<String > event = coerceRequest(method, "[{\"name\": \"cat\",\"age\":2}]");
assertFalse(event.getBatch().isEmpty());
assertEquals(1, event.getBatch().size());
assertEquals(animal, event.getBatch().get(0));
}
@Test
public void testHeaders() {
MethodWrapper method = new DefaultMethodWrapper(QueueSourceObjectTestFunction.class, "handler");
when(requestinvocationContext.getRequestHeaders()).thenReturn(Headers.emptyHeaders().addHeader("foo", "bar"));
ConnectorHubBatch<String > event = coerceRequest(method, "[{\"name\": \"cat\",\"age\":2}]");
assertEquals("bar", event.getHeaders().get("foo").get());
}
@Test
public void testEmptyHeaders() {
MethodWrapper method = new DefaultMethodWrapper(QueueSourceObjectTestFunction.class, "handler");
when(requestinvocationContext.getRequestHeaders()).thenReturn(Headers.emptyHeaders());
ConnectorHubBatch<String > event = coerceRequest(method, "[{\"name\": \"cat\",\"age\":2}]");
assertEquals(0, event.getHeaders().asMap().size());
}
private ConnectorHubBatch coerceRequest(MethodWrapper method, String body) {
ByteArrayInputStream is = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
InputEvent inputEvent = new ReadOnceInputEvent(is, Headers.emptyHeaders(), "call", Instant.now());
return coercion.tryCoerceParam(requestinvocationContext, 0, inputEvent, method).orElseThrow(RuntimeException::new);
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/coercion/APIGatewayCoercionTest.java | fn-events/src/test/java/com/fnproject/events/coercion/APIGatewayCoercionTest.java | package com.fnproject.events.coercion;
import static com.fnproject.events.coercion.APIGatewayCoercion.OM_KEY;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fnproject.events.input.APIGatewayRequestEvent;
import com.fnproject.events.output.APIGatewayResponseEvent;
import com.fnproject.events.testfns.Car;
import com.fnproject.events.testfns.apigatewayfns.APIGatewayTestFunction;
import com.fnproject.events.testfns.Animal;
import com.fnproject.events.testfns.apigatewayfns.GrandChildGatewayTestFunction;
import com.fnproject.events.testfns.apigatewayfns.ListAPIGatewayTestFunction;
import com.fnproject.events.testfns.apigatewayfns.StringAPIGatewayTestFunction;
import com.fnproject.events.testfns.apigatewayfns.UncheckedAPIGatewayTestFunction;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.api.InvocationContext;
import com.fnproject.fn.api.MethodWrapper;
import com.fnproject.fn.api.OutputEvent;
import com.fnproject.fn.api.RuntimeContext;
import com.fnproject.fn.runtime.DefaultFunctionInvocationContext;
import com.fnproject.fn.runtime.DefaultMethodWrapper;
import com.fnproject.fn.runtime.FunctionRuntimeContext;
import com.fnproject.fn.runtime.ReadOnceInputEvent;
import org.junit.Before;
import org.junit.Test;
public class APIGatewayCoercionTest {
private APIGatewayCoercion coercion;
private InvocationContext requestinvocationContext;
private DefaultFunctionInvocationContext responseInvocationContext;
@Before
public void setUp() {
coercion = APIGatewayCoercion.instance();
requestinvocationContext = mock(InvocationContext.class);
RuntimeContext runtimeContext = mock(RuntimeContext.class);
ObjectMapper mapper = new ObjectMapper();
when(runtimeContext.getAttribute(OM_KEY, ObjectMapper.class)).thenReturn(Optional.of(mapper));
when(requestinvocationContext.getRuntimeContext()).thenReturn(runtimeContext);
}
@Test
public void testReturnEmptyWhenNotAPIGatewayClass() {
MethodWrapper method = new DefaultMethodWrapper(APIGatewayCoercionTest.class, "testMethod");
Headers headers = Headers.emptyHeaders();
when(requestinvocationContext.getRequestHeaders()).thenReturn(headers);
ByteArrayInputStream is = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
InputEvent inputEvent = new ReadOnceInputEvent(is, Headers.emptyHeaders(), "call", Instant.now());
Optional<APIGatewayRequestEvent> requestEvent = coercion.tryCoerceParam(requestinvocationContext, 0, inputEvent, method);
assertFalse(requestEvent.isPresent());
}
@Test
public void testRequestHeaders() {
MethodWrapper method = new DefaultMethodWrapper(StringAPIGatewayTestFunction.class, "handler");
Headers h = Headers.emptyHeaders()
.setHeader("H1", "h1val")
.setHeader("Fn-Http-H-", "ignored")
.setHeader("Fn-Http-H-A", "b")
.setHeader("Fn-Http-H-mv", "c", "d");
APIGatewayRequestEvent<String> requestEvent = coerceRequest(method, h, "");
assertEquals("b", (requestEvent.getHeaders().get("A")).get());
assertEquals("c", (requestEvent.getHeaders().getAllValues("Mv")).get(0));
assertEquals("d", (requestEvent.getHeaders().getAllValues("Mv")).get(1));
assertFalse(requestEvent.getHeaders().get("H1").isPresent());
}
@Test
public void testRequestUrl() {
MethodWrapper method = new DefaultMethodWrapper(StringAPIGatewayTestFunction.class, "handler");
Headers h = Headers.emptyHeaders()
.setHeader("Fn-Http-Request-Url", "/v2/employee/123?param1=value%20with%20spaces");
APIGatewayRequestEvent<String> requestEvent = coerceRequest(method, h, "");
assertEquals("/v2/employee/123?param1=value%20with%20spaces", requestEvent.getRequestUrl());
}
@Test
public void testRequestMethod() {
MethodWrapper method = new DefaultMethodWrapper(StringAPIGatewayTestFunction.class, "handler");
Headers h = Headers.emptyHeaders()
.setHeader("Fn-Http-Method", "PATCH");
APIGatewayRequestEvent requestEvent = coerceRequest(method, h, "");
assertEquals("PATCH", requestEvent.getMethod());
}
@Test
public void testQueryParameters() {
MethodWrapper method = new DefaultMethodWrapper(StringAPIGatewayTestFunction.class, "handler");
Headers h = Headers.emptyHeaders()
.setHeader("Fn-Http-Request-Url", "/v2/employee/123?param1=value%20with%20spaces&repeat=2&repeat=3");
APIGatewayRequestEvent requestEvent = coerceRequest(method, h, "");
assertEquals("value with spaces", requestEvent.getQueryParameters().get("param1").get());
}
@Test
public void testQueryRepeatedParameters() {
MethodWrapper method = new DefaultMethodWrapper(StringAPIGatewayTestFunction.class, "handler");
Headers h = Headers.emptyHeaders()
.setHeader("Fn-Http-Request-Url", "/v2/employee/123?param1=value%20with%20spaces&repeat=2&repeat=3");
APIGatewayRequestEvent requestEvent = coerceRequest(method, h, "");
assertEquals("2", (requestEvent.getQueryParameters().getValues("repeat")).get(0));
assertEquals("3", (requestEvent.getQueryParameters().getValues("repeat")).get(1));
}
@Test
public void testRequestStringBody() {
MethodWrapper method = new DefaultMethodWrapper(StringAPIGatewayTestFunction.class, "handler");
APIGatewayRequestEvent requestEvent = coerceRequest(method, "simple string");
assertEquals("simple string", requestEvent.getBody());
}
@Test
public void testListObjectRequestBody() {
MethodWrapper method = new DefaultMethodWrapper(ListAPIGatewayTestFunction.class, "handler");
APIGatewayRequestEvent requestEvent = coerceRequest(method, "[{\"name\":\"Spot\",\"age\":6}]");
assertEquals("Spot", ((List<Animal>) requestEvent.getBody()).get(0).getName());
assertEquals(6, ((List<Animal>) requestEvent.getBody()).get(0).getAge());
}
@Test
public void testSingleObjectRequestBody() {
MethodWrapper method = new DefaultMethodWrapper(APIGatewayTestFunction.class, "handler");
APIGatewayRequestEvent requestEvent = coerceRequest(method, "{\"name\":\"Spot\",\"age\":6}");
assertEquals("Spot", ((Animal) requestEvent.getBody()).getName());
assertEquals(6, ((Animal) requestEvent.getBody()).getAge());
}
@Test
public void testUncheckedHandler() {
MethodWrapper method = new DefaultMethodWrapper(UncheckedAPIGatewayTestFunction.class, "handler");
Headers h = Headers.emptyHeaders().setHeader("H1", "h1val");
APIGatewayRequestEvent requestEvent = coerceRequest(method, h, "{\"name\":\"Spot\",\"age\":6}");
assertEquals("{\"name\":\"Spot\",\"age\":6}", requestEvent.getBody());
}
@Test
public void testFailureToParseIsUserFriendlyError() {
MethodWrapper method = new DefaultMethodWrapper(APIGatewayTestFunction.class, "handler");
RuntimeException exception = assertThrows(RuntimeException.class, () -> coerceRequest(method, "INVALID JSON"));
assertEquals("Failed to coerce event to user function parameter type [simple type, class com.fnproject.events.testfns.Animal]", exception.getMessage());
assertTrue(exception.getCause().getMessage().startsWith("Unrecognized token 'INVALID':"));
}
@Test
public void testCoerceForGrandChild() {
MethodWrapper method = new DefaultMethodWrapper(GrandChildGatewayTestFunction.class, "handler");
APIGatewayRequestEvent requestEvent = coerceRequest(method, "simple string");
assertEquals("simple string", requestEvent.getBody());
}
@Test
public void testReturnEmptyResponseWhenNotAPIGatewayClass() {
MethodWrapper method = new DefaultMethodWrapper(APIGatewayCoercionTest.class, "testMethod");
APIGatewayResponseEvent<String> responseEvent = new APIGatewayResponseEvent.Builder<String>().build();
Optional<OutputEvent> outputEvent = coercion.wrapFunctionResult(responseInvocationContext, method, responseEvent);
assertFalse(outputEvent.isPresent());
}
@Test
public void testResponseHeaders() {
Headers headers = Headers.emptyHeaders()
.addHeader("custom-header", "customValue")
.setHeaders(Collections.singletonMap("custom-header-2", Collections.singletonList("customValue2")));
APIGatewayResponseEvent<String> responseEvent = new APIGatewayResponseEvent.Builder<String>()
.headers(headers)
.build();
DefaultMethodWrapper method = new DefaultMethodWrapper(APIGatewayTestFunction.class, "handler");
Optional<OutputEvent> outputEvent = wrap(responseEvent, method);
assertTrue(outputEvent.isPresent());
assertEquals("customValue",
responseInvocationContext.getAdditionalResponseHeaders().get("Fn-Http-H-Custom-Header").get(0));
assertEquals("customValue2",
responseInvocationContext.getAdditionalResponseHeaders().get("Fn-Http-H-Custom-Header-2").get(0));
}
@Test
public void testResponseRepeatHeaders() {
Headers headers = Headers.emptyHeaders()
.addHeader("repeat", "1")
.addHeader("repeat", "2");
APIGatewayResponseEvent<String> responseEvent = new APIGatewayResponseEvent.Builder<String>()
.headers(headers)
.build();
DefaultMethodWrapper method = new DefaultMethodWrapper(APIGatewayTestFunction.class, "handler");
Optional<OutputEvent> outputEvent = wrap(responseEvent, method);
assertTrue(outputEvent.isPresent());
assertEquals("2",
responseInvocationContext.getAdditionalResponseHeaders().get("Fn-Http-H-Repeat").get(1));
assertEquals("1",
responseInvocationContext.getAdditionalResponseHeaders().get("Fn-Http-H-Repeat").get(0));
}
@Test
public void testResponseContentTypeDefaultString() {
APIGatewayResponseEvent<String> responseEvent = new APIGatewayResponseEvent.Builder<String>()
.build();
DefaultMethodWrapper method = new DefaultMethodWrapper(StringAPIGatewayTestFunction.class, "handler");
Optional<OutputEvent> outputEvent = wrap(responseEvent, method);
assertTrue(outputEvent.isPresent());
assertEquals("text/plain", outputEvent.get().getContentType().get());
}
@Test
public void testResponseContentTypeDefault() {
APIGatewayResponseEvent<Car> responseEvent = new APIGatewayResponseEvent.Builder<Car>()
.build();
DefaultMethodWrapper method = new DefaultMethodWrapper(APIGatewayTestFunction.class, "handler");
Optional<OutputEvent> outputEvent = wrap(responseEvent, method);
assertTrue(outputEvent.isPresent());
assertEquals("application/json", outputEvent.get().getContentType().get());
}
@Test
public void testResponseCustomContentType() {
Headers headers = Headers.emptyHeaders()
.addHeader("content-type", "application/octet-stream");
APIGatewayResponseEvent<String> responseEvent = new APIGatewayResponseEvent.Builder<String>()
.headers(headers)
.build();
DefaultMethodWrapper method = new DefaultMethodWrapper(APIGatewayTestFunction.class, "handler");
Optional<OutputEvent> outputEvent = wrap(responseEvent, method);
assertTrue(outputEvent.isPresent());
assertEquals("application/octet-stream", outputEvent.get().getContentType().get());
}
@Test
public void testResponseStatus() {
APIGatewayResponseEvent<String> responseEvent = new APIGatewayResponseEvent.Builder<String>()
.statusCode(200)
.build();
DefaultMethodWrapper method = new DefaultMethodWrapper(APIGatewayTestFunction.class, "handler");
Optional<OutputEvent> outputEvent = wrap(responseEvent, method);
assertTrue(outputEvent.isPresent());
assertEquals("200", responseInvocationContext.getAdditionalResponseHeaders().get("Fn-Http-Status").get(0));
}
@Test
public void testResponseStringBody() throws IOException {
APIGatewayResponseEvent<String> responseEvent = new APIGatewayResponseEvent.Builder<String>()
.body("string body")
.build();
DefaultMethodWrapper method = new DefaultMethodWrapper(StringAPIGatewayTestFunction.class, "handler");
Optional<OutputEvent> outputEvent = wrap(responseEvent, method);
assertTrue(outputEvent.isPresent());
String actual = writeToString(outputEvent.get());
assertEquals("string body", actual);
}
@Test
public void testResponseObjectBody() throws IOException {
Car car = new Car("ford", 4);
APIGatewayResponseEvent<Car> responseEvent = new APIGatewayResponseEvent.Builder<Car>()
.body(car)
.build();
DefaultMethodWrapper method = new DefaultMethodWrapper(APIGatewayTestFunction.class, "handler");
Optional<OutputEvent> outputEvent = wrap(responseEvent, method);
assertTrue(outputEvent.isPresent());
String actual = writeToString(outputEvent.get());
assertEquals("{\"brand\":\"ford\",\"wheels\":4}", actual);
}
@Test
public void testResponseListBody() throws IOException {
Car car = new Car("ford", 4);
APIGatewayResponseEvent<List<Car>> responseEvent = new APIGatewayResponseEvent.Builder<List<Car>>()
.body(Collections.singletonList(car))
.build();
DefaultMethodWrapper method = new DefaultMethodWrapper(APIGatewayTestFunction.class, "handler");
Optional<OutputEvent> outputEvent = wrap(responseEvent, method);
assertTrue(outputEvent.isPresent());
String actual = writeToString(outputEvent.get());
assertEquals("[{\"brand\":\"ford\",\"wheels\":4}]", actual);
}
@Test
public void testResponseStringNullBody() {
APIGatewayResponseEvent<String> responseEvent = new APIGatewayResponseEvent.Builder<String>()
.build();
DefaultMethodWrapper method = new DefaultMethodWrapper(StringAPIGatewayTestFunction.class, "handler");
Optional<OutputEvent> outputEvent = wrap(responseEvent, method);
assertTrue(outputEvent.isPresent());
assertEquals("text/plain", outputEvent.get().getContentType().get());
}
@Test
public void testResponseUncheckedBody() {
APIGatewayResponseEvent<String> responseEvent = new APIGatewayResponseEvent.Builder<String>()
.build();
DefaultMethodWrapper method = new DefaultMethodWrapper(UncheckedAPIGatewayTestFunction.class, "handler");
Optional<OutputEvent> outputEvent = wrap(responseEvent, method);
assertTrue(outputEvent.isPresent());
assertEquals("text/plain", outputEvent.get().getContentType().get());
}
@Test
public void testNullResponse() {
DefaultMethodWrapper method = new DefaultMethodWrapper(UncheckedAPIGatewayTestFunction.class, "handler");
Optional<OutputEvent> outputEvent = wrap(null, method);
assertFalse(outputEvent.isPresent());
}
private Optional<OutputEvent> wrap(APIGatewayResponseEvent<?> responseEvent, MethodWrapper method) {
Headers requestHeaders = Headers.emptyHeaders();
InputEvent inputEvent = mock(InputEvent.class);
when(inputEvent.getHeaders()).thenReturn(requestHeaders);
FunctionRuntimeContext frc = new FunctionRuntimeContext(method, new HashMap<>());
responseInvocationContext = new DefaultFunctionInvocationContext(frc, inputEvent);
return coercion.wrapFunctionResult(responseInvocationContext, method, responseEvent);
}
private static String writeToString(OutputEvent oe) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
oe.writeToOutput(baos);
return baos.toString("UTF-8");
}
private APIGatewayRequestEvent coerceRequest(MethodWrapper method, Headers headers, String body) {
when(requestinvocationContext.getRequestHeaders()).thenReturn(headers);
ByteArrayInputStream is = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
InputEvent inputEvent = new ReadOnceInputEvent(is, Headers.emptyHeaders(), "call", Instant.now());
return coercion.tryCoerceParam(requestinvocationContext, 0, inputEvent, method).orElseThrow(RuntimeException::new);
}
private APIGatewayRequestEvent coerceRequest(MethodWrapper method, String body) {
return coerceRequest(method, Headers.emptyHeaders(), body);
}
public String testMethod(List<Animal> ss) {
// This method isn't actually called, it only exists to have its parameter types examined by the JacksonCoercion
return ss.get(0).getName();
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/coercion/NotificationCoercionTest.java | fn-events/src/test/java/com/fnproject/events/coercion/NotificationCoercionTest.java | package com.fnproject.events.coercion;
import static com.fnproject.events.coercion.APIGatewayCoercion.OM_KEY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Optional;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fnproject.events.input.NotificationMessage;
import com.fnproject.events.testfns.Animal;
import com.fnproject.events.testfns.notification.NotificationObjectTestFunction;
import com.fnproject.events.testfns.notification.NotificationStringTestFunction;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.api.InvocationContext;
import com.fnproject.fn.api.MethodWrapper;
import com.fnproject.fn.api.RuntimeContext;
import com.fnproject.fn.runtime.DefaultMethodWrapper;
import com.fnproject.fn.runtime.ReadOnceInputEvent;
import org.junit.Before;
import org.junit.Test;
public class NotificationCoercionTest {
private NotificationCoercion coercion;
private InvocationContext requestinvocationContext;
@Before
public void setUp() {
coercion = NotificationCoercion.instance();
requestinvocationContext = mock(InvocationContext.class);
RuntimeContext runtimeContext = mock(RuntimeContext.class);
ObjectMapper mapper = new ObjectMapper();
when(runtimeContext.getAttribute(OM_KEY, ObjectMapper.class)).thenReturn(Optional.of(mapper));
when(requestinvocationContext.getRuntimeContext()).thenReturn(runtimeContext);
}
@Test
public void testReturnEmptyWhenNotNotificationClass() {
MethodWrapper method = new DefaultMethodWrapper(APIGatewayCoercionTest.class, "testMethod");
Headers headers = Headers.emptyHeaders();
when(requestinvocationContext.getRequestHeaders()).thenReturn(headers);
ByteArrayInputStream is = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
InputEvent inputEvent = new ReadOnceInputEvent(is, Headers.emptyHeaders(), "call", Instant.now());
Optional<?> batch = coercion.tryCoerceParam(requestinvocationContext, 0, inputEvent, method);
assertFalse(batch.isPresent());
}
@Test
public void testNotificationObjectInput() {
MethodWrapper method = new DefaultMethodWrapper(NotificationObjectTestFunction.class, "handler");
NotificationMessage<Animal> event = coerceRequest(method, "{\"name\":\"foo\",\"age\":3}");
assertEquals(3, event.getContent().getAge());
assertEquals("foo", event.getContent().getName());
}
@Test
public void testNotificationStringInput() {
MethodWrapper method = new DefaultMethodWrapper(NotificationStringTestFunction.class, "handler");
NotificationMessage<String> event = coerceRequest(method, "a plain string");
assertEquals("a plain string", event.getContent());
}
@Test
public void testNotificationStringInputEmpty() {
MethodWrapper method = new DefaultMethodWrapper(NotificationStringTestFunction.class, "handler");
NotificationMessage<String> event = coerceRequest(method, "");
assertEquals("", event.getContent());
}
@Test
public void testHeaders() {
MethodWrapper method = new DefaultMethodWrapper(NotificationObjectTestFunction.class, "handler");
when(requestinvocationContext.getRequestHeaders()).thenReturn(Headers.emptyHeaders().addHeader("foo", "bar"));
NotificationMessage<String > event = coerceRequest(method, "{\"name\": \"cat\",\"age\":2}");
assertEquals("bar", event.getHeaders().get("foo").get());
}
@Test
public void testEmptyHeaders() {
MethodWrapper method = new DefaultMethodWrapper(NotificationObjectTestFunction.class, "handler");
when(requestinvocationContext.getRequestHeaders()).thenReturn(Headers.emptyHeaders());
NotificationMessage<String > event = coerceRequest(method, "{\"name\": \"cat\",\"age\":2}");
assertEquals(0, event.getHeaders().asMap().size());
}
private NotificationMessage coerceRequest(MethodWrapper method, String body) {
ByteArrayInputStream is = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
InputEvent inputEvent = new ReadOnceInputEvent(is, Headers.emptyHeaders(), "call", Instant.now());
return coercion.tryCoerceParam(requestinvocationContext, 0, inputEvent, method).orElseThrow(RuntimeException::new);
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/coercion/jackson/Base64ToTypeDeserializerTest.java | fn-events/src/test/java/com/fnproject/events/coercion/jackson/Base64ToTypeDeserializerTest.java | package com.fnproject.events.coercion.jackson;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.fnproject.events.input.sch.StreamingData;
import com.fnproject.events.testfns.Animal;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
public class Base64ToTypeDeserializerTest {
private final ObjectMapper mapper = new ObjectMapper();
// Helpers
private static String b64(String s) {
return Base64.getEncoder().encodeToString(s.getBytes(StandardCharsets.UTF_8));
}
private static String animalJson(String name, int age) {
return "{\"name\":\"" + name + "\",\"age\":" + age + "}";
}
@Test
public void testDecodeBase64JsonIntoPojo() throws Exception {
String valueB64 = b64(animalJson("Felix", 2));
String json = "{ \"stream\":\"s\", \"partition\":\"p\", \"key\":\"k\", \"value\":\"" + valueB64 + "\", \"offset\":\"o\" }";
StreamingData<Animal> sd = mapper.readValue(json, new TypeReference<StreamingData<Animal>>() {
});
assertThat(sd.getValue(), instanceOf(Animal.class));
assertEquals("Felix", sd.getValue().getName());
assertEquals(2, sd.getValue().getAge());
}
@Test
public void testDecodeBase64TextIntoString() throws Exception {
String valueB64 = b64("hello world");
String json = "{ \"stream\":\"s\", \"partition\":\"p\", \"key\":\"k\", \"value\":\"" + valueB64 + "\", \"offset\":\"o\" }";
StreamingData<String> sd = mapper.readValue(json, new TypeReference<StreamingData<String>>() {
});
assertEquals("hello world", sd.getValue());
}
@Test
public void testPassThroughNonBase64StringForStringTarget() throws Exception {
String json = "{ \"stream\":\"s\", \"partition\":\"p\", \"key\":\"k\", \"value\":\"not-base64$\", \"offset\":\"o\" }";
StreamingData<String> sd = mapper.readValue(json, new TypeReference<StreamingData<String>>() {
});
assertEquals("not-base64$", sd.getValue());
}
@Test
public void testInterpretPlainJsonStringWhenNotBase64() throws Exception {
// value is a string that contains JSON; not base64
String inner = animalJson("Buddy", 1);
String json = "{ \"stream\":\"s\", \"partition\":\"p\", \"key\":\"k\", \"value\":\"" + inner.replace("\"", "\\\"") + "\", \"offset\":\"o\" }";
StreamingData<Animal> sd = mapper.readValue(json, new TypeReference<StreamingData<Animal>>() {
});
assertThat(sd.getValue(), instanceOf(Animal.class));
assertEquals("Buddy", sd.getValue().getName());
assertEquals(1, sd.getValue().getAge());
}
@Test
public void testNonStringValueDelegatesNormally() throws Exception {
// The value is already a JSON object (not a string). The deserializer should delegate to normal binding.
String json = "{ \"stream\":\"s\", \"partition\":\"p\", \"key\":\"k\", \"value\": " + animalJson("Milo", 3) + ", \"offset\":\"o\" }";
StreamingData<Animal> sd = mapper.readValue(json, new TypeReference<StreamingData<Animal>>() {
});
assertThat(sd.getValue(), instanceOf(Animal.class));
assertEquals("Milo", sd.getValue().getName());
assertEquals(3, sd.getValue().getAge());
}
@Test
public void testNullValueReturnsNull() throws Exception {
String json = "{ \"stream\":\"s\", \"partition\":\"p\", \"key\":\"k\", \"value\": null, \"offset\":\"o\" }";
StreamingData<Animal> sd = mapper.readValue(json, new TypeReference<StreamingData<Animal>>() {
});
assertNull(sd.getValue());
}
@Test
public void testResolveTypeFromEnclosingGenericInCollection() throws Exception {
String v1 = b64(animalJson("Felix", 1));
String v2 = b64(animalJson("Buddy", 2));
String json = "[ " +
"{ \"stream\":\"s\", \"partition\":\"p\", \"key\":\"k1\", \"value\":\"" + v1 + "\", \"offset\":\"o1\" }," +
"{ \"stream\":\"s\", \"partition\":\"p\", \"key\":\"k2\", \"value\":\"" + v2 + "\", \"offset\":\"o2\" }" +
"]";
List<StreamingData<Animal>> list = mapper.readValue(
json, new TypeReference<List<StreamingData<Animal>>>() {
});
assertEquals(2, list.size());
assertThat(list.get(0).getValue(), instanceOf(Animal.class));
assertEquals("Felix", list.get(0).getValue().getName());
assertThat(list.get(1).getValue(), instanceOf(Animal.class));
assertEquals("Buddy", list.get(1).getValue().getName());
}
@Test
public void testInvalidNonJsonForNonStringTargetYieldsMismatch() {
// Not base64; not JSON; not coercible to Animal -> should surface a MismatchedInputException
String json = "{ \"stream\":\"s\", \"partition\":\"p\", \"key\":\"k\", \"value\":\"not-json-or-base64\", \"offset\":\"o\" }";
assertThrows(MismatchedInputException.class, () -> mapper.readValue(json, new TypeReference<StreamingData<Animal>>() {}));
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/output/APIGatewayResponseEventTest.java | fn-events/src/test/java/com/fnproject/events/output/APIGatewayResponseEventTest.java | package com.fnproject.events.output;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.util.Collections;
import java.util.List;
import com.fnproject.events.testfns.Animal;
import com.fnproject.fn.api.Headers;
import org.junit.Test;
public class APIGatewayResponseEventTest {
@Test
public void testGetBody() {
String body = "body";
APIGatewayResponseEvent<String> event = new APIGatewayResponseEvent.Builder<String>().body(body).build();
assertEquals("body", event.getBody());
}
@Test
public void testGetBodyAsObject() {
Animal response = new Animal("body", 1);
APIGatewayResponseEvent<Animal> event = new APIGatewayResponseEvent.Builder<Animal>().body(response).build();
assertEquals(response, event.getBody());
}
@Test
public void testGetBodyAsList() {
Animal response = new Animal("body", 1);
List<Animal> list = Collections.singletonList(response);
APIGatewayResponseEvent<List<Animal>> event = new APIGatewayResponseEvent.Builder<List<Animal>>().body(list).build();
assertEquals(list, event.getBody());
}
@Test
public void testGetNullBody() {
APIGatewayResponseEvent<List<Animal>> event = new APIGatewayResponseEvent.Builder<List<Animal>>().body(null).build();
assertNull(event.getBody());
}
@Test
public void testGetStatus() {
APIGatewayResponseEvent<String> event = new APIGatewayResponseEvent.Builder<String>().statusCode(201).build();
assertEquals(Integer.valueOf(201), event.getStatus());
}
@Test
public void testGetHeaders() {
Headers headers = Headers.emptyHeaders().addHeader("foo","bar");
APIGatewayResponseEvent<String> event = new APIGatewayResponseEvent.Builder<String>().headers(headers).build();
assertEquals(headers, event.getHeaders());
}
@Test
public void testGetRepeatedHeaders() {
Headers headers = Headers.emptyHeaders().addHeader("repeated", "foo").addHeader("repeated", "bar");
APIGatewayResponseEvent<String> event = new APIGatewayResponseEvent.Builder<String>()
.headers(headers)
.build();
assertEquals("foo", event.getHeaders().getAllValues("repeated").get(0));
assertEquals("bar", event.getHeaders().getAllValues("repeated").get(1));
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/NotificationFunction.java | fn-events/src/main/java/com/fnproject/events/NotificationFunction.java | package com.fnproject.events;
import com.fnproject.events.coercion.NotificationCoercion;
import com.fnproject.events.input.NotificationMessage;
import com.fnproject.fn.api.FnConfiguration;
import com.fnproject.fn.api.RuntimeContext;
public abstract class NotificationFunction<T> {
@FnConfiguration
public void configure(RuntimeContext ctx){
ctx.addInputCoercion(NotificationCoercion.instance());
}
public abstract void handler(NotificationMessage<T> notification);
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/ConnectorHubFunction.java | fn-events/src/main/java/com/fnproject/events/ConnectorHubFunction.java | package com.fnproject.events;
import com.fnproject.events.coercion.ConnectorHubCoercion;
import com.fnproject.events.input.ConnectorHubBatch;
import com.fnproject.fn.api.FnConfiguration;
import com.fnproject.fn.api.RuntimeContext;
public abstract class ConnectorHubFunction<T> {
@FnConfiguration
public void configure(RuntimeContext ctx){
ctx.addInputCoercion(ConnectorHubCoercion.instance());
}
public abstract void handler(ConnectorHubBatch<T> connectorHubBatch);
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/APIGatewayFunction.java | fn-events/src/main/java/com/fnproject/events/APIGatewayFunction.java | package com.fnproject.events;
import com.fnproject.events.coercion.APIGatewayCoercion;
import com.fnproject.events.input.APIGatewayRequestEvent;
import com.fnproject.events.output.APIGatewayResponseEvent;
import com.fnproject.fn.api.FnConfiguration;
import com.fnproject.fn.api.RuntimeContext;
public abstract class APIGatewayFunction<T, U> {
@FnConfiguration
public void configure(RuntimeContext ctx){
ctx.addInputCoercion(APIGatewayCoercion.instance());
ctx.addOutputCoercion(APIGatewayCoercion.instance());
}
public abstract APIGatewayResponseEvent<U> handler(APIGatewayRequestEvent<T> requestEvent);
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/input/ConnectorHubBatch.java | fn-events/src/main/java/com/fnproject/events/input/ConnectorHubBatch.java | package com.fnproject.events.input;
import java.util.List;
import java.util.Objects;
import com.fnproject.fn.api.Headers;
public class ConnectorHubBatch<T> {
private final Headers headers;
private final List<T> batch;
public ConnectorHubBatch(List<T> batch, Headers headers) {
this.batch = batch;
this.headers = headers;
}
public List<T> getBatch() {
return batch;
}
public Headers getHeaders() {
return headers;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ConnectorHubBatch<?> that = (ConnectorHubBatch<?>) o;
return Objects.equals(headers, that.headers) && Objects.equals(batch, that.batch);
}
@Override
public int hashCode() {
return Objects.hash(headers, batch);
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/input/NotificationMessage.java | fn-events/src/main/java/com/fnproject/events/input/NotificationMessage.java | package com.fnproject.events.input;
import java.util.Objects;
import com.fnproject.fn.api.Headers;
public class NotificationMessage<T> {
private final T content;
private final Headers headers;
public NotificationMessage(T content, Headers headers) {
this.content = content;
this.headers = headers;
}
public T getContent() {
return content;
}
public Headers getHeaders() {
return headers;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NotificationMessage<?> message = (NotificationMessage<?>) o;
return Objects.equals(content, message.content) && Objects.equals(headers, message.headers);
}
@Override
public int hashCode() {
return Objects.hash(content, headers);
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/input/APIGatewayRequestEvent.java | fn-events/src/main/java/com/fnproject/events/input/APIGatewayRequestEvent.java | package com.fnproject.events.input;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.QueryParameters;
@JsonIgnoreProperties(ignoreUnknown = true)
public class APIGatewayRequestEvent<T> {
private final QueryParameters queryParameters;
private final T body;
private final String method;
private final String requestUrl;
private final Headers headers;
public APIGatewayRequestEvent(QueryParameters queryParameters, T body, String method, String requestUrl, Headers headers) {
this.queryParameters = queryParameters;
this.body = body;
this.method = method;
this.requestUrl = requestUrl;
this.headers = headers;
}
public T getBody() {
return body;
}
public QueryParameters getQueryParameters() {
return queryParameters;
}
public String getMethod() {
return method;
}
public Headers getHeaders() {
return headers;
}
public String getRequestUrl() {
return requestUrl;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
APIGatewayRequestEvent<?> that = (APIGatewayRequestEvent<?>) o;
return Objects.equals(queryParameters, that.queryParameters) && Objects.equals(body, that.body) && Objects.equals(method, that.method) &&
Objects.equals(requestUrl, that.requestUrl) && Objects.equals(headers, that.headers);
}
@Override
public int hashCode() {
return Objects.hash(queryParameters, body, method, requestUrl, headers);
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/input/sch/Datapoint.java | fn-events/src/main/java/com/fnproject/events/input/sch/Datapoint.java | package com.fnproject.events.input.sch;
import java.util.Date;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public final class Datapoint {
private final Date timestamp;
private final Double value;
private final Integer count;
@JsonCreator
public Datapoint(
@JsonProperty("timestamp") Date timestamp,
@JsonProperty("value") Double value,
@JsonProperty("count") Integer count) {
this.timestamp = timestamp;
this.value = value;
this.count = count;
}
public Date getTimestamp() {
return timestamp;
}
public Double getValue() {
return value;
}
public Integer getCount() {
return count;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Datapoint datapoint = (Datapoint) o;
return Objects.equals(timestamp, datapoint.timestamp) && Objects.equals(value, datapoint.value) && Objects.equals(count, datapoint.count);
}
@Override
public int hashCode() {
return Objects.hash(timestamp, value, count);
}
@Override
public String toString() {
return "Datapoint{" +
"timestamp=" + timestamp +
", value=" + value +
", count=" + count +
'}';
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/input/sch/StreamingData.java | fn-events/src/main/java/com/fnproject/events/input/sch/StreamingData.java | package com.fnproject.events.input.sch;
import java.util.Date;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fnproject.events.coercion.jackson.Base64ToTypeDeserializer;
@JsonIgnoreProperties(ignoreUnknown = true)
public class StreamingData<T> {
private final String stream;
private final String partition;
private final String key;
private final T value;
private final String offset;
private final Date timestamp;
@JsonCreator
public StreamingData(
@JsonProperty("stream") String stream,
@JsonProperty("partition") String partition,
@JsonProperty("key") String key,
@JsonDeserialize(using = Base64ToTypeDeserializer.class) @JsonProperty("value") T value,
@JsonProperty("offset") String offset,
@JsonProperty("time") Date timestamp) {
this.stream = stream;
this.partition = partition;
this.key = key;
this.value = value;
this.offset = offset;
this.timestamp = timestamp;
}
public String getStream() {
return stream;
}
public String getPartition() {
return partition;
}
public String getKey() {
return key;
}
public T getValue() {
return value;
}
public Date getTimestamp() {
return timestamp;
}
public String getOffset() {
return offset;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StreamingData<?> that = (StreamingData<?>) o;
return Objects.equals(stream, that.stream) && Objects.equals(partition, that.partition) && Objects.equals(key, that.key) &&
Objects.equals(value, that.value) && Objects.equals(offset, that.offset) && Objects.equals(timestamp, that.timestamp);
}
@Override
public int hashCode() {
return Objects.hash(stream, partition, key, value, offset, timestamp);
}
@Override
public String toString() {
return "StreamingData{" +
"stream='" + stream + '\'' +
", partition='" + partition + '\'' +
", key='" + key + '\'' +
", value=" + value +
", offset='" + offset + '\'' +
", timestamp=" + timestamp +
'}';
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/input/sch/LoggingData.java | fn-events/src/main/java/com/fnproject/events/input/sch/LoggingData.java | package com.fnproject.events.input.sch;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class LoggingData {
private final String id;
private final String source;
private final String specversion;
private final String subject;
private final String type;
private final Map<String, String> data;
private final Map<String, String> oracle;
private final Date time;
@JsonCreator
public LoggingData(
@JsonProperty("id") String id,
@JsonProperty("source") String source,
@JsonProperty("specversion") String specversion,
@JsonProperty("subject") String subject,
@JsonProperty("type") String type,
@JsonProperty("data") Map<String, String> data,
@JsonProperty("oracle") Map<String, String> oracle,
@JsonProperty("time") Date time) {
this.id = id;
this.source = source;
this.specversion = specversion;
this.subject = subject;
this.type = type;
this.data = data;
this.oracle = oracle;
this.time = time;
}
public String getId() {
return id;
}
public String getSource() {
return source;
}
public String getSpecversion() {
return specversion;
}
public String getSubject() {
return subject;
}
public Map<String, String> getData() {
return data;
}
public Map<String, String> getOracle() {
return oracle;
}
public Date getTime() {
return time;
}
public String getType() {
return type;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LoggingData that = (LoggingData) o;
return Objects.equals(id, that.id) && Objects.equals(source, that.source) && Objects.equals(specversion, that.specversion) &&
Objects.equals(subject, that.subject) && Objects.equals(type, that.type) && Objects.equals(data, that.data) &&
Objects.equals(oracle, that.oracle) && Objects.equals(time, that.time);
}
@Override
public int hashCode() {
return Objects.hash(id, source, specversion, subject, type, data, oracle, time);
}
@Override
public String toString() {
return "LoggingData{" +
"id='" + id + '\'' +
", source='" + source + '\'' +
", specversion='" + specversion + '\'' +
", subject='" + subject + '\'' +
", type='" + type + '\'' +
", data=" + data +
", oracle=" + oracle +
", time=" + time +
'}';
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/input/sch/MetricData.java | fn-events/src/main/java/com/fnproject/events/input/sch/MetricData.java | package com.fnproject.events.input.sch;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public class MetricData {
private final String namespace;
private final String resourceGroup;
private final String compartmentId;
private final String name;
private final Map<String, String> dimensions;
private final Map<String, String> metadata;
private final List<Datapoint> datapoints;
@JsonCreator
public MetricData(
@JsonProperty("namespace") String namespace,
@JsonProperty("resourceGroup") String resourceGroup,
@JsonProperty("compartmentId") String compartmentId,
@JsonProperty("name") String name,
@JsonProperty("dimensions") Map<String, String> dimensions,
@JsonProperty("metadata") Map<String, String> metadata,
@JsonProperty("datapoints") List<Datapoint> datapoints) {
this.namespace = namespace;
this.resourceGroup = resourceGroup;
this.compartmentId = compartmentId;
this.name = name;
this.dimensions = dimensions;
this.metadata = metadata;
this.datapoints = datapoints;
}
public String getNamespace() {
return namespace;
}
public String getResourceGroup() {
return resourceGroup;
}
public String getCompartmentId() {
return compartmentId;
}
public String getName() {
return name;
}
public Map<String, String> getDimensions() {
return dimensions;
}
public Map<String, String> getMetadata() {
return metadata;
}
public List<Datapoint> getDatapoints() {
return datapoints;
}
@Override
public String toString() {
return "MetricData{" +
"namespace='" + namespace + '\'' +
", resourceGroup='" + resourceGroup + '\'' +
", compartmentId='" + compartmentId + '\'' +
", name='" + name + '\'' +
", dimensions=" + dimensions +
", metadata=" + metadata +
", datapoints=" + datapoints +
'}';
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/mapper/APIGatewayRequestEventMapper.java | fn-events/src/main/java/com/fnproject/events/mapper/APIGatewayRequestEventMapper.java | package com.fnproject.events.mapper;
import com.fnproject.events.input.APIGatewayRequestEvent;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.QueryParameters;
import com.fnproject.fn.api.httpgateway.HTTPGatewayContext;
import com.fnproject.fn.runtime.httpgateway.QueryParametersImpl;
public class APIGatewayRequestEventMapper implements ApiGatewayRequestMapper {
public <T> APIGatewayRequestEvent<T> toApiGatewayRequestEvent(HTTPGatewayContext context, T body) {
QueryParameters queryParameters =
context.getQueryParameters() != null ? context.getQueryParameters() : new QueryParametersImpl();
Headers headers =
context.getHeaders() != null ? context.getHeaders() : Headers.emptyHeaders();
return new APIGatewayRequestEvent<>(queryParameters, body, context.getMethod(), context.getRequestURL(), headers);
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/mapper/ApiGatewayRequestMapper.java | fn-events/src/main/java/com/fnproject/events/mapper/ApiGatewayRequestMapper.java | package com.fnproject.events.mapper;
import com.fnproject.events.input.APIGatewayRequestEvent;
import com.fnproject.fn.api.httpgateway.HTTPGatewayContext;
public interface ApiGatewayRequestMapper {
<T> APIGatewayRequestEvent<T> toApiGatewayRequestEvent(HTTPGatewayContext context, T body);
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/coercion/NotificationCoercion.java | fn-events/src/main/java/com/fnproject/events/coercion/NotificationCoercion.java | package com.fnproject.events.coercion;
import static com.fnproject.events.coercion.Util.hasEventFnInHierarchy;
import static com.fnproject.events.coercion.Util.readBodyAsString;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Optional;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fnproject.events.NotificationFunction;
import com.fnproject.events.input.NotificationMessage;
import com.fnproject.fn.api.InputCoercion;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.api.InvocationContext;
import com.fnproject.fn.api.MethodWrapper;
public class NotificationCoercion implements InputCoercion<NotificationMessage<?>> {
private static final NotificationCoercion instance = new NotificationCoercion();
static final String OM_KEY = NotificationCoercion.class.getCanonicalName() + ".om";
public static NotificationCoercion instance() {
return instance;
}
private static ObjectMapper objectMapper(InvocationContext ctx) {
Optional<ObjectMapper> omo = ctx.getRuntimeContext().getAttribute(OM_KEY, ObjectMapper.class);
if (!omo.isPresent()) {
ObjectMapper om = new ObjectMapper();
ctx.getRuntimeContext().setAttribute(OM_KEY, om);
return om;
} else {
return omo.get();
}
}
@Override
public Optional<NotificationMessage<?>> tryCoerceParam(InvocationContext currentContext, int param, InputEvent input, MethodWrapper method) {
if (hasEventFnInHierarchy(method.getTargetClass().getSuperclass(), NotificationFunction.class)) {
Type type = method.getTargetMethod().getGenericParameterTypes()[param];
JavaType javaType = objectMapper(currentContext).constructType(type);
List<JavaType> requestGenerics = javaType.getBindings().getTypeParameters();
JavaType elementType = requestGenerics.get(0);
if (elementType.hasRawClass(String.class)) {
return Optional.of(new NotificationMessage(readBodyAsString(input), currentContext.getRequestHeaders()));
}
ObjectMapper mapper = objectMapper(currentContext);
Object messageContent = input.consumeBody(is -> {
try {
return mapper.readValue(is, elementType);
} catch (IOException e) {
throw coercionFailed(elementType, e);
}
});
return Optional.of(new NotificationMessage<>(messageContent, currentContext.getRequestHeaders()));
} else {
return Optional.empty();
}
}
private static RuntimeException coercionFailed(Type paramType, Throwable cause) {
return new RuntimeException("Failed to coerce event to user function parameter type " + paramType, cause);
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/coercion/Util.java | fn-events/src/main/java/com/fnproject/events/coercion/Util.java | package com.fnproject.events.coercion;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import com.fnproject.fn.api.InputEvent;
import org.apache.commons.io.IOUtils;
public class Util {
public static boolean hasEventFnInHierarchy(Class<?> targetClass, Class<?> eventClass) {
for (Class<?> c = targetClass; c != null; c = c.getSuperclass()) {
if (c == eventClass) return true;
}
return false;
}
static String readBodyAsString(InputEvent input) {
return input.consumeBody(is -> {
try {
return IOUtils.toString(is, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Error reading input as string", e);
}
});
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/coercion/APIGatewayCoercion.java | fn-events/src/main/java/com/fnproject/events/coercion/APIGatewayCoercion.java | package com.fnproject.events.coercion;
import static com.fnproject.events.coercion.Util.hasEventFnInHierarchy;
import static com.fnproject.events.coercion.Util.readBodyAsString;
import static com.fnproject.fn.api.OutputEvent.CONTENT_TYPE_HEADER;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Optional;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fnproject.events.APIGatewayFunction;
import com.fnproject.events.input.APIGatewayRequestEvent;
import com.fnproject.events.mapper.APIGatewayRequestEventMapper;
import com.fnproject.events.mapper.ApiGatewayRequestMapper;
import com.fnproject.events.output.APIGatewayResponseEvent;
import com.fnproject.fn.api.InputCoercion;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.api.InvocationContext;
import com.fnproject.fn.api.MethodWrapper;
import com.fnproject.fn.api.OutputCoercion;
import com.fnproject.fn.api.OutputEvent;
import com.fnproject.fn.runtime.httpgateway.FunctionHTTPGatewayContext;
public class APIGatewayCoercion implements InputCoercion<APIGatewayRequestEvent>, OutputCoercion {
private static final APIGatewayCoercion instance = new APIGatewayCoercion();
static final String OM_KEY = APIGatewayCoercion.class.getCanonicalName() + ".om";
private final ApiGatewayRequestMapper requestMapper;
public APIGatewayCoercion(ApiGatewayRequestMapper requestMapper) {
this.requestMapper = requestMapper;
}
private APIGatewayCoercion() {
requestMapper = new APIGatewayRequestEventMapper();
}
public static APIGatewayCoercion instance() {
return instance;
}
private static ObjectMapper objectMapper(InvocationContext ctx) {
Optional<ObjectMapper> omo = ctx.getRuntimeContext().getAttribute(OM_KEY, ObjectMapper.class);
if (!omo.isPresent()) {
ObjectMapper om = new ObjectMapper();
ctx.getRuntimeContext().setAttribute(OM_KEY, om);
return om;
} else {
return omo.get();
}
}
@Override
public Optional<APIGatewayRequestEvent> tryCoerceParam(InvocationContext currentContext, int param, InputEvent input, MethodWrapper method) {
if (hasEventFnInHierarchy(method.getTargetClass().getSuperclass(), APIGatewayFunction.class)) {
FunctionHTTPGatewayContext functionHTTPGatewayContext = new FunctionHTTPGatewayContext(currentContext);
Type type = method.getTargetMethod().getGenericParameterTypes()[param];
JavaType javaType = objectMapper(currentContext).constructType(type);
List<JavaType> requestGenerics = javaType.getBindings().getTypeParameters();
Object body;
if (!requestGenerics.isEmpty()) {
JavaType requestGeneric = requestGenerics.get(0);
if (requestGeneric.hasRawClass(String.class)) {
body = readBodyAsString(input);
} else {
ObjectMapper mapper = objectMapper(currentContext);
body = input.consumeBody(is -> {
try {
return mapper.readValue(is, requestGeneric);
} catch (IOException e) {
throw coercionFailed(requestGeneric, e);
}
});
}
} else {
body = readBodyAsString(input);
}
APIGatewayRequestEvent requestEvent = requestMapper.toApiGatewayRequestEvent(functionHTTPGatewayContext, body);
return Optional.of(requestEvent);
} else {
return Optional.empty();
}
}
@Override
public Optional<OutputEvent> wrapFunctionResult(InvocationContext currentContext, MethodWrapper method, Object value) {
if (!hasEventFnInHierarchy(method.getTargetClass().getSuperclass(), APIGatewayFunction.class) || value == null) {
return Optional.empty();
}
FunctionHTTPGatewayContext ctx = new FunctionHTTPGatewayContext(currentContext);
APIGatewayResponseEvent responseEvent = (APIGatewayResponseEvent) value;
String contentType = null;
if (responseEvent.getHeaders() != null) {
for (String key : responseEvent.getHeaders().asMap().keySet()) {
ctx.addResponseHeader(key, responseEvent.getHeaders().getAllValues(key));
}
Optional<String> userSetContentType = responseEvent.getHeaders().get(CONTENT_TYPE_HEADER);
if (userSetContentType.isPresent()) {
contentType = userSetContentType.get();
}
}
if (responseEvent.getStatus() != null) {
ctx.setStatusCode(responseEvent.getStatus());
}
Optional<Object> body = Optional.ofNullable(responseEvent.getBody());
Type gs = method.getTargetClass().getGenericSuperclass();
if (gs instanceof ParameterizedType) {
Type responseGeneric = ((ParameterizedType) gs).getActualTypeArguments()[1]; // response type param
JavaType responseType = TypeFactory
.defaultInstance()
.constructType(responseGeneric);
if (responseType.hasRawClass(String.class)) {
if (contentType == null) {
contentType = "text/plain";
}
return Optional.of(OutputEvent.fromBytes(((String) body.orElse("")).getBytes(), OutputEvent.Status.Success, contentType));
}
if (contentType == null) {
contentType = "application/json";
}
try {
return Optional.of(OutputEvent.fromBytes(objectMapper(currentContext).writeValueAsBytes(body.orElse("")), OutputEvent.Status.Success, contentType));
} catch (JsonProcessingException e) {
throw new RuntimeException("Failed to render response to JSON", e);
}
} else {
if (contentType == null) {
contentType = "text/plain";
}
return Optional.of(OutputEvent.fromBytes(((String) body.orElse("")).getBytes(), OutputEvent.Status.Success, contentType));
}
}
private static RuntimeException coercionFailed(Type paramType, Throwable cause) {
return new RuntimeException("Failed to coerce event to user function parameter type " + paramType, cause);
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/coercion/ConnectorHubCoercion.java | fn-events/src/main/java/com/fnproject/events/coercion/ConnectorHubCoercion.java | package com.fnproject.events.coercion;
import static com.fnproject.events.coercion.Util.hasEventFnInHierarchy;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Optional;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fnproject.events.ConnectorHubFunction;
import com.fnproject.events.input.ConnectorHubBatch;
import com.fnproject.fn.api.InputCoercion;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.api.InvocationContext;
import com.fnproject.fn.api.MethodWrapper;
public class ConnectorHubCoercion implements InputCoercion<ConnectorHubBatch<?>> {
private static final ConnectorHubCoercion instance = new ConnectorHubCoercion();
static final String OM_KEY = ConnectorHubCoercion.class.getCanonicalName() + ".om";
public static ConnectorHubCoercion instance() {
return instance;
}
private static ObjectMapper objectMapper(InvocationContext ctx) {
Optional<ObjectMapper> omo = ctx.getRuntimeContext().getAttribute(OM_KEY, ObjectMapper.class);
if (!omo.isPresent()) {
ObjectMapper om = new ObjectMapper();
ctx.getRuntimeContext().setAttribute(OM_KEY, om);
return om;
} else {
return omo.get();
}
}
@Override
public Optional<ConnectorHubBatch<?>> tryCoerceParam(InvocationContext currentContext, int param, InputEvent input, MethodWrapper method) {
if (hasEventFnInHierarchy(method.getTargetClass().getSuperclass(), ConnectorHubFunction.class)) {
Type type = method.getTargetMethod().getGenericParameterTypes()[param];
JavaType javaType = objectMapper(currentContext).constructType(type);
List<JavaType> requestGenerics = javaType.getBindings().getTypeParameters();
ObjectMapper mapper = objectMapper(currentContext);
JavaType elementType = requestGenerics.get(0);
JavaType listType = mapper.getTypeFactory()
.constructCollectionType(List.class, elementType);
List<Object> batchedItems = input.consumeBody(is -> {
try {
return mapper.readValue(is, listType);
} catch (IOException e) {
throw coercionFailed(listType, e);
}
});
return Optional.of(new ConnectorHubBatch(batchedItems, currentContext.getRequestHeaders()));
} else {
return Optional.empty();
}
}
private static RuntimeException coercionFailed(Type paramType, Throwable cause) {
return new RuntimeException("Failed to coerce event to user function parameter type " + paramType, cause);
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/coercion/jackson/Base64ToTypeDeserializer.java | fn-events/src/main/java/com/fnproject/events/coercion/jackson/Base64ToTypeDeserializer.java | package com.fnproject.events.coercion.jackson;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.jsontype.TypeDeserializer;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Base64ToTypeDeserializer extends JsonDeserializer<Object> implements ContextualDeserializer {
private final JavaType targetType;
public Base64ToTypeDeserializer() {
this(null);
}
private Base64ToTypeDeserializer(JavaType targetType) {
this.targetType = targetType;
}
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
final JavaType t = (targetType != null) ? targetType : ctxt.constructType(Object.class);
final ObjectCodec codec = p.getCodec();
final ObjectMapper mapper = (codec instanceof ObjectMapper) ? (ObjectMapper) codec : new ObjectMapper();
JsonToken tok = p.currentToken();
if (tok == JsonToken.VALUE_NULL) {
return null;
}
// If we didn't receive a string, just let Jackson handle it normally (it might already be JSON)
if (tok != JsonToken.VALUE_STRING) {
return codec.readValue(p, t);
}
// We have a string; attempt base64 decode first
String v = p.getValueAsString();
if (v == null) {
return null;
}
try {
byte[] bytes = Base64.getDecoder().decode(v);
// If T is String, return textual content of decoded bytes
if (t.isTypeOrSubTypeOf(String.class)) {
return new String(bytes, StandardCharsets.UTF_8);
}
// Otherwise, treat decoded bytes as JSON and map to target type T
try (JsonParser jp = mapper.getFactory().createParser(bytes)) {
return mapper.readValue(jp, t);
}
} catch (IllegalArgumentException notBase64) {
// Not valid base64; fallback behavior
// If T is String, return the raw string as-is
if (t.isTypeOrSubTypeOf(String.class)) {
return v;
}
// Try to interpret the string itself as JSON for T
// (common case: string contains JSON payload but wasn't base64-encoded)
try {
return mapper.readValue(v, t);
} catch (IOException cannotParseAsJson) {
// Final fallback: wrap as JSON string and let Jackson coerce if possible (e.g., to primitive/wrapper)
// If not compatible, throw a Jackson-standard exception
try {
return mapper.readValue(mapper.writeValueAsBytes(v), t);
} catch (IOException e) {
return ctxt.reportInputMismatch(
t,
"Cannot coerce non-base64 string value into %s: %s",
t.toString(), e.getMessage()
);
}
}
}
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
JavaType t = (property != null) ? property.getType() : ctxt.getContextualType();
if (t == null || t.hasRawClass(Object.class)) {
// On constructor params this often mirrors property.getType(); if still Object,
// try the context’s parent (the bean being created) via getContextualType()
JavaType enclosing = ctxt.getContextualType();
if (enclosing != null && enclosing.containedTypeCount() > 0) {
t = enclosing.containedType(0); // StreamingData<T> -> T
}
if (t == null || t.hasRawClass(Object.class)) {
t = ctxt.constructType(Object.class);
}
}
return new Base64ToTypeDeserializer(t);
}
@Override
public Object deserializeWithType(JsonParser p, DeserializationContext ctxt, TypeDeserializer typeDeserializer) throws IOException {
return deserialize(p, ctxt);
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/main/java/com/fnproject/events/output/APIGatewayResponseEvent.java | fn-events/src/main/java/com/fnproject/events/output/APIGatewayResponseEvent.java | package com.fnproject.events.output;
import com.fnproject.fn.api.Headers;
public class APIGatewayResponseEvent<T> {
private final T body;
private final Integer statusCode;
private final Headers headers;
private APIGatewayResponseEvent(T body, Integer statusCode, Headers headers) {
this.headers = headers;
this.body = body;
this.statusCode = statusCode;
}
public static class Builder<T> {
private T body;
private Integer statusCode;
private Headers headers;
public Builder<T> body(T body) {
this.body = body;
return this;
}
public Builder<T> statusCode(int statusCode) {
this.statusCode = statusCode;
return this;
}
public Builder<T> headers(Headers headers) {
this.headers = headers;
return this;
}
public APIGatewayResponseEvent<T> build() {
return new APIGatewayResponseEvent<>(this.body, this.statusCode, this.headers);
}
}
public Integer getStatus() {
return statusCode;
}
public Headers getHeaders() {
return headers;
}
public T getBody() {
return body;
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-spring-cloud-function/src/test/java/com/fnproject/springframework/function/SpringCloudFunctionLoaderTest.java | fn-spring-cloud-function/src/test/java/com/fnproject/springframework/function/SpringCloudFunctionLoaderTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.springframework.function;
import com.fnproject.springframework.function.functions.SpringCloudMethod;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.cloud.function.context.catalog.BeanFactoryAwareFunctionRegistry;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class SpringCloudFunctionLoaderTest {
@Rule
public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
private SpringCloudFunctionLoader loader;
@Mock
private BeanFactoryAwareFunctionRegistry registry;
@Before
public void setUp() {
loader = new SpringCloudFunctionLoader(registry);
}
@Test
public void shouldLoadFunctionBeanCalledFunction() {
Function<Object, Object> fn = (x) -> x;
stubCatalogToReturnFunction(fn);
assertThat(getDiscoveredFunction().getTargetClass()).isEqualTo(fn.getClass());
}
@Test
public void shouldLoadConsumerBeanCalledConsumerIfFunctionNotAvailable() {
Consumer<Object> consumer = (x) -> {
};
stubCatalogToReturnConsumer(consumer);
assertThat(getDiscoveredFunction().getTargetClass()).isEqualTo(consumer.getClass());
}
@Test
public void shouldLoadSupplierBeanCalledSupplierIfNoConsumerOrFunctionAvailable() {
Supplier<Object> supplier = () -> "x";
stubCatalogToReturnSupplier(supplier);
assertThat(getDiscoveredFunction().getTargetClass()).isEqualTo(supplier.getClass());
}
@Test
public void shouldLoadUserSpecifiedSupplierInEnvVarOverDefaultFunction() {
String supplierBeanName = "mySupplier";
Supplier<Object> supplier = () -> "x";
Function<Object, Object> function = (x) -> x;
setSupplierEnvVar(supplierBeanName);
stubCatalogToReturnFunction(function);
stubCatalogToReturnSupplier(supplierBeanName, supplier);
assertThat(getDiscoveredFunction().getTargetClass()).isEqualTo(supplier.getClass());
}
@Test
public void shouldLoadUserSpecifiedConsumerInEnvVarOverDefaultFunction() {
String beanName = "myConsumer";
Consumer<Object> consumer = (x) -> {
};
Function<Object, Object> function = (x) -> x;
setConsumerEnvVar(beanName);
stubCatalogToReturnFunction(function);
stubCatalogToReturnConsumer(beanName, consumer);
assertThat(getDiscoveredFunction().getTargetClass()).isEqualTo(consumer.getClass());
}
@Test
public void shouldLoadUserSpecifiedFunctionInEnvVarOverDefaultFunction() {
String functionBeanName = "myFunction";
Function<Object, Object> defaultFunction = (x) -> x;
Function<Object, Object> myFunction = (x) -> x.toString();
setFunctionEnvVar(functionBeanName);
stubCatalogToReturnFunction(defaultFunction);
stubCatalogToReturnFunction(functionBeanName, myFunction);
assertThat(getDiscoveredFunction().getTargetClass()).isEqualTo(myFunction.getClass());
}
private void stubCatalogToReturnFunction(String beanName, Function<Object, Object> function) {
when(registry.lookup(Function.class, beanName)).thenReturn(function);
}
private void stubCatalogToReturnConsumer(String beanName, Consumer<Object> consumer) {
when(registry.lookup(Consumer.class, beanName)).thenReturn(consumer);
}
private void stubCatalogToReturnSupplier(String beanName, Supplier<Object> supplier) {
when(registry.lookup(Supplier.class, beanName)).thenReturn(supplier);
}
private void stubCatalogToReturnSupplier(Supplier<Object> supplier) {
stubCatalogToReturnSupplier("supplier", supplier);
}
private void stubCatalogToReturnFunction(Function<Object, Object> function) {
stubCatalogToReturnFunction("function", function);
}
private void stubCatalogToReturnConsumer(Consumer<Object> consumer) {
stubCatalogToReturnConsumer("consumer", consumer);
}
private void setFunctionEnvVar(String beanName) {
environmentVariables.set(SpringCloudFunctionLoader.ENV_VAR_FUNCTION_NAME, beanName);
}
private void setConsumerEnvVar(String beanName) {
environmentVariables.set(SpringCloudFunctionLoader.ENV_VAR_CONSUMER_NAME, beanName);
}
private void setSupplierEnvVar(String supplierBeanName) {
environmentVariables.set(SpringCloudFunctionLoader.ENV_VAR_SUPPLIER_NAME, supplierBeanName);
}
private SpringCloudMethod getDiscoveredFunction() {
loader.loadFunction();
return loader.getFunction();
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-spring-cloud-function/src/test/java/com/fnproject/springframework/function/SpringCloudFunctionInvokerTest.java | fn-spring-cloud-function/src/test/java/com/fnproject/springframework/function/SpringCloudFunctionInvokerTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.springframework.function;
import com.fnproject.springframework.function.functions.SpringCloudFunction;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.function.context.catalog.SimpleFunctionRegistry;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class SpringCloudFunctionInvokerTest {
private SpringCloudFunctionInvoker invoker;
@Autowired
private SimpleFunctionRegistry registry;
@Before
public void setUp() {
invoker = new SpringCloudFunctionInvoker((SpringCloudFunctionLoader) null);
}
@Test
public void invokesFunctionWithEmptyFlux() {
SpringCloudFunction fnWrapper = new SpringCloudFunction(x -> x, registry);
Object result = invoker.tryInvoke(fnWrapper, new Object[0]);
assertThat(result).isNull();
}
@Test
public void invokesFunctionWithFluxOfSingleItem() {
SpringCloudFunction fnWrapper = new SpringCloudFunction(x -> x, registry);
Object result = invoker.tryInvoke(fnWrapper, new Object[]{ "hello" });
assertThat(result).isInstanceOf(String.class);
assertThat(result).isEqualTo("hello");
}
@Test
public void invokesFunctionWithFluxOfMultipleItems() {
SpringCloudFunction fnWrapper = new SpringCloudFunction(x -> x, registry);
Object result = invoker.tryInvoke(fnWrapper, new Object[]{ Arrays.asList("hello", "world") });
assertThat(result).isInstanceOf(List.class);
assertThat((List) result).containsSequence("hello", "world");
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-spring-cloud-function/src/test/java/com/fnproject/springframework/function/SpringCloudFunctionInvokerIntegrationTest.java | fn-spring-cloud-function/src/test/java/com/fnproject/springframework/function/SpringCloudFunctionInvokerIntegrationTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.springframework.function;
import com.fnproject.fn.testing.FnTestingRule;
import com.fnproject.springframework.function.testfns.EmptyFunctionConfig;
import com.fnproject.springframework.function.testfns.FunctionConfig;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import static org.assertj.core.api.Assertions.assertThat;
public class SpringCloudFunctionInvokerIntegrationTest {
@Rule
public final FnTestingRule fnRule = FnTestingRule.createDefault();
@Rule
public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
@Test
public void shouldInvokeFunction() {
fnRule.givenEvent().withBody("HELLO").enqueue();
fnRule.thenRun(FunctionConfig.class, "handleRequest");
assertThat(fnRule.getOnlyResult().getBodyAsString()).isEqualTo("hello");
}
@Test
@Ignore("Consumer behaviour seems broken in this release of Spring Cloud Function")
// NB the problem is that FluxConsumer is not a subclass of j.u.f.Consumer, but _is_
// a subclass of j.u.f.Function.
// Effectively a Consumer<T> is treated as a Function<T, Void> which means when we lookup
// by env var name "consumer", we don't find a j.u.f.Consumer, so we fall back to the default
// behaviour which is to invoke the bean named "function"
public void shouldInvokeConsumer() {
environmentVariables.set(SpringCloudFunctionLoader.ENV_VAR_CONSUMER_NAME, "consumer");
fnRule.givenEvent().withBody("consumer input").enqueue();
fnRule.thenRun(FunctionConfig.class, "handleRequest");
assertThat(fnRule.getStdErrAsString()).contains("consumer input");
}
@Test
public void shouldInvokeSupplier() {
environmentVariables.set(SpringCloudFunctionLoader.ENV_VAR_SUPPLIER_NAME, "supplier");
fnRule.givenEvent().enqueue();
fnRule.thenRun(FunctionConfig.class, "handleRequest");
String output = fnRule.getOnlyResult().getBodyAsString();
assertThat(output).isEqualTo("Hello");
}
@Test
public void shouldThrowFunctionLoadExceptionIfNoValidFunction() {
fnRule.givenEvent().enqueue();
fnRule.thenRun(EmptyFunctionConfig.class, "handleRequest");
int exitCode = fnRule.getLastExitCode();
assertThat(exitCode).isEqualTo(1);
assertThat(fnRule.getResults()).isEmpty(); // fails at init so no results.
assertThat(fnRule.getStdErrAsString()).contains("No Spring Cloud Function found");
}
@Test
public void noNPEifFunctionReturnsNull() {
fnRule.givenEvent().enqueue();
fnRule.thenRun(EmptyFunctionConfig.class, "handleRequest");
int exitCode = fnRule.getLastExitCode();
assertThat(exitCode).isEqualTo(1);
assertThat(fnRule.getResults()).isEmpty(); // fails at init so no results.
assertThat(fnRule.getStdErrAsString()).contains("No Spring Cloud Function found");
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-spring-cloud-function/src/test/java/com/fnproject/springframework/function/testfns/FunctionConfig.java | fn-spring-cloud-function/src/test/java/com/fnproject/springframework/function/testfns/FunctionConfig.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.springframework.function.testfns;
import com.fnproject.fn.api.FnConfiguration;
import com.fnproject.fn.api.FnFeature;
import com.fnproject.fn.api.RuntimeContext;
import com.fnproject.springframework.function.SpringCloudFunctionFeature;
import com.fnproject.springframework.function.SpringCloudFunctionInvoker;
import org.springframework.cloud.function.context.config.ContextFunctionCatalogAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import reactor.core.publisher.Flux;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
@Configuration
@Import(ContextFunctionCatalogAutoConfiguration.class)
@FnFeature(SpringCloudFunctionFeature.class)
public class FunctionConfig {
public void handleRequest() {
}
@Bean
public Supplier<Flux<String>> supplier() {
String str = "Hello";
return () -> Flux.just(str);
}
@Bean
public Consumer<String> consumer() {
System.out.println("LOADED");
return System.out::println;
}
@Bean
public Function<String, String> function() {
return String::toLowerCase;
}
@Bean
public Function<String, String> upperCaseFunction() {
return String::toUpperCase;
}
@Bean
public String notAFunction() {
return "NotAFunction";
}
// Empty entrypoint that isn't used but necessary for the EntryPoint. Our invoker ignores this and loads our own
// function to invoke
public static class Name {
public final String first;
public final String last;
public Name(String first, String last) {
this.first = first;
this.last = last;
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-spring-cloud-function/src/test/java/com/fnproject/springframework/function/testfns/EmptyFunctionConfig.java | fn-spring-cloud-function/src/test/java/com/fnproject/springframework/function/testfns/EmptyFunctionConfig.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.springframework.function.testfns;
import com.fnproject.fn.api.FnConfiguration;
import com.fnproject.fn.api.FnFeature;
import com.fnproject.fn.api.FunctionInvoker;
import com.fnproject.fn.api.RuntimeContext;
import com.fnproject.springframework.function.SpringCloudFunctionFeature;
import com.fnproject.springframework.function.SpringCloudFunctionInvoker;
import org.springframework.cloud.function.context.config.ContextFunctionCatalogAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import(ContextFunctionCatalogAutoConfiguration.class)
@FnFeature(SpringCloudFunctionFeature.class)
public class EmptyFunctionConfig {
public void handleRequest() {
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/SimpleTypeWrapper.java | fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/SimpleTypeWrapper.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.springframework.function;
import com.fnproject.fn.api.TypeWrapper;
/**
* Implementation of @{@link TypeWrapper} which stores the type
* passed in directly.
*/
public class SimpleTypeWrapper implements TypeWrapper {
private final Class<?> cls;
public SimpleTypeWrapper(Class<?> cls) {
this.cls = cls;
}
@Override
public Class<?> getParameterClass() {
return cls;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/SpringCloudFunctionFeature.java | fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/SpringCloudFunctionFeature.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.springframework.function;
import com.fnproject.fn.api.FunctionInvoker;
import com.fnproject.fn.api.RuntimeContext;
import com.fnproject.fn.api.RuntimeFeature;
/**
*
* The SpringCloudFunctionFeature enables a function to be run with a spring cloud function configuration
*
* Created on 10/09/2018.
* <p>
* (c) 2018 Oracle Corporation
*/
public class SpringCloudFunctionFeature implements RuntimeFeature {
@Override
public void initialize(RuntimeContext ctx) {
ctx.addInvoker(new SpringCloudFunctionInvoker(ctx.getMethod().getTargetClass()),FunctionInvoker.Phase.Call);
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/SpringCloudFunctionInvoker.java | fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/SpringCloudFunctionInvoker.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.springframework.function;
import com.fnproject.fn.api.*;
import com.fnproject.fn.api.exception.FunctionInputHandlingException;
import com.fnproject.fn.api.exception.FunctionOutputHandlingException;
import com.fnproject.springframework.function.functions.SpringCloudMethod;
import org.springframework.boot.Banner;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import reactor.core.publisher.Flux;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
/**
* A {@link FunctionInvoker} for Spring Cloud Functions
*
* Call {@link RuntimeContext#setInvoker(FunctionInvoker)} before any function invocations
* to use this.
*/
public class SpringCloudFunctionInvoker implements FunctionInvoker, Closeable {
private final SpringCloudFunctionLoader loader;
private ConfigurableApplicationContext applicationContext;
SpringCloudFunctionInvoker(SpringCloudFunctionLoader loader) {
this.loader = loader;
}
/**
* A common pattern is to call this function from within a Configuration method of
* a {@link org.springframework.beans.factory.annotation.Configurable} function.
*
* @param configClass The class which defines your Spring Cloud Function @Beans
*/
public SpringCloudFunctionInvoker(Class<?> configClass) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(configClass);
applicationContext = builder.web(WebApplicationType.NONE).bannerMode(Banner.Mode.OFF).run();
loader = applicationContext.getAutowireCapableBeanFactory().createBean(SpringCloudFunctionLoader.class);
loader.loadFunction();
}
/**
* Invoke the user's function with params generated from:
*
* @param ctx the {@link InvocationContext}
* @param evt the {@link InputEvent}
*/
@Override
public Optional<OutputEvent> tryInvoke(InvocationContext ctx, InputEvent evt) {
SpringCloudMethod method = loader.getFunction();
Object[] userFunctionParams = coerceParameters(ctx, method, evt);
Object result = tryInvoke(method, userFunctionParams);
return coerceReturnValue(ctx, method, result);
}
private Object[] coerceParameters(InvocationContext ctx, MethodWrapper targetMethod, InputEvent evt) {
try {
Object[] userFunctionParams = new Object[targetMethod.getParameterCount()];
for (int paramIndex = 0; paramIndex < userFunctionParams.length; paramIndex++) {
userFunctionParams[paramIndex] = coerceParameter(ctx, targetMethod, paramIndex, evt);
}
return userFunctionParams;
} catch (RuntimeException e) {
throw new FunctionInputHandlingException("An exception was thrown during Input Coercion: " + e.getMessage(), e);
}
}
private Optional<OutputEvent> coerceReturnValue(InvocationContext ctx, MethodWrapper method, Object rawResult) {
try {
return Optional.of((ctx.getRuntimeContext()).getOutputCoercions(method.getTargetMethod())
.stream()
.map((c) -> c.wrapFunctionResult(ctx, method, rawResult))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst()
.orElseThrow(() -> new FunctionOutputHandlingException("No coercion found for return type")));
} catch (RuntimeException e) {
throw new FunctionOutputHandlingException("An exception was thrown during Output Coercion: " + e.getMessage(), e);
}
}
private Object coerceParameter(InvocationContext ctx, MethodWrapper targetMethod, int param, InputEvent evt) {
RuntimeContext runtimeContext = ctx.getRuntimeContext();
return runtimeContext.getInputCoercions(targetMethod, param)
.stream()
.map((c) -> c.tryCoerceParam(ctx, param, evt, targetMethod))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst()
.orElseThrow(() -> new FunctionInputHandlingException("No type coercion for argument " + param + " of " + targetMethod + " of found"));
}
// NB: this could be private except it's tested directly
protected Object tryInvoke(SpringCloudMethod method, Object[] userFunctionParams) {
Object userFunctionParam = null;
if (userFunctionParams.length > 0) {
userFunctionParam = userFunctionParams[0];
}
Flux<?> input = convertToFlux(userFunctionParams);
Flux<?> result = method.invoke(input);
return convertFromFlux(userFunctionParam, result);
}
private Object convertFromFlux(Object preFluxifiedInput, Flux<?> output) {
List<Object> result = new ArrayList<>();
for (Object val : output.toIterable()) {
result.add(val);
}
if (result.isEmpty()) {
return null;
} else if (isSingleValue(preFluxifiedInput) && result.size() == 1) {
return result.get(0);
} else {
return result;
}
}
private boolean isSingleValue(Object input) {
return !(input instanceof Collection);
}
private Flux<?> convertToFlux(Object[] params) {
if (params.length == 0) {
return Flux.empty();
}
Object firstParam = params[0];
if (firstParam instanceof Collection){
return Flux.fromIterable((Collection) firstParam);
}
return Flux.just(firstParam);
}
@Override
public void close() {
applicationContext.close();
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/SpringCloudFunctionLoader.java | fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/SpringCloudFunctionLoader.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.springframework.function;
import com.fnproject.springframework.function.exception.SpringCloudFunctionNotFoundException;
import com.fnproject.springframework.function.functions.SpringCloudConsumer;
import com.fnproject.springframework.function.functions.SpringCloudFunction;
import com.fnproject.springframework.function.functions.SpringCloudMethod;
import com.fnproject.springframework.function.functions.SpringCloudSupplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.function.context.FunctionCatalog;
import org.springframework.cloud.function.context.catalog.SimpleFunctionRegistry;
import reactor.core.publisher.Flux;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* The Loader for Spring Cloud Functions
* <p>
* Looks up Functions from the {@link FunctionCatalog} (which is likely populated by your
* function class, see {@link SpringCloudFunctionInvoker#SpringCloudFunctionInvoker(SpringCloudFunctionLoader)})
* <p>
* Lookup is in the following order:
* <p>
* Environment variable `FN_SPRING_FUNCTION` returning a `Function`
* Environment variable `FN_SPRING_CONSUMER` returning a `Consumer`
* Environment variable `FN_SPRING_SUPPLIER` returning a `Supplier`
* Bean named `function` returning a `Function`
* Bean named `consumer` returning a `Consumer`
* Bean named `supplier` returning a `Supplier`
*/
public class SpringCloudFunctionLoader {
public static final String DEFAULT_SUPPLIER_BEAN = "supplier";
public static final String DEFAULT_CONSUMER_BEAN = "consumer";
public static final String DEFAULT_FUNCTION_BEAN = "function";
public static final String ENV_VAR_FUNCTION_NAME = "FN_SPRING_FUNCTION";
public static final String ENV_VAR_CONSUMER_NAME = "FN_SPRING_CONSUMER";
public static final String ENV_VAR_SUPPLIER_NAME = "FN_SPRING_SUPPLIER";
private final SimpleFunctionRegistry registry;
private Function<Flux<?>, Flux<?>> function;
private Consumer<Flux<?>> consumer;
private Supplier<Flux<?>> supplier;
SpringCloudFunctionLoader(@Autowired SimpleFunctionRegistry registry) {
this.registry = registry;
}
void loadFunction() {
loadSpringCloudFunctionFromEnvVars();
if (noSpringCloudFunctionFound()) {
loadSpringCloudFunctionFromDefaults();
}
if (noSpringCloudFunctionFound()) {
throw new SpringCloudFunctionNotFoundException("No Spring Cloud Function found.");
}
}
private void loadSpringCloudFunctionFromEnvVars() {
String functionName = System.getenv(ENV_VAR_FUNCTION_NAME);
if (functionName != null) {
function = this.registry.lookup(Function.class, functionName);
}
String consumerName = System.getenv(ENV_VAR_CONSUMER_NAME);
if (consumerName != null) {
consumer = this.registry.lookup(Consumer.class, consumerName);
}
String supplierName = System.getenv(ENV_VAR_SUPPLIER_NAME);
if (supplierName != null) {
supplier = this.registry.lookup(Supplier.class, supplierName);
}
}
private void loadSpringCloudFunctionFromDefaults() {
function = this.registry.lookup(Function.class, DEFAULT_FUNCTION_BEAN);
consumer = this.registry.lookup(Consumer.class, DEFAULT_CONSUMER_BEAN);
supplier = this.registry.lookup(Supplier.class, DEFAULT_SUPPLIER_BEAN);
}
private boolean noSpringCloudFunctionFound() {
return function == null && consumer == null && supplier == null;
}
SpringCloudMethod getFunction() {
if (function != null) {
return new SpringCloudFunction(function, registry);
} else if (consumer != null) {
return new SpringCloudConsumer(consumer, registry);
} else {
return new SpringCloudSupplier(supplier, registry);
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/exception/SpringCloudFunctionNotFoundException.java | fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/exception/SpringCloudFunctionNotFoundException.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.springframework.function.exception;
import com.fnproject.fn.api.exception.FunctionLoadException;
/**
* Spring Cloud Function integration attempts to find the right Bean to use
* as the function entrypoint. This exception is thrown when that fails.
*/
public class SpringCloudFunctionNotFoundException extends FunctionLoadException {
public SpringCloudFunctionNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public SpringCloudFunctionNotFoundException(String msg) {
super(msg);
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/functions/SpringCloudMethod.java | fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/functions/SpringCloudMethod.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.springframework.function.functions;
import com.fnproject.fn.api.MethodWrapper;
import com.fnproject.fn.api.TypeWrapper;
import com.fnproject.springframework.function.SimpleTypeWrapper;
import org.springframework.cloud.function.context.catalog.SimpleFunctionRegistry;
import reactor.core.publisher.Flux;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* Superclass for classes which represent java.util.function.* objects as
* Spring Cloud Functions
*/
public abstract class SpringCloudMethod implements MethodWrapper {
private SimpleFunctionRegistry registry;
SpringCloudMethod(SimpleFunctionRegistry registry) {
this.registry = registry;
}
@Override
public Class<?> getTargetClass() {
return getFunction().getClass();
}
@Override
public Method getTargetMethod() {
Class<?> cls = getTargetClass();
String methodName = getMethodName();
return Arrays.stream(cls.getMethods())
.filter((m) -> m.getName().equals(methodName))
.findFirst()
.orElseThrow(() -> new IllegalStateException("Could not find " + methodName + " on " + cls));
}
/**
* Returns the name of the method used to invoke the function object.
* e.g. {@code apply} for {@link java.util.function.Function},
* {@code accept} for {@link java.util.function.Consumer},
* {@code get} for {@link java.util.function.Supplier}
*
* @return name of the method used to invoke the function object
*/
protected abstract String getMethodName();
/**
* Returns the target function object as an {@link Object}.
* (used for type inspection purposes)
*
* @return target function object
*/
protected abstract Object getFunction();
@Override
public TypeWrapper getParamType(int index) {
return new SimpleTypeWrapper(registry.getInputType(getFunction()));
}
@Override
public TypeWrapper getReturnType() {
return new SimpleTypeWrapper(registry.getOutputType(getFunction()));
}
/**
* Invoke the target function object
*
* @param arg fuction invoke arguments
* @return Flux type object
*/
public abstract Flux<?> invoke(Flux<?> arg);
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/functions/SpringCloudSupplier.java | fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/functions/SpringCloudSupplier.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.springframework.function.functions;
import com.fnproject.fn.api.TypeWrapper;
import com.fnproject.springframework.function.SimpleTypeWrapper;
import org.springframework.cloud.function.context.catalog.SimpleFunctionRegistry;
import reactor.core.publisher.Flux;
import java.util.function.Supplier;
/**
* {@link SpringCloudMethod} representing a {@link Supplier}
*/
public class SpringCloudSupplier extends SpringCloudMethod {
private Supplier<Flux<?>> supplier;
public SpringCloudSupplier(Supplier<Flux<?>> supplier, SimpleFunctionRegistry registry) {
super(registry);
this.supplier = supplier;
}
@Override
protected String getMethodName() {
return "get";
}
@Override
protected Object getFunction() {
return supplier;
}
@Override
public TypeWrapper getParamType(int i) {
return new SimpleTypeWrapper(Void.class);
}
@Override
public Flux<?> invoke(Flux<?> arg) {
return supplier.get();
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/functions/SpringCloudConsumer.java | fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/functions/SpringCloudConsumer.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.springframework.function.functions;
import com.fnproject.fn.api.TypeWrapper;
import com.fnproject.springframework.function.SimpleTypeWrapper;
import org.springframework.cloud.function.context.catalog.SimpleFunctionRegistry;
import reactor.core.publisher.Flux;
import java.util.function.Consumer;
/**
* {@link SpringCloudMethod} representing a {@link Consumer}
*/
public class SpringCloudConsumer extends SpringCloudMethod {
private Consumer<Flux<?>> consumer;
public SpringCloudConsumer(Consumer<Flux<?>> consumer, SimpleFunctionRegistry registry) {
super(registry);
this.consumer = consumer;
}
@Override
protected String getMethodName() {
return "accept";
}
@Override
protected Object getFunction() {
return consumer;
}
@Override
public TypeWrapper getReturnType() {
return new SimpleTypeWrapper(Void.class);
}
@Override
public Flux<?> invoke(Flux<?> arg) {
consumer.accept(arg);
return Flux.empty();
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/functions/SpringCloudFunction.java | fn-spring-cloud-function/src/main/java/com/fnproject/springframework/function/functions/SpringCloudFunction.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.springframework.function.functions;
import org.springframework.cloud.function.context.catalog.SimpleFunctionRegistry;
import reactor.core.publisher.Flux;
import java.util.function.Function;
/**
* {@link SpringCloudMethod} representing a {@link Function}
*/
public class SpringCloudFunction extends SpringCloudMethod {
private Function<Flux<?>, Flux<?>> function;
public SpringCloudFunction(Function<Flux<?>, Flux<?>> function, SimpleFunctionRegistry registry) {
super(registry);
this.function = function;
}
@Override
protected String getMethodName() {
return "apply";
}
@Override
protected Object getFunction() {
return function;
}
@Override
public Flux<?> invoke(Flux<?> arg) {
return function.apply(arg);
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/testing-junit4/src/test/java/com/fnproject/fn/testing/FnTestingRuleTest.java | testing-junit4/src/test/java/com/fnproject/fn/testing/FnTestingRuleTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.testing;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.api.OutputEvent;
import com.fnproject.fn.api.RuntimeContext;
import org.apache.commons.io.IOUtils;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
public class FnTestingRuleTest {
public static Map<String, String> configuration;
public static InputEvent inEvent;
public static List<InputEvent> capturedInputs = new ArrayList<>();
public static List<byte[]> capturedBodies = new ArrayList<>();
@Rule
public FnTestingRule fn = FnTestingRule.createDefault();
private final String exampleBaseUrl = "http://www.example.com";
@Before
public void reset() {
fn.addSharedClass(FnTestingRuleTest.class);
fn.addSharedClass(InputEvent.class);
FnTestingRuleTest.configuration = null;
FnTestingRuleTest.inEvent = null;
FnTestingRuleTest.capturedInputs = new ArrayList<>();
FnTestingRuleTest.capturedBodies = new ArrayList<>();
}
public static class TestFn {
private RuntimeContext ctx;
public TestFn(RuntimeContext ctx) {
this.ctx = ctx;
}
public void copyConfiguration() {
configuration = new HashMap<>(ctx.getConfiguration());
}
public void copyInputEvent(InputEvent inEvent) {
FnTestingRuleTest.inEvent = inEvent;
}
public void err() {
throw new RuntimeException("ERR");
}
public void captureInput(InputEvent in) {
capturedInputs.add(in);
capturedBodies.add(in.consumeBody(TestFn::consumeToBytes));
}
private static byte[] consumeToBytes(InputStream is) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
IOUtils.copy(is, bos);
return bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public OutputEvent echoInput(InputEvent in) {
byte[] result = in.consumeBody(TestFn::consumeToBytes);
return OutputEvent.fromBytes(result, OutputEvent.Status.Success, "application/octet-stream");
}
}
@Test
public void shouldSetEnvironmentInsideFnScope() {
fn.givenEvent().enqueue();
fn.setConfig("CONFIG_FOO", "BAR");
fn.thenRun(FnTestingRuleTest.TestFn.class, "copyConfiguration");
Assertions.assertThat(configuration).containsEntry("CONFIG_FOO", "BAR");
}
@Test
public void shouldCleanEnvironmentOfSpecialVarsInsideFnScope() {
fn.givenEvent().enqueue();
fn.setConfig("CONFIG_FOO", "BAR");
fn.thenRun(FnTestingRuleTest.TestFn.class, "copyConfiguration");
Assertions.assertThat(configuration).doesNotContainKeys("APP_NAME", "ROUTE", "METHOD", "REQUEST_URL");
}
@Test
public void shouldHandleErrors() {
fn.givenEvent().enqueue();
fn.thenRun(FnTestingRuleTest.TestFn.class, "err");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.FunctionError);
Assertions.assertThat(fn.getStdErrAsString()).contains("An error occurred in function: ERR");
}
@Test
public void configShouldNotOverrideIntrinsicHeaders() {
fn.givenEvent().enqueue();
fn.setConfig("Fn-Call-Id", "BAR");
fn.thenRun(FnTestingRuleTest.TestFn.class, "copyInputEvent");
Assertions.assertThat(inEvent.getCallID()).isEqualTo("callId");
}
@Test
public void configShouldBeCaptitalisedAndReplacedWithUnderscores() {// Basic test
// Test uppercasing and mangling of keys
fn.givenEvent().enqueue();
fn.setConfig("some-key-with-dashes", "some-value");
fn.thenRun(FnTestingRuleTest.TestFn.class, "copyConfiguration");
Assertions.assertThat(configuration).containsEntry("SOME_KEY_WITH_DASHES", "some-value");
}
@Test
public void shouldSendEventDataToSDKInputEvent() {
fn.setConfig("SOME_CONFIG", "SOME_VALUE");
fn.givenEvent()
.withHeader("FOO", "BAR, BAZ")
.withHeader("FEH", "")
.withBody("Body") // body as string
.enqueue();
fn.thenRun(TestFn.class, "captureInput");
FnResult result = fn.getOnlyResult();
Assertions.assertThat(result.getBodyAsString()).isEmpty();
Assertions.assertThat(result.getStatus()).isEqualTo(OutputEvent.Status.Success);
InputEvent event = capturedInputs.get(0);
Assertions.assertThat(event.getHeaders().asMap())
.contains(headerEntry("FOO", "BAR, BAZ"))
.contains(headerEntry("FEH", ""));
Assertions.assertThat(capturedBodies.get(0)).isEqualTo("Body".getBytes());
}
@Test
public void shouldEnqueueMultipleDistinctEvents() {
fn.setConfig("SOME_CONFIG", "SOME_VALUE");
fn.givenEvent()
.withHeader("FOO", "BAR")
.withBody("Body") // body as string
.enqueue();
fn.givenEvent()
.withHeader("FOO2", "BAR2")
.withBody("Body2") // body as string
.enqueue();
fn.thenRun(TestFn.class, "captureInput");
FnResult result = fn.getResults().get(0);
Assertions.assertThat(result.getBodyAsString()).isEmpty();
Assertions.assertThat(result.getStatus()).isEqualTo(OutputEvent.Status.Success);
InputEvent event = capturedInputs.get(0);
Assertions.assertThat(event.getHeaders().asMap()).contains(headerEntry("FOO", "BAR"));
Assertions.assertThat(capturedBodies.get(0)).isEqualTo("Body".getBytes());
FnResult result2 = fn.getResults().get(1);
Assertions.assertThat(result2.getBodyAsString()).isEmpty();
Assertions.assertThat(result2.getStatus()).isEqualTo(OutputEvent.Status.Success);
InputEvent event2 = capturedInputs.get(1);
Assertions.assertThat(event2.getHeaders().asMap()).contains(headerEntry("FOO2", "BAR2"));
Assertions.assertThat(capturedBodies.get(1)).isEqualTo("Body2".getBytes());
}
@Test
public void shouldEnqueueMultipleIdenticalEvents() {
fn.givenEvent()
.withHeader("FOO", "BAR")
.withHeader("Content-Type", "application/octet-stream")
.withBody("Body") // body as string
.enqueue(10);
fn.thenRun(TestFn.class, "echoInput");
List<FnResult> results = fn.getResults();
Assertions.assertThat(results).hasSize(10);
results.forEach((r) -> {
Assertions.assertThat(r.getStatus()).isEqualTo(OutputEvent.Status.Success);
});
}
@Test
public void shouldEnqueuIndependentEventsWithInputStreams() throws IOException {
fn.givenEvent()
.withBody(new ByteArrayInputStream("Body".getBytes())) // body as string
.enqueue();
fn.givenEvent()
.withBody(new ByteArrayInputStream("Body1".getBytes())) // body as string
.enqueue();
fn.thenRun(TestFn.class, "echoInput");
List<FnResult> results = fn.getResults();
Assertions.assertThat(results).hasSize(2);
Assertions.assertThat(results.get(0).getBodyAsString()).isEqualTo("Body");
Assertions.assertThat(results.get(1).getBodyAsString()).isEqualTo("Body1");
}
@Test
public void shouldHandleBodyAsInputStream() throws IOException {
fn.givenEvent().withBody(new ByteArrayInputStream("FOO BAR".getBytes())).enqueue();
fn.thenRun(TestFn.class, "captureInput");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(capturedBodies.get(0)).isEqualTo("FOO BAR".getBytes());
}
// TODO move this to HTTP gateway
// @Test
// public void shouldLeaveQueryParamtersOffIfNotSpecified() {
// String baseUrl = "www.example.com";
// fn.givenEvent()
// .withRequestUrl(baseUrl)
// .enqueue();
// fn.thenRun(TestFn.class, "copyInputEvent");
//
// Assertions.assertThat(inEvent.getRequestUrl()).isEqualTo(baseUrl);
// }
//
// @Test
// public void shouldPrependQuestionMarkForFirstQueryParam() {
// String baseUrl = "www.example.com";
// fn.givenEvent()
// .withRequestUrl(baseUrl)
// .withQueryParameter("var", "val")
// .enqueue();
// fn.thenRun(TestFn.class, "copyInputEvent");
// Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(200);
// Assertions.assertThat(inEvent.getRequestUrl()).isEqualTo(baseUrl + "?var=val");
// }
//
// @Test
// public void shouldHandleMultipleQueryParameters() {
// String baseUrl = "www.example.com";
// fn.givenEvent()
// .withRequestUrl(baseUrl)
// .withQueryParameter("var1", "val1")
// .withQueryParameter("var2", "val2")
// .enqueue();
// fn.thenRun(TestFn.class, "copyInputEvent");
//
// Assertions.assertThat(inEvent.getRequestUrl()).isEqualTo(baseUrl + "?var1=val1&var2=val2");
// }
//
// @Test
// public void shouldHandleMultipleQueryParametersWithSameKey() {
// String baseUrl = "www.example.com";
// fn.givenEvent()
// .withRequestUrl(baseUrl)
// .withQueryParameter("var", "val1")
// .withQueryParameter("var", "val2")
// .enqueue();
// fn.thenRun(TestFn.class, "copyInputEvent");
//
// Assertions.assertThat(inEvent.getRequestUrl()).isEqualTo(baseUrl + "?var=val1&var=val2");
// }
//
// @Test
// public void shouldUrlEncodeQueryParameterKey() {
// fn.givenEvent()
// .withRequestUrl(exampleBaseUrl)
// .withQueryParameter("&", "val")
// .enqueue();
// fn.thenRun(TestFn.class, "copyInputEvent");
//
// Assertions.assertThat(inEvent.getRequestUrl()).isEqualTo(exampleBaseUrl + "?%26=val");
// }
//
// @Test
// public void shouldHandleQueryParametersWithSpaces() {
// fn.givenEvent()
// .withRequestUrl(exampleBaseUrl)
// .withQueryParameter("my var", "this val")
// .enqueue();
// fn.thenRun(TestFn.class, "copyInputEvent");
//
// Assertions.assertThat(inEvent.getRequestUrl()).isEqualTo(exampleBaseUrl + "?my+var=this+val");
// }
//
// @Test
// public void shouldUrlEncodeQueryParameterValue() {
// String baseUrl = "www.example.com";
// fn.givenEvent()
// .withRequestUrl(baseUrl)
// .withQueryParameter("var", "&")
// .enqueue();
// fn.thenRun(TestFn.class, "copyInputEvent");
//
// Assertions.assertThat(inEvent.getRequestUrl()).isEqualTo(baseUrl + "?var=%26");
// }
private static Map.Entry<String, List<String>> headerEntry(String key, String... values) {
return new AbstractMap.SimpleEntry<>(Headers.canonicalKey(key), Arrays.asList(values));
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/testing-junit4/src/main/java/com/fnproject/fn/testing/FnTestingRule.java | testing-junit4/src/main/java/com/fnproject/fn/testing/FnTestingRule.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.testing;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fnproject.fn.api.*;
import com.fnproject.fn.runtime.EventCodec;
import org.apache.commons.io.output.TeeOutputStream;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import java.io.*;
import java.util.*;
/**
* Testing {@link Rule} for fn Java FDK functions.
* <p>
* This interface facilitates:
* <ul>
* <li>The creation of an in-memory environment replicating the functionality of the {@code fn} service</li>
* <li>The creation of input events passed to a user function using {@link #givenEvent()}</li>
* <li>The verification of function behaviour by accessing output represented by {@link FnResult} instances.</li>
* </ul>
* <h1>Example Usage:</h1>
* <pre>{@code
* public class MyFunctionTest {
* {@literal @}Rule
* public final FnTestingRule testing = FnTestingRule.createDefault();
*
* {@literal @}Test
* public void myTest() {
* // Create an event to invoke MyFunction and put it into the event queue
* fn.givenEvent()
* .addHeader("FOO", "BAR")
* .withBody("Body")
* .enqueue();
*
* // Run MyFunction#handleRequest using the built event queue from above
* fn.thenRun(MyFunction.class, "handleRequest");
*
* // Get the function result and check it for correctness
* FnResult result = fn.getOnlyResult();
* assertThat(result.getStatus()).isEqualTo(200);
* assertThat(result.getBodyAsString()).isEqualTo("expected return value of my function");
* }
* }}</pre>
*/
public final class FnTestingRule implements TestRule {
private final Map<String, String> config = new HashMap<>();
private Map<String, String> eventEnv = new HashMap<>();
private boolean hasEvents = false;
private List<InputEvent> pendingInput = Collections.synchronizedList(new ArrayList<>());
private List<FnResult> output = Collections.synchronizedList(new ArrayList<>());
private ByteArrayOutputStream stdErr = new ByteArrayOutputStream();
private static final ObjectMapper objectMapper = new ObjectMapper();
private final List<String> sharedPrefixes = new ArrayList<>();
private int lastExitCode;
private final List<FnTestingRuleFeature> features = new ArrayList<>();
{
// Internal shared classes required to bridge completer into tests
addSharedClassPrefix("java.");
addSharedClassPrefix("javax.");
addSharedClassPrefix("sun.");
addSharedClassPrefix("jdk.");
addSharedClass(Headers.class);
addSharedClass(InputEvent.class);
addSharedClass(OutputEvent.class);
addSharedClass(OutputEvent.Status.class);
addSharedClass(TestOutput.class);
addSharedClass(TestCodec.class);
addSharedClass(EventCodec.class);
addSharedClass(EventCodec.Handler.class);
}
/**
* TestOutput represents an output of a function it wraps OutputEvent and provides buffered access to the function output
*/
public static final class TestOutput implements FnResult {
private final OutputEvent from;
byte[] body;
private TestOutput(OutputEvent from) throws IOException {
this.from = Objects.requireNonNull(from, "from");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
from.writeToOutput(bos);
body = bos.toByteArray();
}
/**
* construct a test output from an output event - this consums the body of the output event
*
* @param from an output event to consume
* @return a new TestEvent that wraps the passed even t
* @throws IOException
*/
public static TestOutput fromOutputEvent(OutputEvent from) throws IOException {
return new TestOutput(from);
}
@Override
public Status getStatus() {
return from.getStatus();
}
@Override
public Optional<String> getContentType() {
return from.getContentType();
}
@Override
public Headers getHeaders() {
return from.getHeaders();
}
@Override
public void writeToOutput(OutputStream out) throws IOException {
out.write(body);
}
@Override
public byte[] getBodyAsBytes() {
return body;
}
/**
* Returns the buffered body of the event as a string
*
* @return the body of the event as a string
*/
@Override
public String getBodyAsString() {
return new String(body);
}
}
private FnTestingRule() {
}
public void addFeature(FnTestingRuleFeature f) {
this.features.add(f);
}
public void addInput(InputEvent input) {
pendingInput.add(input);
}
/**
* Create an instance of the testing {@link Rule}, with Flows support
*
* @return a new test rule
*/
public static FnTestingRule createDefault() {
return new FnTestingRule();
}
/**
* Add a config variable to the function for the test
* <p>
* Config names will be translated to upper case with hyphens and spaces translated to _. Clashing config keys will
* be overwritten.
*
* @param key the configuration key
* @param value the configuration value
* @return the current test rule
*/
public FnTestingRule setConfig(String key, String value) {
config.put(key.toUpperCase().replaceAll("[- ]", "_"), value);
return this;
}
/**
* Add a class or package name to be forked during the test.
* The test will be run under the aegis of a classloader that duplicates the class hierarchy named.
*
* @param prefix A class name or package prefix, such as "com.example.foo."
*/
public FnTestingRule addSharedClassPrefix(String prefix) {
sharedPrefixes.add(prefix);
return this;
}
/**
* Add a class to be forked during the test.
* The test will be run under the aegis of a classloader that duplicates the class hierarchy named.
*
* @param cls A class
*/
public FnTestingRule addSharedClass(Class<?> cls) {
sharedPrefixes.add("=" + cls.getName());
return this;
}
@Override
public Statement apply(Statement base, Description description) {
return base;
}
/**
* Create an HTTP event builder for the function
*
* @return a new event builder
*/
public FnEventBuilderJUnit4 givenEvent() {
return new DefaultFnEventBuilder();
}
/**
* Runs the function runtime with the specified class and method (and waits for Flow stages to finish
* if the test spawns any flows)
*
* @param cls class to thenRun
* @param method the method name
*/
public void thenRun(Class<?> cls, String method) {
thenRun(cls.getName(), method);
}
public static class TestCodec implements EventCodec {
private final List<InputEvent> input;
private final List<FnResult> output;
public TestCodec(List<InputEvent> input, List<FnResult> output) {
this.input = input;
this.output = output;
}
@Override
public void runCodec(Handler h) {
for (InputEvent in : input) {
try {
output.add(new TestOutput(h.handle(in)));
} catch (IOException e) {
throw new RuntimeException("Unexpected exception in test", e);
}
}
}
}
/**
* Runs the function runtime with the specified class and method (and waits for Flow stages to finish
* if the test spawns any Flow)
*
* @param cls class to thenRun
* @param method the method name
*/
public void thenRun(String cls, String method) {
final ClassLoader functionClassLoader;
Class c = null;
try {
// Trick to work around Maven class loader separation
// if passed class is a valid class then set the classloader to the same as the class's loader
c = Class.forName(cls);
} catch (Exception ignored) {
// TODO don't fall through here
}
if (c != null) {
functionClassLoader = c.getClassLoader();
} else {
functionClassLoader = getClass().getClassLoader();
}
PrintStream oldSystemOut = System.out;
PrintStream oldSystemErr = System.err;
for (FnTestingRuleFeature f : features) {
f.prepareTest(functionClassLoader, oldSystemErr, cls, method);
}
Map<String, String> mutableEnv = new HashMap<>();
try {
PrintStream functionErr = new PrintStream(new TeeOutputStream(stdErr, oldSystemErr));
System.setOut(functionErr);
System.setErr(functionErr);
mutableEnv.putAll(config);
mutableEnv.putAll(eventEnv);
mutableEnv.put("FN_FORMAT", "http-stream");
mutableEnv.put("FN_FN_ID","myFnID");
mutableEnv.put("FN_APP_ID","myAppID");
FnTestingClassLoader forked = new FnTestingClassLoader(functionClassLoader, sharedPrefixes);
if (forked.isShared(cls)) {
oldSystemErr.println("WARNING: The function class under test is shared with the test ClassLoader.");
oldSystemErr.println(" This may result in unexpected behaviour around function initialization and configuration.");
}
for (FnTestingRuleFeature f : features) {
f.prepareFunctionClassLoader(forked);
}
TestCodec codec = new TestCodec(pendingInput, output);
lastExitCode = forked.run(
mutableEnv,
codec,
functionErr,
cls + "::" + method);
stdErr.flush();
for (FnTestingRuleFeature f : features) {
f.afterTestComplete();
}
} catch (Exception e) {
throw new RuntimeException("internal error raised by entry point or flushing the test streams", e);
} finally {
System.out.flush();
System.err.flush();
System.setOut(oldSystemOut);
System.setErr(oldSystemErr);
}
}
/**
* Get the exit code from the most recent invocation
* 0 = success
* 1 = failed
* 2 = not run due to initialization error
*/
public int getLastExitCode() {
return lastExitCode;
}
/**
* Get the StdErr stream returned by the function as a byte array
*
* @return the StdErr stream as bytes from the runtime
*/
public byte[] getStdErr() {
return stdErr.toByteArray();
}
/**
* Gets the StdErr stream returned by the function as a String
*
* @return the StdErr stream as a string from the function
*/
public String getStdErrAsString() {
return new String(stdErr.toByteArray());
}
/**
* Parses any pending HTTP responses on the functions output stream and returns the corresponding FnResult instances
*
* @return a list of Parsed HTTP responses (as {@link FnResult}s) from the function runtime output
*/
public List<FnResult> getResults() {
return output;
}
/**
* Convenience method to get the one and only parsed http response expected on the output of the function
*
* @return a single parsed HTTP response from the function runtime output
* @throws IllegalStateException if zero or more than one responses were produced
*/
public FnResult getOnlyResult() {
List<FnResult> results = getResults();
if (results.size() == 1) {
return results.get(0);
}
throw new IllegalStateException("One and only one response expected, but " + results.size() + " responses were generated.");
}
public List<String> getSharedPrefixes() {
return Collections.unmodifiableList(sharedPrefixes);
}
public Map<String, String> getConfig() {
return Collections.unmodifiableMap(config);
}
public Map<String, String> getEventEnv() {
return Collections.unmodifiableMap(eventEnv);
}
/**
* Builds a mocked input event into the function runtime
*/
private class DefaultFnEventBuilder implements FnEventBuilderJUnit4 {
FnHttpEventBuilder builder = new FnHttpEventBuilder();
@Override
public FnEventBuilder withHeader(String key, String value) {
builder.withHeader(key, value);
return this;
}
@Override
public FnEventBuilder withBody(InputStream body) throws IOException {
builder.withBody(body);
return this;
}
@Override
public FnEventBuilder withBody(byte[] body) {
builder.withBody(body);
return this;
}
@Override
public FnEventBuilder withBody(String body) {
builder.withBody(body);
return this;
}
@Override
public FnTestingRule enqueue() {
pendingInput.add(builder.buildEvent());
return FnTestingRule.this;
}
@Override
public FnTestingRule enqueue(int n) {
if (n <= 0) {
throw new IllegalArgumentException("Invalid count");
}
for (int i = 0; i < n; i++) {
enqueue();
}
return FnTestingRule.this;
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/testing-junit4/src/main/java/com/fnproject/fn/testing/FnEventBuilderJUnit4.java | testing-junit4/src/main/java/com/fnproject/fn/testing/FnEventBuilderJUnit4.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.testing;
public interface FnEventBuilderJUnit4 extends FnEventBuilder<FnTestingRule> {
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/testing-junit4/src/main/java/com/fnproject/fn/testing/FnTestingRuleFeature.java | testing-junit4/src/main/java/com/fnproject/fn/testing/FnTestingRuleFeature.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.testing;
import java.io.PrintStream;
/**
* Created on 07/09/2018.
* <p>
* (c) 2018 Oracle Corporation
*/
public interface FnTestingRuleFeature {
/**
* Prepares a test
* @param functionClassLoader
* @param stderr
* @param cls
* @param method
*/
void prepareTest(ClassLoader functionClassLoader, PrintStream stderr, String cls, String method);
void prepareFunctionClassLoader(FnTestingClassLoader cl);
void afterTestComplete();
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/test/java/com/fnproject/fn/runtime/flow/FlowsContinuationInvokerTest.java | flow-runtime/src/test/java/com/fnproject/fn/runtime/flow/FlowsContinuationInvokerTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fnproject.fn.api.*;
import com.fnproject.fn.api.exception.FunctionInputHandlingException;
import com.fnproject.fn.api.flow.*;
import com.fnproject.fn.runtime.ReadOnceInputEvent;
import com.fnproject.fn.runtime.exception.InternalFunctionInvocationException;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.*;
import java.lang.reflect.Method;
import java.time.Instant;
import java.util.*;
import static com.fnproject.fn.runtime.flow.FlowContinuationInvoker.FLOW_ID_HEADER;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.instanceOf;
public class FlowsContinuationInvokerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
private final String FLOW_ID = "flow";
private final String STAGE_ID = "stage_id";
private TestBlobStore blobStore = new TestBlobStore();
private FlowContinuationInvoker invoker = new FlowContinuationInvoker();
@Before
public void setupClient() {
FlowRuntimeGlobals.setCompleterClientFactory(new CompleterClientFactory() {
@Override
public CompleterClient getCompleterClient() {
throw new IllegalStateException("Should not be called");
}
@Override
public BlobStoreClient getBlobStoreClient() {
return blobStore;
}
});
}
@After
public void tearDownClient() {
FlowRuntimeGlobals.resetCompleterClientFactory();
}
@Test
public void continuationInvokedWhenGraphHeaderPresent() throws IOException, ClassNotFoundException {
// Given
InputEvent event = newRequest()
.withClosure((Flows.SerFunction<Integer, Integer>) (x) -> x * 2)
.withJavaObjectArgs(10)
.asEvent();
// When
Optional<OutputEvent> result = invoker.tryInvoke(new EmptyInvocationContext(), event);
// Then
assertThat(result).isPresent();
APIModel.InvokeStageResponse response = fromOutput(result.get());
assertThat(response.result.successful).isTrue();
assertThat(blobStore.deserializeBlobResult(response.result, Integer.class)).isEqualTo(20);
}
@Test
public void continuationNotInvokedWhenHeaderMissing() throws IOException, ClassNotFoundException {
// Given
InputEvent event = new InputEventBuilder()
.withBody("")
.build();
// When
FlowContinuationInvoker invoker = new FlowContinuationInvoker();
Optional<OutputEvent> result = invoker.tryInvoke(new EmptyInvocationContext(), event);
// Then
assertThat(result).isNotPresent();
}
@Test
public void failsIfArgMissing() throws IOException, ClassNotFoundException {
thrown.expect(FunctionInputHandlingException.class);
// Given
InputEvent event = newRequest()
.withClosure((Flows.SerFunction<Integer, Integer>) (x) -> x * 2)
.asEvent();
invoker.tryInvoke(new EmptyInvocationContext(), event);
}
private static class TestIf implements Serializable {
void call() {
}
}
@Test
public void failsIfUnknownClosureType() {
thrown.expect(FunctionInputHandlingException.class);
// Given
InputEvent event = newRequest()
.withClosure(new TestIf())
.asEvent();
invoker.tryInvoke(new EmptyInvocationContext(), event);
}
@Test
public void handlesAllClosureTypes() {
class Tc {
private final Serializable closure;
private final Object args[];
private final Object result;
private Tc(Serializable closure, Object result, Object... args) {
this.closure = closure;
this.result = result;
this.args = args;
}
}
Tc[] cases = new Tc[]{
new Tc((Flows.SerConsumer<String>) (v) -> {
}, null, "hello"),
new Tc((Flows.SerBiFunction<String, String, String>) (String::concat), "hello bob", "hello ", "bob"),
new Tc((Flows.SerBiConsumer<String, String>) (a, b) -> {
}, null, "hello ", "bob"),
new Tc((Flows.SerFunction<String, String>) (String::toUpperCase), "HELLO BOB", "hello bob"),
new Tc((Flows.SerRunnable) () -> {
}, null),
new Tc((Flows.SerCallable<String>) () -> "hello", "hello"),
new Tc((Flows.SerSupplier<String>) () -> "hello", "hello"),
};
for (Tc tc : cases) {
InputEvent event = newRequest()
.withClosure(tc.closure)
.withJavaObjectArgs(tc.args)
.asEvent();
Optional<OutputEvent> result = invoker.tryInvoke(new EmptyInvocationContext(), event);
assertThat(result).isPresent();
APIModel.InvokeStageResponse res = fromOutput(result.get());
if (tc.result == null) {
assertThat(res.result.result).isInstanceOf(APIModel.EmptyDatum.class);
} else {
assertThat(blobStore.deserializeBlobResult(res.result, Object.class)).isEqualTo(tc.result);
}
}
}
@Test
public void emptyValueCorrectlySerialized() throws IOException, ClassNotFoundException {
// Given
InputEvent event = newRequest()
.withClosure((Flows.SerConsumer<Object>) (x) -> {
if (x != null) {
throw new RuntimeException("Not Null");
}
})
.withEmptyDatumArg()
.asEvent();
// When
Optional<OutputEvent> result = invoker.tryInvoke(new EmptyInvocationContext(), event);
// Then
assertThat(result).isPresent();
APIModel.InvokeStageResponse response = fromOutput(result.get());
assertThat(response.result.successful).isTrue();
}
@Test
public void emptyValueCorrectlyDeSerialized() throws IOException, ClassNotFoundException {
// Given
InputEvent event = newRequest()
.withClosure((Flows.SerSupplier<Object>) () -> null)
.asEvent();
// When
Optional<OutputEvent> result = invoker.tryInvoke(new EmptyInvocationContext(), event);
// Then
assertThat(result).isPresent();
APIModel.InvokeStageResponse response = fromOutput(result.get());
assertThat(response.result.successful).isTrue();
assertThat(response.result.result).isInstanceOf(APIModel.EmptyDatum.class);
}
@Test
public void stageRefCorrectlyDeserialized() throws IOException, ClassNotFoundException {
// Given
InputEvent event = newRequest()
.withClosure((Flows.SerConsumer<FlowFuture<Object>>) (x) -> {
assertThat(x).isNotNull();
assertThat(((RemoteFlow.RemoteFlowFuture<Object>) x).id()).isEqualTo("newStage");
})
.withStageRefArg("newStage")
.asEvent();
// When
Optional<OutputEvent> result = invoker.tryInvoke(new EmptyInvocationContext(), event);
// Then
assertThat(result).isPresent();
APIModel.InvokeStageResponse response = fromOutput(result.get());
assertThat(response.result.successful).isTrue();
}
@Test
public void stageRefCorrectlySerialized() throws IOException, ClassNotFoundException {
RemoteFlow rf = new RemoteFlow(new FlowId(FLOW_ID));
FlowFuture<Object> ff = rf.createFlowFuture(new CompletionId("newStage"));
// Given
InputEvent event = newRequest()
.withClosure((Flows.SerSupplier<FlowFuture<Object>>) () -> ff)
.asEvent();
// When
Optional<OutputEvent> result = invoker.tryInvoke(new EmptyInvocationContext(), event);
// Then
assertThat(result).isPresent();
APIModel.InvokeStageResponse response = fromOutput(result.get());
assertThat(response.result.successful).isTrue();
assertThat(response.result.result).isInstanceOf(APIModel.StageRefDatum.class);
assertThat(((APIModel.StageRefDatum) response.result.result).stageId).isEqualTo("newStage");
}
@Test
public void setsCurrentStageId() throws IOException, ClassNotFoundException {
InputEvent event = newRequest()
.withClosure((Flows.SerRunnable) () -> {
assertThat(FlowRuntimeGlobals.getCurrentCompletionId()).contains(new CompletionId("myStage"));
})
.withStageId("myStage")
.asEvent();
// When
Optional<OutputEvent> result = invoker.tryInvoke(new EmptyInvocationContext(), event);
// Then
assertThat(result).isPresent();
APIModel.InvokeStageResponse response = fromOutput(result.get());
assertThat(response.result.successful).isTrue();
}
@Test
public void httpRespToFn() throws Exception {
// Given
InputEvent event = newRequest()
.withClosure((Flows.SerConsumer<HttpResponse>) (x) -> {
assertThat(x.getBodyAsBytes()).isEqualTo("Hello".getBytes());
assertThat(x.getStatusCode()).isEqualTo(201);
assertThat(x.getHeaders().get("Foo")).contains("Bar");
})
.withHttpRespArg(201, "Hello", APIModel.HTTPHeader.create("Foo", "Bar"))
.asEvent();
// When
Optional<OutputEvent> result = invoker.tryInvoke(new EmptyInvocationContext(), event);
assertThat(result).isPresent();
APIModel.InvokeStageResponse resp = fromOutput(result.get());
assertThat(resp.result.successful).isTrue();
}
@Test
public void httpRespToFnWithError() throws Exception {
// Given
InputEvent event = newRequest()
.withClosure((Flows.SerConsumer<FunctionInvocationException>) (e) -> {
HttpResponse x = e.getFunctionResponse();
assertThat(x.getBodyAsBytes()).isEqualTo("Hello".getBytes());
assertThat(x.getStatusCode()).isEqualTo(201);
assertThat(x.getHeaders().get("Foo")).contains("Bar");
})
.withHttpRespArg(false, 201, "Hello", APIModel.HTTPHeader.create("Foo", "Bar"))
.asEvent();
// When
Optional<OutputEvent> result = invoker.tryInvoke(new EmptyInvocationContext(), event);
// Then
assertThat(result).isPresent();
APIModel.InvokeStageResponse resp = fromOutput(result.get());
assertThat(resp.result.successful).isTrue();
}
@Test
public void platformErrorsBecomeExceptions() throws IOException, ClassNotFoundException {
class TestCase {
private final APIModel.ErrorType errorType;
private final Class<? extends Throwable> exceptionType;
TestCase(APIModel.ErrorType errorType, Class<? extends Throwable> exceptionType) {
this.errorType = errorType;
this.exceptionType = exceptionType;
}
}
for (TestCase tc : new TestCase[]{
new TestCase(APIModel.ErrorType.InvalidStageResponse, InvalidStageResponseException.class),
new TestCase(APIModel.ErrorType.FunctionInvokeFailed, FunctionInvokeFailedException.class),
new TestCase(APIModel.ErrorType.FunctionTimeout, FunctionTimeoutException.class),
new TestCase(APIModel.ErrorType.StageFailed, StageInvokeFailedException.class),
new TestCase(APIModel.ErrorType.StageTimeout, StageTimeoutException.class),
new TestCase(APIModel.ErrorType.StageLost, StageLostException.class)
}) {
Class<? extends Throwable> type = tc.exceptionType;
// Given
InputEvent event = newRequest()
.withClosure((Flows.SerConsumer<Throwable>) (e) -> {
assertThat(e).hasMessage("My Error");
assertThat(e).isInstanceOf(type);
})
.withErrorBody(tc.errorType, "My Error")
.asEvent();
// When
Optional<OutputEvent> result = invoker.tryInvoke(new EmptyInvocationContext(), event);
// Then
assertThat(result).isPresent();
APIModel.InvokeStageResponse resp = fromOutput(result.get());
assertThat(resp.result.successful).isTrue();
}
}
@Test
public void functionInvocationExceptionThrownIfStageResultIsNotSerializable() {
thrown.expect(ResultSerializationException.class);
InputEvent event = newRequest()
.withClosure((Flows.SerSupplier<Object>) Object::new)
.asEvent();
invoker.tryInvoke(new EmptyInvocationContext(), event);
}
private static class MyRuntimeException extends RuntimeException {
}
@Test
public void functionInvocationExceptionThrownIfStageThrowsException() {
thrown.expect(InternalFunctionInvocationException.class);
thrown.expectCause(instanceOf(RuntimeException.class));
thrown.expectMessage("Error invoking flows lambda");
InputEvent event = newRequest()
.withClosure((Flows.SerRunnable) () -> {
throw new MyRuntimeException();
})
.asEvent();
invoker.tryInvoke(new EmptyInvocationContext(), event);
}
public static class FlowRequestBuilder {
private String flowId;
private final TestBlobStore blobStore;
APIModel.InvokeStageRequest req = new APIModel.InvokeStageRequest();
public FlowRequestBuilder(TestBlobStore blobStore, String flowId, String stageId) {
this.flowId = flowId;
req.flowId = flowId;
req.stageId = stageId;
this.blobStore = blobStore;
}
public FlowRequestBuilder withStageId(String stageId) {
req.stageId = stageId;
return this;
}
public FlowRequestBuilder withClosure(Serializable closure) {
req.closure = blobStore.withJavaBlob(flowId, closure);
return this;
}
public FlowRequestBuilder withJavaObjectArgs(Object... args) {
Arrays.stream(args).forEach((arg) ->
req.args.add(blobStore.withResult(flowId, arg, true)));
return this;
}
public InputEvent asEvent() {
ObjectMapper objectMapper = new ObjectMapper();
byte[] body;
try {
body = objectMapper.writeValueAsBytes(req);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
System.err.println("Req:" + new String(body));
return new InputEventBuilder()
.withHeader(FLOW_ID_HEADER, flowId)
.withHeader("Content-type", "application/json")
.withBody(new ByteArrayInputStream(body))
.build();
}
public FlowRequestBuilder withEmptyDatumArg() {
APIModel.CompletionResult res = new APIModel.CompletionResult();
res.successful = true;
res.result = new APIModel.EmptyDatum();
req.args.add(res);
return this;
}
public FlowRequestBuilder withStageRefArg(String stage) {
APIModel.StageRefDatum stageRefDatum = new APIModel.StageRefDatum();
stageRefDatum.stageId = stage;
APIModel.CompletionResult res = new APIModel.CompletionResult();
res.result = stageRefDatum;
res.successful = true;
req.args.add(res);
return this;
}
public FlowRequestBuilder withHttpRespArg(boolean status, int code, String body, APIModel.HTTPHeader... httpHeaders) {
APIModel.HTTPResp resp = new APIModel.HTTPResp();
resp.statusCode = code;
BlobResponse blobResponse = blobStore.writeBlob(flowId, body.getBytes(), "application/octet");
resp.body = APIModel.Blob.fromBlobResponse(blobResponse);
resp.headers = Arrays.asList(httpHeaders);
APIModel.CompletionResult res = new APIModel.CompletionResult();
APIModel.HTTPRespDatum datum = new APIModel.HTTPRespDatum();
datum.resp = resp;
res.result = datum;
res.successful = status;
req.args.add(res);
return this;
}
public FlowRequestBuilder withHttpRespArg(int code, String body, APIModel.HTTPHeader... httpHeaders) {
return withHttpRespArg(true, code, body, httpHeaders);
}
public FlowRequestBuilder withErrorBody(APIModel.ErrorType errType, String message) {
APIModel.ErrorDatum errorDatum = new APIModel.ErrorDatum();
errorDatum.type = errType;
errorDatum.message = message;
APIModel.CompletionResult result = new APIModel.CompletionResult();
result.successful = false;
result.result = errorDatum;
req.args.add(result);
return this;
}
}
FlowRequestBuilder newRequest() {
return new FlowRequestBuilder(blobStore, FLOW_ID, STAGE_ID);
}
private APIModel.InvokeStageResponse fromOutput(OutputEvent result) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
result.writeToOutput(bos);
System.err.println("Result: " + new String(bos.toByteArray()));
return new ObjectMapper().readValue(bos.toByteArray(), APIModel.InvokeStageResponse.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static class InputEventBuilder {
private InputStream body;
private Headers headers = Headers.fromMap(Collections.emptyMap());
InputEventBuilder() {
}
public InputEventBuilder withBody(InputStream body) {
this.body = body;
return this;
}
public InputEventBuilder withBody(String body) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
bos.write(body.getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
this.body = new ByteArrayInputStream(bos.toByteArray());
return this;
}
private Map<String, List<String>> currentHeaders() {
return new HashMap<>(headers.asMap());
}
public InputEventBuilder withHeader(String name, String value) {
this.headers = headers.setHeader(name, value);
return this;
}
private String getHeader(String key) {
return headers.get(key).orElse(null);
}
public InputEvent build() {
return new ReadOnceInputEvent(
body,
headers, "callID", Instant.now());
}
}
class EmptyRuntimeContext implements RuntimeContext {
@Override
public String getAppID() {
return "appID";
}
@Override
public String getFunctionID() {
return "fnID";
}
@Override
public Optional<Object> getInvokeInstance() {
return Optional.empty();
}
@Override
public Optional<String> getConfigurationByKey(String key) {
return Optional.empty();
}
@Override
public Map<String, String> getConfiguration() {
return null;
}
@Override
public <T> Optional<T> getAttribute(String att, Class<T> type) {
return Optional.empty();
}
@Override
public void setAttribute(String att, Object val) {
throw new RuntimeException("You can't modify the empty runtime context in the tests, sorry.");
}
@Override
public void addInputCoercion(InputCoercion ic) {
throw new RuntimeException("You can't modify the empty runtime context in the tests, sorry.");
}
@Override
public List<InputCoercion> getInputCoercions(MethodWrapper targetMethod, int param) {
return null;
}
@Override
public void addOutputCoercion(OutputCoercion oc) {
throw new RuntimeException("You can't modify the empty runtime context in the tests, sorry.");
}
@Override
public List<OutputCoercion> getOutputCoercions(Method method) {
return null;
}
@Override
public void setInvoker(FunctionInvoker invoker) {
throw new RuntimeException("You can't modify the empty runtime context in the tests, sorry.");
}
@Override
public void addInvoker(FunctionInvoker invoker, FunctionInvoker.Phase phase) {
throw new RuntimeException("You can't modify the empty runtime context in the tests, sorry.");
}
@Override
public MethodWrapper getMethod() {
return null;
}
}
class EmptyInvocationContext implements InvocationContext {
@Override
public RuntimeContext getRuntimeContext() {
return new EmptyRuntimeContext();
}
@Override
public void addListener(InvocationListener listener) {
}
@Override
public Headers getRequestHeaders() {
return Headers.emptyHeaders();
}
@Override
public void addResponseHeader(String key, String value) {
}
@Override
public void setResponseHeader(String key, String value, String... vs) {
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/test/java/com/fnproject/fn/runtime/flow/TestBlobStore.java | flow-runtime/src/test/java/com/fnproject/fn/runtime/flow/TestBlobStore.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import static com.fnproject.fn.runtime.flow.RemoteFlowApiClient.CONTENT_TYPE_JAVA_OBJECT;
/**
* Created on 26/11/2017.
* <p>
* (c) 2017 Oracle Corporation
*/
public class TestBlobStore implements BlobStoreClient {
Map<String, byte[]> blobs = new HashMap<>();
AtomicInteger blobCount = new AtomicInteger();
@Override
public BlobResponse writeBlob(String prefix, byte[] bytes, String contentType) {
String blobId = prefix + "-" + blobCount.incrementAndGet();
blobs.put(blobId, bytes);
BlobResponse blob = new BlobResponse();
blob.contentType = contentType;
blob.blobLength = (long) bytes.length;
blob.blobId = blobId;
return blob;
}
@Override
public <T> T readBlob(String prefix, String blobId, Function<InputStream, T> reader, String expectedContentType) {
if (!blobs.containsKey(blobId)) {
throw new IllegalStateException("Blob not found");
}
if (!blobId.startsWith(prefix)) {
throw new IllegalStateException("Invalid blob ID = prefix '" + prefix + "' does not match blob '" + blobId + "'");
}
return reader.apply(new ByteArrayInputStream(blobs.get(blobId)));
}
public APIModel.Blob withJavaBlob(String prefix, Object o) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(o);
oos.close();
BlobResponse br = writeBlob(prefix, bos.toByteArray(), CONTENT_TYPE_JAVA_OBJECT);
return APIModel.Blob.fromBlobResponse(br);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public APIModel.CompletionResult withResult(String prefix, Object o, boolean status) {
APIModel.CompletionResult result = new APIModel.CompletionResult();
result.successful = status;
APIModel.BlobDatum blobDatum = new APIModel.BlobDatum();
blobDatum.blob = withJavaBlob(prefix, o);
result.result = blobDatum;
return result;
}
public <T> T deserializeBlobResult(APIModel.CompletionResult result, Class<T> type) {
if (!(result.result instanceof APIModel.BlobDatum)) {
throw new IllegalArgumentException("Datum is not a blob");
}
byte[] blob = blobs.get(((APIModel.BlobDatum) result.result).blob.blobId);
try {
ObjectInputStream oos = new ObjectInputStream(new ByteArrayInputStream(blob));
return type.cast(oos.readObject());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/test/java/com/fnproject/fn/runtime/flow/RemoteFlowApiClientTest.java | flow-runtime/src/test/java/com/fnproject/fn/runtime/flow/RemoteFlowApiClientTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.flow.FlowCompletionException;
import com.fnproject.fn.api.flow.Flows;
import com.fnproject.fn.api.flow.HttpMethod;
import com.fnproject.fn.runtime.exception.PlatformCommunicationException;
import com.fnproject.fn.runtime.flow.*;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentMatcher;
import org.mockito.internal.progress.ThreadSafeMockingProgress;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.*;
public class RemoteFlowApiClientTest {
private HttpClient mockHttpClient = mock(HttpClient.class, RETURNS_DEEP_STUBS);
private BlobStoreClient blobStoreClient = mock(BlobStoreClient.class);
private RemoteFlowApiClient completerClient = new RemoteFlowApiClient("", blobStoreClient, mockHttpClient);
private ObjectMapper objectMapper = new ObjectMapper();
private final Flows.SerCallable<Integer> serializableLambda = () -> 42;
private final CodeLocation codeLocation = locationFn();
private final byte[] lambdaBytes;
private final String testFlowId = "TEST";
private final String testStageId = "STAGEID";
{
try {
lambdaBytes = serializeObject(serializableLambda);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setup() {
FlowRuntimeGlobals.setCurrentCompletionId(new CompletionId("CallerId"));
}
@Test
public void createFlow() throws Exception {
// Given
String functionId = "functionId";
HttpClient.HttpResponse response = responseWithCreateGraphResponse(testFlowId);
when(mockHttpClient.execute(requestContainingFunctionId(functionId))).thenReturn(response);
// When
FlowId flowId = completerClient.createFlow(functionId);
// Then
assertNotNull(flowId);
assertEquals(flowId.getId(), testFlowId);
}
@Test
public void supply() throws Exception {
// Given
String contentType = "application/java-serialized-object";
String testBlobId = "BLOBID";
BlobResponse blobResponse = makeBlobResponse(lambdaBytes, contentType, testBlobId);
when(blobStoreClient.writeBlob(testFlowId, lambdaBytes, contentType)).thenReturn(blobResponse);
HttpClient.HttpResponse response = responseWithAddStageResponse(testFlowId, testStageId);
when(mockHttpClient.execute(requestContainingAddStageRequest(blobResponse.blobId, Collections.emptyList()))).thenReturn(response);
// When
CompletionId completionId = completerClient.supply(new FlowId(testFlowId), serializableLambda, codeLocation);
// Then
assertNotNull(completionId);
assertEquals(completionId.getId(), testStageId);
}
@Test
public void invokeFunctionNormally() throws Exception {
// Given
String testFunctionId = "TESTFUNCTION";
String blobid = "BLOBID";
byte[] invokeBody = "INPUTDATA".getBytes();
String contentType = "text/plain";
BlobResponse blobResponse = makeBlobResponse(invokeBody, contentType, blobid);
when(blobStoreClient.writeBlob(eq(testFlowId), eq(invokeBody), eq(contentType))).thenReturn(blobResponse);
HttpClient.HttpResponse response = responseWithAddStageResponse(testFlowId, testStageId);
when(mockHttpClient.execute(requestContainingAddInvokeFunctionStageRequest(testFunctionId, APIModel.HTTPMethod.Post))).thenReturn(response);
// When
CompletionId completionId = completerClient.invokeFunction(new FlowId(testFlowId), testFunctionId, invokeBody, HttpMethod.POST, Headers.fromMap(Collections.singletonMap("Content-type", contentType)), CodeLocation.unknownLocation());
// Then
assertNotNull(completionId);
assertEquals(completionId.getId(), testStageId);
}
@Test
public void invokeFunctionWithInvalidFunctionId() throws Exception {
// Given
String testFunctionId = "INVALIDFUNCTIONID";
byte[] invokeBody = "INPUTDATA".getBytes();
String contentType = "text/plain";
BlobResponse blobResponse = makeBlobResponse(invokeBody, contentType, "BLOBID");
when(blobStoreClient.writeBlob(testFlowId, invokeBody, contentType)).thenReturn(blobResponse);
when(mockHttpClient.execute(requestContainingAddInvokeFunctionStageRequest(testFunctionId, APIModel.HTTPMethod.Post))).thenReturn(new HttpClient.HttpResponse(400));
// Then
thrown.expect(PlatformCommunicationException.class);
thrown.expectMessage("Failed to add stage");
// When
Map headersMap = Collections.singletonMap("Content-type", contentType);
Headers headers = Headers.fromMap(headersMap);
completerClient.invokeFunction(new FlowId(testFlowId), testFunctionId, invokeBody, HttpMethod.POST, headers, locationFn());
}
@Test
public void waitForCompletionNormally() throws Exception {
// Given
String testBlobId = "BLOBID";
String testContentType = "application/java-serialized-object";
APIModel.Blob blob = new APIModel.Blob();
blob.blobId = testBlobId;
blob.contentType = testContentType;
APIModel.CompletionResult completionResult = APIModel.CompletionResult.success(APIModel.BlobDatum.fromBlob(blob));
when(mockHttpClient.execute(requestForAwaitStageResult())).thenReturn(responseWithAwaitStageResponse(completionResult));
when(blobStoreClient.readBlob(eq(testFlowId), eq("BLOBID"), any(), eq("application/java-serialized-object"))).thenReturn(1);
// When
Object result = completerClient.waitForCompletion(new FlowId(testFlowId), new CompletionId(testStageId), null);
// Then
assertEquals(result, 1);
}
@Test
public void waitForCompletionOnExceptionallyCompletedStage() throws Exception {
// Given
String testBlobId = "BLOBID";
String testContentType = "application/java-serialized-object";
APIModel.Blob blob = new APIModel.Blob();
blob.blobId = testBlobId;
blob.contentType = testContentType;
APIModel.CompletionResult completionResult = APIModel.CompletionResult.failure(APIModel.BlobDatum.fromBlob(blob));
when(mockHttpClient.execute(requestForAwaitStageResult())).thenReturn(responseWithAwaitStageResponse(completionResult));
class MyException extends RuntimeException {}
MyException myException = new MyException();
when(blobStoreClient.readBlob(eq(testFlowId), eq(testBlobId), any(), eq(testContentType))).thenReturn(myException);
// Then
thrown.expect(new BaseMatcher<Object>() {
@Override
public void describeTo(Description description) {
description.appendText("an exception of type FlowCompletionException, containing a cause of type MyException");
}
@Override
public boolean matches(Object o) {
if(o instanceof FlowCompletionException) {
FlowCompletionException flowCompletionException = (FlowCompletionException) o;
if(flowCompletionException.getCause().equals(myException)) {
return true;
}
}
return false;
}
});
// When
completerClient.waitForCompletion(new FlowId(testFlowId), new CompletionId(testStageId), null);
}
@Test
public void waitForCompletionUnknownStage() throws Exception {
// Given
when(mockHttpClient.execute(requestForAwaitStageResult())).thenReturn(new HttpClient.HttpResponse(404));
// Then
thrown.expect(PlatformCommunicationException.class);
thrown.expectMessage(contains("unexpected response"));
// When
completerClient.waitForCompletion(new FlowId(testFlowId), new CompletionId(testStageId), null);
}
private BlobResponse makeBlobResponse(byte[] invokeBody, String contentType, String blobid) {
BlobResponse blobResponse = new BlobResponse();
blobResponse.blobId = blobid;
blobResponse.blobLength = Long.valueOf(invokeBody.length);
blobResponse.contentType = contentType;
return blobResponse;
}
private HttpClient.HttpResponse responseWithAwaitStageResponse(APIModel.CompletionResult result) throws IOException {
APIModel.AwaitStageResponse awaitStageResponse = new APIModel.AwaitStageResponse();
awaitStageResponse.result = result;
return responseWithJSONBody(awaitStageResponse);
}
private HttpClient.HttpResponse responseWithAddStageResponse(String flowId, String stageId) throws IOException {
APIModel.AddStageResponse addStageResponse = new APIModel.AddStageResponse();
addStageResponse.flowId = flowId;
addStageResponse.stageId = stageId;
return responseWithJSONBody(addStageResponse);
}
private HttpClient.HttpResponse responseWithJSONBody(Object body) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
objectMapper.writeValue(byteArrayOutputStream, body);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
HttpClient.HttpResponse response = new HttpClient.HttpResponse(200);
response.setEntity(byteArrayInputStream);
return response;
}
private HttpClient.HttpResponse responseWithCreateGraphResponse(String flowId) throws IOException {
APIModel.CreateGraphResponse createGraphResponse = new APIModel.CreateGraphResponse();
createGraphResponse.flowId = flowId;
return responseWithJSONBody(createGraphResponse);
}
HttpClient.HttpRequest requestForAwaitStageResult() {
ArgumentMatcher<HttpClient.HttpRequest> argumentMatcher = httpRequest -> {
if(httpRequest.method != "GET") {
System.err.println("Expecting a GET request, got " + httpRequest.method);
return false;
}
return true;
};
ThreadSafeMockingProgress.mockingProgress().getArgumentMatcherStorage().reportMatcher(argumentMatcher);
return null;
}
HttpClient.HttpRequest requestContainingFunctionId(String functionId) {
ArgumentMatcher<HttpClient.HttpRequest> argumentMatcher = httpRequest -> {
if(httpRequest.method != "POST") {
System.err.println("Expecting a POST request, got " + httpRequest.method);
return false;
}
try {
APIModel.CreateGraphRequest createGraphRequest = objectMapper.readValue(new String(httpRequest.bodyBytes), APIModel.CreateGraphRequest.class);
if ((createGraphRequest.functionId != null) && (createGraphRequest.functionId.equals(functionId))) {
return true;
}
System.err.println("Request body doesn't contain an CreateGraphRequest with matching functionId field");
return false;
} catch (IOException e) {
System.err.println("Request body doesn't contain an CreateGraphRequest");
return false;
}
};
ThreadSafeMockingProgress.mockingProgress().getArgumentMatcherStorage().reportMatcher(argumentMatcher);
return null;
}
HttpClient.HttpRequest requestContainingAddStageRequest(String blobId, List<String> dependencies) {
ArgumentMatcher<HttpClient.HttpRequest> argumentMatcher = httpRequest -> {
if(httpRequest.method != "POST") {
System.err.println("Expecting a POST request, got " + httpRequest.method);
return false;
}
try {
APIModel.AddStageRequest addStageRequest = objectMapper.readValue(new String(httpRequest.bodyBytes), APIModel.AddStageRequest.class);
if ( (addStageRequest.closure != null) &&
(addStageRequest.closure.blobId.equals(blobId)) &&
(addStageRequest.deps.equals(dependencies))) {
return true;
}
System.err.println("Request body doesn't contain an AddStageRequest with closure with matching blobId field");
return false;
} catch (IOException e) {
System.err.println("Request body doesn't contain an AddStageRequest");
return false;
}
};
ThreadSafeMockingProgress.mockingProgress().getArgumentMatcherStorage().reportMatcher(argumentMatcher);
return null;
}
HttpClient.HttpRequest requestContainingAddInvokeFunctionStageRequest(String functionId, APIModel.HTTPMethod httpMethod) {
ArgumentMatcher<HttpClient.HttpRequest> argumentMatcher = httpRequest -> {
if(httpRequest.method != "POST") {
System.err.println("Expecting a POST request, got " + httpRequest.method);
return false;
}
try {
APIModel.AddInvokeFunctionStageRequest addInvokeFunctionStageRequest = objectMapper.readValue(new String(httpRequest.bodyBytes), APIModel.AddInvokeFunctionStageRequest.class);
if ((addInvokeFunctionStageRequest.functionId != null) &&
(addInvokeFunctionStageRequest.functionId.equals(functionId)) &&
(addInvokeFunctionStageRequest.arg.method.equals(httpMethod))) {
return true;
} else {
System.err.println("Request body doesn't contain a matching AddInvokeFunctionStageRequest");
}
return false;
} catch (IOException e) {
System.err.println("Request body doesn't contain an AddInvokeFunctionStageRequest");
return false;
}
};
ThreadSafeMockingProgress.mockingProgress().getArgumentMatcherStorage().reportMatcher(argumentMatcher);
return null;
}
private byte[] serializeObject(Object value) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(value);
return byteArrayOutputStream.toByteArray();
}
private static CodeLocation locationFn() {
return CodeLocation.fromCallerLocation(0);
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/test/java/com/fnproject/fn/testing/flowtestfns/FnFlowsFunction.java | flow-runtime/src/test/java/com/fnproject/fn/testing/flowtestfns/FnFlowsFunction.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.testing.flowtestfns;
import com.fnproject.fn.api.FnFeature;
import com.fnproject.fn.api.flow.Flow;
import com.fnproject.fn.api.flow.Flows;
import com.fnproject.fn.runtime.flow.FlowFeature;
import java.io.Serializable;
@FnFeature(FlowFeature.class)
public class FnFlowsFunction implements Serializable {
public static void usingFlows() {
Flows.currentFlow();
}
public static void notUsingFlows() {
}
public static void supply() {
Flow fl = Flows.currentFlow();
fl.supply(() -> 3);
}
public static void accessRuntimeMultipleTimes() {
Flows.currentFlow();
Flows.currentFlow();
}
public static Integer supplyAndGetResult() {
Flow fl = Flows.currentFlow();
Integer res = fl.supply(() -> 3).get();
return res;
}
public static void createFlowAndThenFail() {
Flow fl = Flows.currentFlow();
throw new NullPointerException(fl.toString());
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/CompleterClient.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/CompleterClient.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.flow.HttpMethod;
import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Internal interface to a remote completion service
*/
public interface CompleterClient {
/**
* create a new flow against the flow service
*
* @param functionId Id of the function for which flow needs to be created
* @return a FlowId
*/
FlowId createFlow(String functionId);
CompletionId supply(FlowId flowID, Serializable code, CodeLocation codeLocation);
// thenApply completionID -> DO NOW (result) | new parentId
CompletionId thenApply(FlowId flowID, CompletionId completionId, Serializable consumer, CodeLocation codeLocation);
// thenApply completionID -> DO NOW (result) | new parentId
CompletionId whenComplete(FlowId flowID, CompletionId completionId, Serializable consumer, CodeLocation codeLocation);
/**
* Compose a function into the tree
* The transmitted function is wrapped to convert th ElvisFuture into it's completion iD
*
* @param flowId flowId for thenCompose
* @param completionId completionId for thenCompose
* @param fn fn for thenCompose
* @param codeLocation codeLocation for thenCompose
* @return a completion ID that completes when the completion returned by the inner function completes
*/
CompletionId thenCompose(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation);
// block (indefinitely) until the completion completes
Object waitForCompletion(FlowId flowId, CompletionId id, ClassLoader loader);
// block until the timeout for the completion to complete and throw a TimeoutException upon reaching timeout
Object waitForCompletion(FlowId flowId, CompletionId id, ClassLoader loader, long timeout, TimeUnit unit) throws TimeoutException;
CompletionId thenAccept(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation);
CompletionId thenRun(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation);
CompletionId acceptEither(FlowId flowId, CompletionId completionId, CompletionId alternate, Serializable fn, CodeLocation codeLocation);
CompletionId applyToEither(FlowId flowId, CompletionId completionId, CompletionId alternate, Serializable fn, CodeLocation codeLocation);
boolean complete(FlowId flowId, CompletionId completionId, Object value, CodeLocation codeLocation);
boolean completeExceptionally(FlowId flowId, CompletionId completionId, Throwable value, CodeLocation codeLocation);
CompletionId anyOf(FlowId flowId, List<CompletionId> cids, CodeLocation codeLocation);
CompletionId delay(FlowId flowId, long l, CodeLocation codeLocation);
CompletionId thenAcceptBoth(FlowId flowId, CompletionId completionId, CompletionId alternate, Serializable fn, CodeLocation codeLocation);
CompletionId createCompletion(FlowId flowId, CodeLocation codeLocation);
CompletionId invokeFunction(FlowId flowId, String functionId, byte[] data, HttpMethod method, Headers headers, CodeLocation codeLocation);
CompletionId completedValue(FlowId flowId, boolean success, Object value, CodeLocation codeLocation);
CompletionId allOf(FlowId flowId, List<CompletionId> cids, CodeLocation codeLocation);
CompletionId handle(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation);
CompletionId exceptionally(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation);
CompletionId exceptionallyCompose(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation);
CompletionId thenCombine(FlowId flowId, CompletionId completionId, Serializable fn, CompletionId alternate, CodeLocation codeLocation);
void commit(FlowId flowId);
void addTerminationHook(FlowId flowId, Serializable code, CodeLocation codeLocation);
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/BlobResponse.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/BlobResponse.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import com.fasterxml.jackson.annotation.JsonProperty;
public class BlobResponse {
@JsonProperty("blob_id")
public String blobId;
@JsonProperty("length")
public Long blobLength;
@JsonProperty("content_type")
public String contentType;
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/HttpClient.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/HttpClient.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
public class HttpClient {
private static final int REQUEST_TIMEOUT_MS = 600000;
private static final int CONNECT_TIMEOUT_MS = 1000;
public HttpResponse execute(HttpRequest request) throws IOException {
request.headers.putIfAbsent("Content-Type", "application/octet-stream");
request.headers.putIfAbsent("Accept", "application/octet-stream");
URLConnection connection = request.toUrl().openConnection();
connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
connection.setReadTimeout(REQUEST_TIMEOUT_MS);
for (Map.Entry<String, String> requestHeader : request.headers.entrySet()) {
connection.setRequestProperty(requestHeader.getKey(), requestHeader.getValue());
}
if (request.method.equals("POST")) {
connection.setDoOutput(true); // implies POST
connection.getOutputStream().write(request.bodyBytes);
}
connection.connect();
// DEAL WITH THE RESPONSE
HttpURLConnection httpConn = (HttpURLConnection) connection;
int status = httpConn.getResponseCode();
HttpResponse response = new HttpResponse(status);
for (Map.Entry<String, List<String>> header : httpConn.getHeaderFields().entrySet()) {
if (header.getKey() == null) {
response.setStatusLine(header.getValue().get(0));
} else {
response.addHeader(header.getKey(), header.getValue().get(0));
}
}
if (200 <= status && status < 300) {
response.setEntity(httpConn.getInputStream());
} else {
response.setEntity(httpConn.getErrorStream());
}
return response;
}
public static class HttpResponse implements EntityReader, Closeable {
final int status;
final Map<String, String> headers = new HashMap<>();
String statusLine;
InputStream body = new ByteArrayInputStream(new byte[0]);
public HttpResponse(int status) {
this.status = status;
}
public int getStatusCode() {
return status;
}
public HttpResponse setStatusLine(String statusLine) {
this.statusLine = statusLine;
return this;
}
public HttpResponse addHeader(String name, String value) {
headers.put(name.toLowerCase(), value);
return this;
}
public HttpResponse setEntity(InputStream body) {
this.body = body;
return this;
}
public String getHeader(String headerName) {
return headers.get(headerName.toLowerCase());
}
@Override
public String getHeaderElement(String h, String e) {
// This is ugly: we need to parse a header element here to recover the pieces
return null;
}
@Override
public Optional<String> getHeaderValue(String header) {
return Optional.ofNullable(getHeader(header.toLowerCase()));
}
@Override
public InputStream getContentStream() {
return body;
}
@Override
public Map<String, String> getHeaders() {
return headers;
}
public String entityAsString() throws IOException {
return body == null ? null : IOUtils.toString(body, StandardCharsets.UTF_8);
}
public InputStream getEntity() {
return body;
}
public byte[] entityAsBytes() throws IOException {
return body == null ? null : IOUtils.toByteArray(body);
}
@Override
public String toString() {
return "HttpResponse{" +
"status=" + status +
", statusLine='" + statusLine + '\'' +
", headers=" + headers +
'}';
}
@Override
public void close() throws IOException {
if (body != null) {
body.close();
}
}
}
public static class HttpRequest {
final String method;
final String url;
final Map<String, String> query = new HashMap<>();
byte[] bodyBytes = new byte[0];
final Map<String, String> headers = new HashMap<>();
private HttpRequest(String method, String url) {
this.method = method;
this.url = url;
}
public HttpRequest withQueryParam(String key, String value) {
query.put(key, value);
return this;
}
public HttpRequest withBody(byte[] bodyBytes) {
this.bodyBytes = bodyBytes;
return this;
}
public HttpRequest withHeader(String header, String value) {
headers.put(header, value);
return this;
}
private String enc(String s) {
try {
return URLEncoder.encode(s, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 is not a supported encoding on this platform. Where are we?", e);
}
}
private URL toUrl() throws IOException {
String queryParams = query.entrySet().stream().map((kv) -> enc(kv.getKey()) + "=" + enc(kv.getValue())).collect(Collectors.joining("&"));
URL url = new URL(this.url + (queryParams.isEmpty() ? "" : "?" + queryParams));
return url;
}
public HttpRequest withAdditionalHeaders(Map<String, String> additionalHeaders) {
this.headers.putAll(additionalHeaders);
return this;
}
}
public static HttpRequest prepareGet(String url) {
return new HttpRequest("GET", url);
}
public static HttpRequest preparePost(String url) {
return new HttpRequest("POST", url);
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/CompletionId.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/CompletionId.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import java.io.Serializable;
import java.util.Objects;
/**
* Value type for a completion ID
*/
public final class CompletionId implements Serializable {
private final String id;
public CompletionId(String id) {
this.id = Objects.requireNonNull(id);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CompletionId that = (CompletionId) o;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
public String getId() {
return id;
}
@Override
public String toString() {
return "#" + getId();
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/FlowContinuationInvoker.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/FlowContinuationInvoker.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fnproject.fn.api.*;
import com.fnproject.fn.api.exception.FunctionInputHandlingException;
import com.fnproject.fn.api.flow.Flow;
import com.fnproject.fn.api.flow.Flows;
import com.fnproject.fn.api.flow.PlatformException;
import com.fnproject.fn.runtime.exception.InternalFunctionInvocationException;
import com.fnproject.fn.runtime.exception.PlatformCommunicationException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.function.*;
import static com.fnproject.fn.runtime.flow.RemoteFlowApiClient.CONTENT_TYPE_JAVA_OBJECT;
/**
* Invoker that handles flow stages
*/
public final class FlowContinuationInvoker implements FunctionInvoker {
private static final String DEFAULT_COMPLETER_BASE_URL = "http://completer-svc:8081";
private static final String COMPLETER_BASE_URL = "COMPLETER_BASE_URL";
public static final String FLOW_ID_HEADER = "Fnproject-FlowId";
FlowContinuationInvoker() {
}
private static class URLCompleterClientFactory implements CompleterClientFactory {
private final String completerBaseUrl;
private transient CompleterClient completerClient;
private transient BlobStoreClient blobClient;
URLCompleterClientFactory(String completerBaseUrl) {
this.completerBaseUrl = completerBaseUrl;
}
@Override
public synchronized CompleterClient getCompleterClient() {
if (this.completerClient == null) {
this.completerClient = new RemoteFlowApiClient(completerBaseUrl + "/v1",
getBlobStoreClient(), new HttpClient());
}
return this.completerClient;
}
public synchronized BlobStoreClient getBlobStoreClient() {
if (this.blobClient == null) {
this.blobClient = new RemoteBlobStoreClient(completerBaseUrl + "/blobs", new HttpClient());
}
return this.blobClient;
}
}
/**
* Gets or creates the completer completerClient factory; if it has been overridden, the parameter will be ignored
*
* @param completerBaseUrl the completer base URL to use if and when creating the factory
*/
private static synchronized CompleterClientFactory getOrCreateCompleterClientFactory(String completerBaseUrl) {
if (FlowRuntimeGlobals.getCompleterClientFactory() == null) {
FlowRuntimeGlobals.setCompleterClientFactory(new URLCompleterClientFactory(completerBaseUrl));
}
return FlowRuntimeGlobals.getCompleterClientFactory();
}
/**
* Invoke the function wrapped by this loader
*
* @param evt The function event
* @return the function response
*/
@Override
public Optional<OutputEvent> tryInvoke(InvocationContext ctx, InputEvent evt) {
Optional<String> graphIdOption = evt.getHeaders().get(FLOW_ID_HEADER);
final String completerBaseUrl = ctx.getRuntimeContext().getConfigurationByKey(COMPLETER_BASE_URL).orElse(DEFAULT_COMPLETER_BASE_URL);
if (graphIdOption.isPresent()) {
CompleterClientFactory ccf = getOrCreateCompleterClientFactory(completerBaseUrl);
final FlowId flowId = new FlowId(graphIdOption.get());
Flows.FlowSource attachedSource = new Flows.FlowSource() {
Flow runtime;
@Override
public synchronized Flow currentFlow() {
if (runtime == null) {
runtime = new RemoteFlow(flowId);
}
return runtime;
}
};
Flows.setCurrentFlowSource(attachedSource);
try {
return evt.consumeBody((is) -> {
try {
APIModel.InvokeStageRequest invokeStageRequest = FlowRuntimeGlobals.getObjectMapper().readValue(is, APIModel.InvokeStageRequest.class);
HttpClient httpClient = new HttpClient();
BlobStoreClient blobClient = ccf.getBlobStoreClient();
FlowRuntimeGlobals.setCurrentCompletionId(new CompletionId(invokeStageRequest.stageId));
if (invokeStageRequest.closure.contentType.equals(CONTENT_TYPE_JAVA_OBJECT)) {
Object continuation = blobClient.readBlob(flowId.getId(), invokeStageRequest.closure.blobId, (requestInputStream) -> {
try (ObjectInputStream objectInputStream = new ObjectInputStream(requestInputStream)) {
return objectInputStream.readObject();
} catch (IOException | ClassNotFoundException e) {
throw new FunctionInputHandlingException("Error reading continuation content", e);
}
}, invokeStageRequest.closure.contentType);
DispatchPattern matchingDispatchPattern = null;
for (DispatchPattern dp : Dispatchers.values()) {
if (dp.matches(continuation)) {
matchingDispatchPattern = dp;
break;
}
}
if (matchingDispatchPattern != null) {
if (matchingDispatchPattern.numArguments() != invokeStageRequest.args.size()) {
throw new FunctionInputHandlingException("Number of arguments provided (" + invokeStageRequest.args.size() + ") in .InvokeStageRequest does not match the number required by the function type (" + matchingDispatchPattern.numArguments() + ")");
}
} else {
throw new FunctionInputHandlingException("No functional interface type matches the supplied continuation class");
}
Object[] args = invokeStageRequest.args.stream().map(arg -> arg.toJava(flowId, blobClient, getClass().getClassLoader())).toArray();
OutputEvent result = invokeContinuation(blobClient, flowId, continuation, matchingDispatchPattern.getInvokeMethod(continuation), args);
return Optional.of(result);
} else {
throw new FunctionInputHandlingException("Content type of closure isn't a Java serialized object");
}
} catch (IOException e) {
throw new PlatformCommunicationException("Error reading continuation content", e);
}
});
} finally {
Flows.setCurrentFlowSource(null);
FlowRuntimeGlobals.setCurrentCompletionId(null);
}
} else {
Flows.FlowSource deferredSource = new Flows.FlowSource() {
Flow runtime;
@Override
public synchronized Flow currentFlow() {
if (runtime == null) {
String functionId = ctx.getRuntimeContext().getFunctionID();
CompleterClientFactory factory = getOrCreateCompleterClientFactory(completerBaseUrl);
final FlowId flowId = factory.getCompleterClient().createFlow(functionId);
runtime = new RemoteFlow(flowId);
InvocationListener flowInvocationListener = new InvocationListener() {
@Override
public void onSuccess() {
factory.getCompleterClient().commit(flowId);
}
public void onFailure() {
factory.getCompleterClient().commit(flowId);
}
};
ctx.addListener(flowInvocationListener);
}
return runtime;
}
};
// Not a flow invocation
Flows.setCurrentFlowSource(deferredSource);
return Optional.empty();
}
}
private OutputEvent invokeContinuation(BlobStoreClient blobStoreClient, FlowId flowId, Object instance, Method m, Object[] args) {
Object result;
try {
m.setAccessible(true);
result = m.invoke(instance, args);
} catch (InvocationTargetException ite) {
APIModel.Datum datum = APIModel.datumFromJava(flowId, ite.getCause(), blobStoreClient);
throw new InternalFunctionInvocationException(
"Error invoking flows lambda",
ite.getCause(),
constructOutputEvent(datum, false)
);
} catch (Exception ex) {
throw new PlatformException(ex);
}
APIModel.Datum resultDatum = APIModel.datumFromJava(flowId, result, blobStoreClient);
return constructOutputEvent(resultDatum, true);
}
/**
* We want to always return 200, despite success or failure, from a continuation response.
* We don't want to trample on what the use wants from an ordinary function.
*/
final static class ContinuationOutputEvent implements OutputEvent {
private final byte[] body;
private static final Headers headers = Headers.emptyHeaders().setHeader(OutputEvent.CONTENT_TYPE_HEADER, "application/json");
private ContinuationOutputEvent(boolean success, byte[] body) {
this.body = body;
}
@Override
public Status getStatus() {
return Status.Success;
}
@Override
public void writeToOutput(OutputStream out) throws IOException {
out.write(body);
}
@Override
public Headers getHeaders() {
return headers;
}
}
private OutputEvent constructOutputEvent(APIModel.Datum obj, boolean success) {
APIModel.CompletionResult result = new APIModel.CompletionResult();
result.result = obj;
result.successful = success;
APIModel.InvokeStageResponse resp = new APIModel.InvokeStageResponse();
resp.result = result;
String json;
try {
json = FlowRuntimeGlobals.getObjectMapper().writeValueAsString(resp);
} catch (JsonProcessingException e) {
throw new PlatformException("Error writing JSON", e);
}
return new ContinuationOutputEvent(success, json.getBytes());
}
private interface DispatchPattern {
boolean matches(Object instance);
int numArguments();
Method getInvokeMethod(Object instance);
}
/**
* Calling conventions for different target objects
*/
private enum Dispatchers implements DispatchPattern {
CallableDispatch(Callable.class, 0, "call"),
FunctionDispatch(Function.class, 1, "apply"),
BiFunctionDispatch(BiFunction.class, 2, "apply"),
RunnableDispatch(Runnable.class, 0, "run"),
ConsumerDispatch(Consumer.class, 1, "accept"),
BiConsumerDispatch(BiConsumer.class, 2, "accept"),
SupplierDispatch(Supplier.class, 0, "get");
@Override
public boolean matches(Object instance) {
return matchType.isInstance(instance);
}
public int numArguments() {
return numArguments;
}
public Method getInvokeMethod(Object instance) {
try {
Class<?> args[] = new Class[numArguments];
for (int i = 0; i < args.length; i++) {
args[i] = Object.class;
}
return instance.getClass().getMethod(methodName, args);
} catch (Exception e) {
throw new IllegalStateException("Unable to find method " + methodName + " on " + instance.getClass());
}
}
private final Class<?> matchType;
private final int numArguments;
private final String methodName;
Dispatchers(Class<?> matchType, int numArguments, String methodName) {
this.matchType = matchType;
this.numArguments = numArguments;
this.methodName = methodName;
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/BlobStoreClient.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/BlobStoreClient.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import java.io.InputStream;
import java.util.function.Function;
public interface BlobStoreClient {
BlobResponse writeBlob(String prefix, byte[] bytes, String contentType);
<T> T readBlob(String prefix, String blobId, Function<InputStream, T> reader, String expectedContentType);
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/APIModel.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/APIModel.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.exception.FunctionInputHandlingException;
import com.fnproject.fn.api.flow.*;
import com.fnproject.fn.runtime.exception.PlatformCommunicationException;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.util.*;
/**
* Created on 22/11/2017.
* <p>
* (c) 2017 Oracle Corporation
*/
public class APIModel {
enum CompletionOperation {
@JsonProperty("unknown_operation")
UNKNOWN_OPERATION,
@JsonProperty("acceptEither")
ACCEPT_EITHER,
@JsonProperty("applyToEither")
APPLY_TO_EITHER,
@JsonProperty("thenAcceptBoth")
THEN_ACCEPT_BOTH,
@JsonProperty("thenApply")
THEN_APPLY,
@JsonProperty("thenRun")
THEN_RUN,
@JsonProperty("thenAccept")
THEN_ACCEPT,
@JsonProperty("thenCompose")
THEN_COMPOSE,
@JsonProperty("thenCombine")
THEN_COMBINE,
@JsonProperty("whenComplete")
WHEN_COMPLETE,
@JsonProperty("handle")
HANDLE(),
@JsonProperty("supply")
SUPPLY(),
@JsonProperty("invokeFunction")
INVOKE_FUNCTION(),
@JsonProperty("completedValue")
COMPLETED_VALUE(),
@JsonProperty("delay")
DELAY(),
@JsonProperty("allOf")
ALL_OF(),
@JsonProperty("anyOf")
ANY_OF(),
@JsonProperty("externalCompletion")
EXTERNAL_COMPLETION(),
@JsonProperty("exceptionally")
EXCEPTIONALLY(),
@JsonProperty("terminationHook")
TERMINATION_HOOK(),
@JsonProperty("exceptionallyCompose")
EXCEPTIONALLY_COMPOSE();
CompletionOperation() {
}
}
public static final class Blob {
@JsonProperty("blob_id")
public String blobId;
@JsonProperty("length")
public Long blobLength;
@JsonProperty("content_type")
public String contentType;
public static Blob fromBlobResponse(BlobResponse blobResponse) {
Blob blob= new Blob();
blob.blobId = blobResponse.blobId;
blob.contentType = blobResponse.contentType;
blob.blobLength = blobResponse.blobLength;
return blob;
}
}
public static class CompletionResult {
@JsonProperty("datum")
public Datum result;
@JsonProperty("successful")
public boolean successful;
public Object toJava(FlowId flowId, BlobStoreClient blobClient, ClassLoader classLoader) {
return result.toJava(successful, flowId, blobClient, classLoader);
}
public static CompletionResult failure(Datum datum) {
CompletionResult result = new CompletionResult();
result.successful = false;
result.result = datum;
return result;
}
public static CompletionResult success(Datum datum) {
CompletionResult result = new CompletionResult();
result.successful = true;
result.result = datum;
return result;
}
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({
@JsonSubTypes.Type(name = "empty", value = EmptyDatum.class),
@JsonSubTypes.Type(name = "blob", value = BlobDatum.class),
@JsonSubTypes.Type(name = "stage_ref", value = StageRefDatum.class),
@JsonSubTypes.Type(name = "error", value = ErrorDatum.class),
@JsonSubTypes.Type(name = "http_req", value = HTTPReqDatum.class),
@JsonSubTypes.Type(name = "http_resp", value = HTTPRespDatum.class),
@JsonSubTypes.Type(name = "status", value = StatusDatum.class),
})
public static abstract class Datum {
public abstract Object toJava(boolean successful, FlowId flowId, BlobStoreClient blobStore, ClassLoader classLoader);
}
public static final class EmptyDatum extends Datum {
@Override
public Object toJava(boolean successful, FlowId flowId, BlobStoreClient blobStore, ClassLoader classLoader) {
return null;
}
}
public static final class BlobDatum extends Datum {
@JsonUnwrapped
public Blob blob;
@Override
public Object toJava(boolean successful, FlowId flowId, BlobStoreClient blobStore, ClassLoader classLoader) {
return blobStore.readBlob(flowId.getId(), blob.blobId, (requestInputStream) -> {
try (ObjectInputStream ois = new ObjectInputStream(requestInputStream) {
@Override
protected Class resolveClass(ObjectStreamClass classDesc)
throws IOException, ClassNotFoundException {
String cname = classDesc.getName();
try {
return classLoader.loadClass(cname);
} catch (ClassNotFoundException ex) {
return super.resolveClass(classDesc);
}
}
}) {
return ois.readObject();
} catch (ClassNotFoundException | InvalidClassException | StreamCorruptedException | OptionalDataException e) {
throw new FunctionInputHandlingException("Error reading continuation content", e);
} catch (IOException e) {
throw new PlatformException("Error reading blob data", e);
}
}, blob.contentType);
}
public static BlobDatum fromBlob(Blob blob) {
BlobDatum datum = new BlobDatum();
datum.blob = blob;
return datum;
}
}
public static final class StageRefDatum extends Datum {
@JsonProperty("stage_id")
public String stageId;
@Override
public Object toJava(boolean successful, FlowId flowId, BlobStoreClient blobStore, ClassLoader classLoader) {
return ((RemoteFlow) Flows.currentFlow()).createFlowFuture(new CompletionId(stageId));
}
}
public enum ErrorType {
@JsonProperty("unknown_error")
UnknownError(),
@JsonProperty("stage_timeout")
StageTimeout(),
@JsonProperty("stage_failed")
StageFailed(),
@JsonProperty("function_timeout")
FunctionTimeout(),
@JsonProperty("function_invoke_failed")
FunctionInvokeFailed(),
@JsonProperty("stage_lost")
StageLost(),
@JsonProperty("invalid_stage_response")
InvalidStageResponse();
}
public static final class ErrorDatum extends Datum {
@JsonProperty("type")
public ErrorType type;
@JsonProperty("message")
public String message;
@Override
public Object toJava(boolean successful, FlowId flowId, BlobStoreClient blobStore, ClassLoader classLoader) {
switch (type) {
case StageTimeout:
return new StageTimeoutException(message);
case StageLost:
return new StageLostException(message);
case StageFailed:
return new StageInvokeFailedException(message);
case FunctionTimeout:
return new FunctionTimeoutException(message);
case FunctionInvokeFailed:
return new FunctionInvokeFailedException(message);
case InvalidStageResponse:
return new InvalidStageResponseException(message);
default:
return new PlatformException(message);
}
}
public static ErrorDatum newError(ErrorType type, String message) {
ErrorDatum datum = new ErrorDatum();
datum.type = type;
datum.message = message;
return datum;
}
}
public enum HTTPMethod {
@JsonProperty("unknown_method")
UnknownMethod(HttpMethod.GET),
@JsonProperty("get")
Get(HttpMethod.GET),
@JsonProperty("head")
Head(HttpMethod.HEAD),
@JsonProperty("post")
Post(HttpMethod.POST),
@JsonProperty("put")
Put(HttpMethod.PUT),
@JsonProperty("delete")
Delete(HttpMethod.DELETE),
@JsonProperty("options")
Options(HttpMethod.OPTIONS),
@JsonProperty("patch")
Patch(HttpMethod.PATCH);
final HttpMethod flowMethod;
HTTPMethod(HttpMethod flowMethod) {
this.flowMethod = flowMethod;
}
public static HTTPMethod fromFlow(HttpMethod f) {
return Arrays.stream(values())
.filter((x) -> x.flowMethod == f)
.findFirst().orElseThrow(() -> new IllegalArgumentException("Invalid flow method"));
}
}
public static final class HTTPHeader {
@JsonProperty("key")
public String key;
@JsonProperty("value")
public String value;
public static HTTPHeader create(String key, String value) {
HTTPHeader header = new HTTPHeader();
header.key = key;
header.value = value;
return header;
}
}
public static final class HTTPReq {
@JsonProperty("body")
public Blob body;
@JsonProperty("headers")
public List<HTTPHeader> headers;
@JsonProperty("method")
public HTTPMethod method;
}
public static final class HTTPReqDatum extends Datum {
@JsonUnwrapped
public HTTPReq req;
@Override
public Object toJava(boolean successful, FlowId flowId, BlobStoreClient blobStore, ClassLoader classLoader) {
return null;
}
}
public enum StatusDatumType {
@JsonProperty("unknown_state")
UnknownState(Flow.FlowState.UNKNOWN),
@JsonProperty("succeeded")
Succeeded(Flow.FlowState.SUCCEEDED),
@JsonProperty("failed")
Failed(Flow.FlowState.FAILED),
@JsonProperty("cancelled")
Cancelled(Flow.FlowState.CANCELLED),
@JsonProperty("killed")
Killed(Flow.FlowState.KILLED);
private final Flow.FlowState flowState;
StatusDatumType(Flow.FlowState flowState) {
this.flowState = flowState;
}
public Flow.FlowState getFlowState() {
return flowState;
}
}
public static final class StatusDatum extends Datum {
@JsonProperty("type")
public StatusDatumType type;
@Override
public Object toJava(boolean successful, FlowId flowId, BlobStoreClient blobStore, ClassLoader classLoader) {
return type.getFlowState();
}
public static StatusDatum fromType(StatusDatumType type) {
StatusDatum datum = new StatusDatum();
datum.type = type;
return datum;
}
}
public static final class HTTPResp {
@JsonProperty("body")
public Blob body;
@JsonProperty("headers")
public List<HTTPHeader> headers = new ArrayList<>();
@JsonProperty("status_code")
public Integer statusCode;
}
public static final class HTTPRespDatum extends Datum {
@JsonUnwrapped
public HTTPResp resp;
@Override
public Object toJava(boolean successful, FlowId flowId, BlobStoreClient blobStore, ClassLoader classLoader) {
HttpResponse resp = new RemoteHTTPResponse(flowId, this.resp, blobStore);
if (successful) {
return resp;
} else {
return new FunctionInvocationException(resp);
}
}
public static HTTPRespDatum create(HTTPResp res) {
HTTPRespDatum datum = new HTTPRespDatum();
datum.resp = res;
return datum;
}
}
public static Datum datumFromJava(FlowId flow, Object value, BlobStoreClient blobStore) {
if (value == null) {
return new EmptyDatum();
} else if (value instanceof FlowFuture) {
if (!(value instanceof RemoteFlow.RemoteFlowFuture)) {
throw new IllegalStateException("Unsupported flow future type return by function");
}
StageRefDatum datum = new StageRefDatum();
datum.stageId = ((RemoteFlow.RemoteFlowFuture) value).id();
return datum;
} else if (value instanceof RemoteHTTPResponse) {
HTTPRespDatum datum = new HTTPRespDatum();
datum.resp = ((RemoteHTTPResponse) value).response;
return datum;
} else if (value instanceof RemoteHTTPRequest) {
HTTPReqDatum datum = new HTTPReqDatum();
datum.req = ((RemoteHTTPRequest) value).req;
return datum;
} else {
byte[] data;
try {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(value);
oos.close();
data = bos.toByteArray();
} catch (NotSerializableException e) {
if (value instanceof Throwable) {
// unserializable errors are wrapped
WrappedFunctionException wrapped = new WrappedFunctionException((Throwable) value);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(wrapped);
oos.close();
data = bos.toByteArray();
} else {
throw new ResultSerializationException("Value not serializable", e);
}
}
BlobResponse blobResponse = blobStore.writeBlob(flow.getId(), data, RemoteFlowApiClient.CONTENT_TYPE_JAVA_OBJECT);
APIModel.Blob blob = APIModel.Blob.fromBlobResponse(blobResponse);
BlobDatum bd = new BlobDatum();
bd.blob = blob;
return bd;
} catch (IOException e) {
throw new PlatformCommunicationException("Failed to store blob", e);
}
}
}
public static class AddStageResponse {
@JsonProperty("flow_id")
public String flowId;
@JsonProperty("stage_id")
public String stageId;
}
static class CreateGraphResponse {
@JsonProperty("flow_id")
public String flowId;
}
public static class CreateGraphRequest {
public CreateGraphRequest() {
}
public CreateGraphRequest(String functionId) {
this.functionId = functionId;
}
@JsonProperty("function_id")
public String functionId;
}
public static class AddStageRequest {
@JsonProperty("operation")
public CompletionOperation operation;
@JsonProperty("closure")
public Blob closure;
@JsonProperty("deps")
public List<String> deps;
@JsonProperty("code_location")
public String codeLocation;
@JsonProperty("caller_id")
public String callerId;
}
public static class CompleteStageExternallyRequest {
@JsonProperty("value")
public CompletionResult value;
@JsonProperty("code_location")
public String codeLocation;
@JsonProperty("caller_id")
public String callerId;
}
public static class AddCompletedValueStageRequest {
@JsonProperty("value")
public CompletionResult value;
@JsonProperty("code_location")
public String codeLocation;
@JsonProperty("caller_id")
public String callerId;
}
public static class AddDelayStageRequest {
@JsonProperty("delay_ms")
public Long delayMs;
@JsonProperty("code_location")
public String codeLocation;
@JsonProperty("caller_id")
public String callerId;
}
public static class AddInvokeFunctionStageRequest {
@JsonProperty("function_id")
public String functionId;
@JsonProperty("arg")
public HTTPReq arg;
@JsonProperty("code_location")
public String codeLocation;
@JsonProperty("caller_id")
public String callerId;
}
public static class AwaitStageResponse {
@JsonProperty("flow_id")
public String flowId;
@JsonProperty("stage_id")
public String stageId;
@JsonProperty("result")
public CompletionResult result;
}
public static class InvokeStageRequest {
@JsonProperty("flow_id")
public String flowId;
@JsonProperty("stage_id")
public String stageId;
@JsonProperty("closure")
public Blob closure;
@JsonProperty("args")
public List<CompletionResult> args = new ArrayList<>();
}
public static class InvokeStageResponse {
@JsonProperty("result")
public CompletionResult result;
}
private static class RemoteHTTPResponse implements HttpResponse {
private final HTTPResp response;
private final BlobStoreClient blobStoreClient;
private final FlowId flowId;
byte[] body;
RemoteHTTPResponse(FlowId flow, HTTPResp response, BlobStoreClient blobStoreClient) {
this.response = response;
this.blobStoreClient = blobStoreClient;
this.flowId = flow;
}
@Override
public int getStatusCode() {
return response.statusCode;
}
@Override
public Headers getHeaders() {
Map<String, String> headers = new HashMap<>();
response.headers.forEach((h) -> headers.put(h.key, h.value));
return Headers.fromMap(headers);
}
@Override
public byte[] getBodyAsBytes() {
if (body != null) {
return body;
}
return body = readBlobDataAsBytes(blobStoreClient, flowId, response.body);
}
}
private static class RemoteHTTPRequest implements HttpRequest {
private final HTTPReq req;
private final BlobStoreClient blobStoreClient;
private final FlowId flowId;
byte[] body;
RemoteHTTPRequest(FlowId flow, HTTPResp response, HTTPReq req, BlobStoreClient blobStoreClient) {
this.req = req;
this.blobStoreClient = blobStoreClient;
this.flowId = flow;
}
@Override
public HttpMethod getMethod() {
return req.method.flowMethod;
}
@Override
public Headers getHeaders() {
Map<String, String> headers = new HashMap<>();
req.headers.forEach((h) -> headers.put(h.key, h.value));
return Headers.fromMap(headers);
}
@Override
public byte[] getBodyAsBytes() {
if (body != null) {
return body;
}
return body = readBlobDataAsBytes(blobStoreClient, flowId, req.body);
}
}
private static byte[] readBlobDataAsBytes(BlobStoreClient blobStoreClient, FlowId flowId, Blob blob) {
if (blob != null) {
return blobStoreClient.readBlob(flowId.getId(), blob.blobId, (inputStream) -> {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
IOUtils.copy(inputStream, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
} catch (IOException e) {
throw new FunctionInputHandlingException("Unable to read blob");
}
}, blob.contentType);
} else {
return new byte[0];
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/DefaultHttpResponse.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/DefaultHttpResponse.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.flow.HttpResponse;
import java.util.Objects;
/**
* Created on 27/11/2017.
* <p>
* (c) 2017 Oracle Corporation
*/
public class DefaultHttpResponse implements HttpResponse {
private final int statusCode;
private final Headers headers;
private final byte[] body;
public DefaultHttpResponse(int statusCode, Headers headers, byte[] body) {
this.statusCode = statusCode;
this.headers = Objects.requireNonNull(headers);
this.body = Objects.requireNonNull(body);
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public Headers getHeaders() {
return headers;
}
@Override
public byte[] getBodyAsBytes() {
return body;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/RemoteFlowApiClient.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/RemoteFlowApiClient.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.flow.FlowCompletionException;
import com.fnproject.fn.api.flow.HttpMethod;
import com.fnproject.fn.api.flow.LambdaSerializationException;
import com.fnproject.fn.api.flow.PlatformException;
import com.fnproject.fn.runtime.exception.PlatformCommunicationException;
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import static com.fnproject.fn.runtime.flow.HttpClient.prepareGet;
import static com.fnproject.fn.runtime.flow.HttpClient.preparePost;
/**
* REST client for accessing the Flow service API
*/
public class RemoteFlowApiClient implements CompleterClient {
public static final String CONTENT_TYPE_HEADER = "Content-type";
private transient final HttpClient httpClient;
private final String apiUrlBase;
private final BlobStoreClient blobStoreClient;
public static final String CONTENT_TYPE_JAVA_OBJECT = "application/java-serialized-object";
public static final String CONTENT_TYPE_OCTET_STREAM = "application/octet-stream";
public RemoteFlowApiClient(String apiUrlBase, BlobStoreClient blobClient, HttpClient httpClient) {
this.apiUrlBase = Objects.requireNonNull(apiUrlBase);
this.blobStoreClient = Objects.requireNonNull(blobClient);
this.httpClient = Objects.requireNonNull(httpClient);
}
@Override
public FlowId createFlow(String functionId) {
try {
APIModel.CreateGraphRequest createGraphRequest = new APIModel.CreateGraphRequest(functionId);
ObjectMapper objectMapper = FlowRuntimeGlobals.getObjectMapper();
byte[] body = objectMapper.writeValueAsBytes(createGraphRequest);
HttpClient.HttpRequest request = preparePost(apiUrlBase + "/flows").withBody(body);
try (HttpClient.HttpResponse resp = httpClient.execute(request)) {
validateSuccessful(resp);
APIModel.CreateGraphResponse createGraphResponse = objectMapper.readValue(resp.body, APIModel.CreateGraphResponse.class);
return new FlowId(createGraphResponse.flowId);
} catch (Exception e) {
throw new PlatformCommunicationException("Failed to create flow ", e);
}
} catch (IOException e) {
throw new PlatformCommunicationException("Failed to create CreateGraphRequest");
}
}
@Override
public CompletionId supply(FlowId flowId, Serializable supplier, CodeLocation codeLocation) {
return addStageWithClosure(APIModel.CompletionOperation.SUPPLY, flowId, supplier, codeLocation, Collections.emptyList());
}
@Override
public CompletionId thenApply(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation) {
return addStageWithClosure(APIModel.CompletionOperation.THEN_APPLY, flowId, fn, codeLocation, Collections.singletonList(completionId));
}
@Override
public CompletionId thenCompose(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation) {
return addStageWithClosure(APIModel.CompletionOperation.THEN_COMPOSE, flowId, fn, codeLocation, Collections.singletonList(completionId));
}
@Override
public CompletionId whenComplete(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation) {
return addStageWithClosure(APIModel.CompletionOperation.WHEN_COMPLETE, flowId, fn, codeLocation, Collections.singletonList(completionId));
}
@Override
public CompletionId thenAccept(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation) {
return addStageWithClosure(APIModel.CompletionOperation.THEN_ACCEPT, flowId, fn, codeLocation, Collections.singletonList(completionId));
}
@Override
public CompletionId thenRun(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation) {
return addStageWithClosure(APIModel.CompletionOperation.THEN_RUN, flowId, fn, codeLocation, Collections.singletonList(completionId));
}
@Override
public CompletionId acceptEither(FlowId flowId, CompletionId completionId, CompletionId alternate, Serializable fn, CodeLocation codeLocation) {
return addStageWithClosure(APIModel.CompletionOperation.ACCEPT_EITHER, flowId, fn, codeLocation, Arrays.asList(completionId, alternate));
}
@Override
public CompletionId applyToEither(FlowId flowId, CompletionId completionId, CompletionId alternate, Serializable fn, CodeLocation codeLocation) {
return addStageWithClosure(APIModel.CompletionOperation.APPLY_TO_EITHER, flowId, fn, codeLocation, Arrays.asList(completionId, alternate));
}
@Override
public CompletionId thenAcceptBoth(FlowId flowId, CompletionId completionId, CompletionId alternate, Serializable fn, CodeLocation codeLocation) {
return addStageWithClosure(APIModel.CompletionOperation.THEN_ACCEPT_BOTH, flowId, fn, codeLocation, Arrays.asList(completionId, alternate));
}
@Override
public CompletionId createCompletion(FlowId flowId, CodeLocation codeLocation) {
return addStage(APIModel.CompletionOperation.EXTERNAL_COMPLETION, null, Collections.emptyList(), flowId, codeLocation);
}
@Override
public CompletionId invokeFunction(FlowId flowId, String functionId, byte[] data, HttpMethod method, Headers headers, CodeLocation codeLocation) {
APIModel.HTTPReq httpReq = new APIModel.HTTPReq();
if (headers != null) {
if (data.length > 0) {
BlobResponse blobResponse = blobStoreClient.writeBlob(flowId.getId(), data, headers.get(CONTENT_TYPE_HEADER).orElse(CONTENT_TYPE_OCTET_STREAM));
httpReq.body = APIModel.Blob.fromBlobResponse(blobResponse);
}
httpReq.headers = new ArrayList<>();
headers.asMap().forEach((k, vs) -> vs.forEach(v -> httpReq.headers.add(APIModel.HTTPHeader.create(k, v))));
Map<String, List<String>> headersMap = headers.asMap();
headersMap.forEach((key, values) -> values.forEach(value -> httpReq.headers.add(APIModel.HTTPHeader.create(key, value))));
}
httpReq.method = APIModel.HTTPMethod.fromFlow(method);
APIModel.AddInvokeFunctionStageRequest addInvokeFunctionStageRequest = new APIModel.AddInvokeFunctionStageRequest();
addInvokeFunctionStageRequest.arg = httpReq;
addInvokeFunctionStageRequest.codeLocation = codeLocation.getLocation();
addInvokeFunctionStageRequest.callerId = FlowRuntimeGlobals.getCurrentCompletionId().map(CompletionId::getId).orElse(null);
addInvokeFunctionStageRequest.functionId = functionId;
try {
return executeAddInvokeFunctionStageRequest(flowId, addInvokeFunctionStageRequest);
} catch (IOException e) {
throw new PlatformCommunicationException("Failed to create invokeFunction stage", e);
}
}
@Override
public CompletionId completedValue(FlowId flowId, boolean success, Object value, CodeLocation codeLocation) {
try {
APIModel.AddCompletedValueStageRequest addCompletedValueStageRequest = new APIModel.AddCompletedValueStageRequest();
addCompletedValueStageRequest.callerId = FlowRuntimeGlobals.getCurrentCompletionId().map(CompletionId::getId).orElse(null);
addCompletedValueStageRequest.codeLocation = codeLocation.getLocation();
APIModel.CompletionResult completionResult = new APIModel.CompletionResult();
completionResult.successful = success;
if (value instanceof RemoteFlow.RemoteFlowFuture) {
APIModel.StageRefDatum stageRefDatum = new APIModel.StageRefDatum();
stageRefDatum.stageId = ((RemoteFlow.RemoteFlowFuture) value).id();
completionResult.result = stageRefDatum;
} else {
APIModel.Datum blobDatum = APIModel.datumFromJava(flowId, value, blobStoreClient);
completionResult.result = blobDatum;
}
addCompletedValueStageRequest.value = completionResult;
return executeAddCompletedValueStageRequest(flowId, addCompletedValueStageRequest);
} catch (IOException e) {
throw new PlatformCommunicationException("Failed to create completedValue stage", e);
}
}
@Override
public CompletionId allOf(FlowId flowId, List<CompletionId> cids, CodeLocation codeLocation) {
return addStage(APIModel.CompletionOperation.ALL_OF, null, cids, flowId, codeLocation);
}
@Override
public CompletionId handle(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation) {
return addStageWithClosure(APIModel.CompletionOperation.HANDLE, flowId, fn, codeLocation, Collections.singletonList(completionId));
}
@Override
public CompletionId exceptionally(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation) {
return addStageWithClosure(APIModel.CompletionOperation.EXCEPTIONALLY, flowId, fn, codeLocation, Collections.singletonList(completionId));
}
@Override
public CompletionId exceptionallyCompose(FlowId flowId, CompletionId completionId, Serializable fn, CodeLocation codeLocation) {
return addStageWithClosure(APIModel.CompletionOperation.EXCEPTIONALLY_COMPOSE, flowId, fn, codeLocation, Collections.singletonList(completionId));
}
@Override
public CompletionId thenCombine(FlowId flowId, CompletionId completionId, Serializable fn, CompletionId alternate, CodeLocation codeLocation) {
return addStageWithClosure(APIModel.CompletionOperation.THEN_COMBINE, flowId, fn, codeLocation, Arrays.asList(completionId, alternate));
}
@Override
public boolean complete(FlowId flowId, CompletionId completionId, Object value, CodeLocation codeLocation) {
try {
APIModel.Datum blobDatum = APIModel.datumFromJava(flowId, value, blobStoreClient);
APIModel.CompletionResult completionResult = new APIModel.CompletionResult();
completionResult.result = blobDatum;
completionResult.successful = true;
return completeStageExternally(flowId, completionId, completionResult, codeLocation);
} catch (IOException e) {
throw new PlatformCommunicationException("Failed to complete stage externally", e);
}
}
@Override
public boolean completeExceptionally(FlowId flowId, CompletionId completionId, Throwable value, CodeLocation codeLocation) {
try {
APIModel.Datum blobDatum = APIModel.datumFromJava(flowId, value, blobStoreClient);
APIModel.CompletionResult completionResult = new APIModel.CompletionResult();
completionResult.result = blobDatum;
completionResult.successful = false;
return completeStageExternally(flowId, completionId, completionResult, codeLocation);
} catch (IOException e) {
throw new PlatformCommunicationException("Failed to complete stage externally", e);
}
}
@Override
public CompletionId anyOf(FlowId flowId, List<CompletionId> cids, CodeLocation codeLocation) {
return addStage(APIModel.CompletionOperation.ANY_OF, null, cids, flowId, codeLocation);
}
@Override
public CompletionId delay(FlowId flowId, long l, CodeLocation codeLocation) {
try {
APIModel.AddDelayStageRequest addDelayStageRequest = new APIModel.AddDelayStageRequest();
addDelayStageRequest.callerId = FlowRuntimeGlobals.getCurrentCompletionId().map(CompletionId::getId).orElse(null);
addDelayStageRequest.codeLocation = codeLocation.getLocation();
addDelayStageRequest.delayMs = l;
return executeAddDelayStageRequest(flowId, addDelayStageRequest);
} catch (IOException e) {
throw new PlatformCommunicationException("Failed to create completedValue stage", e);
}
}
// wait for completion -> result
@Override
public Object waitForCompletion(FlowId flowId, CompletionId id, ClassLoader ignored, long timeout, TimeUnit unit) throws TimeoutException {
long msTimeout = TimeUnit.MILLISECONDS.convert(timeout, unit);
long start = System.currentTimeMillis();
do {
long lastStart = System.currentTimeMillis();
long remainingTimeout = Math.max(1, start + msTimeout - lastStart);
try (HttpClient.HttpResponse response =
httpClient.execute(prepareGet(apiUrlBase + "/flows/" + flowId.getId() + "/stages/" + id.getId() + "/await?timeout_ms=" + remainingTimeout))) {
if (response.getStatusCode() == 200) {
APIModel.AwaitStageResponse resp = FlowRuntimeGlobals.getObjectMapper().readValue(response.getContentStream(), APIModel.AwaitStageResponse.class);
if (resp.result.successful) {
return resp.result.toJava(flowId, blobStoreClient, getClass().getClassLoader());
} else {
throw new FlowCompletionException((Throwable) resp.result.toJava(flowId, blobStoreClient, getClass().getClassLoader()));
}
} else if (response.getStatusCode() == 408) {
// do nothing go round again
} else {
throw asError(response);
}
try {
Thread.sleep(Math.max(0, 500 - (System.currentTimeMillis() - lastStart)));
} catch (InterruptedException e) {
throw new PlatformCommunicationException("Interrupted", e);
}
} catch (IOException e) {
throw new PlatformCommunicationException("Error fetching result", e);
}
} while (System.currentTimeMillis() - start < msTimeout);
throw new TimeoutException("Stage did not completed before timeout ");
}
@Override
public Object waitForCompletion(FlowId flowId, CompletionId id, ClassLoader ignored) {
try {
return waitForCompletion(flowId, id, ignored, 10, TimeUnit.MINUTES);
} catch (TimeoutException e) {
throw new PlatformCommunicationException("timeout", e);
}
}
public void commit(FlowId flowId) {
try (HttpClient.HttpResponse response = httpClient.execute(preparePost(apiUrlBase + "/flows/" + flowId.getId() + "/commit"))) {
validateSuccessful(response);
} catch (Exception e) {
throw new PlatformCommunicationException("Failed to commit graph", e);
}
}
@Override
public void addTerminationHook(FlowId flowId, Serializable code, CodeLocation codeLocation) {
addStageWithClosure(APIModel.CompletionOperation.TERMINATION_HOOK, flowId, code, codeLocation, Collections.emptyList());
}
private static void validateSuccessful(HttpClient.HttpResponse response) {
if (!isSuccessful(response)) {
throw asError(response);
}
}
private static PlatformCommunicationException asError(HttpClient.HttpResponse response) {
try {
String body = response.entityAsString();
return new PlatformCommunicationException(String.format("Received unexpected response (%d) from " +
"Flow service: %s", response.getStatusCode(), body == null ? "Empty body" : body));
} catch (IOException e) {
return new PlatformCommunicationException(String.format("Received unexpected response (%d) from " +
"Flow service. Could not read body.", response.getStatusCode()), e);
}
}
private static boolean isSuccessful(HttpClient.HttpResponse response) {
return response.getStatusCode() == 200 || response.getStatusCode() == 201;
}
private static byte[] serializeClosure(Object data) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(data);
oos.close();
return bos.toByteArray();
} catch (NotSerializableException nse) {
throw new LambdaSerializationException("Closure not serializable", nse);
} catch (IOException e) {
throw new PlatformException("Failed to write closure", e);
}
}
private CompletionId addStageWithClosure(APIModel.CompletionOperation operation, FlowId flowId, Serializable supplier, CodeLocation codeLocation, List<CompletionId> deps) {
byte[] serialized = serializeClosure(supplier);
BlobResponse blobResponse = blobStoreClient.writeBlob(flowId.getId(), serialized, CONTENT_TYPE_JAVA_OBJECT);
return addStage(operation, APIModel.Blob.fromBlobResponse(blobResponse), deps, flowId, codeLocation);
}
private CompletionId addStage(APIModel.CompletionOperation operation, APIModel.Blob closure, List<CompletionId> deps, FlowId flowId, CodeLocation codeLocation) {
try {
APIModel.AddStageRequest addStageRequest = new APIModel.AddStageRequest();
addStageRequest.closure = closure;
addStageRequest.operation = operation;
addStageRequest.codeLocation = codeLocation.getLocation();
addStageRequest.callerId = FlowRuntimeGlobals.getCurrentCompletionId().map(CompletionId::getId).orElse(null);
addStageRequest.deps = deps.stream().map(dep -> dep.getId()).collect(Collectors.toList());
return executeAddStageRequest(flowId, addStageRequest);
} catch (IOException e) {
throw new PlatformException("Failed to add stage", e);
}
}
private CompletionId executeAddStageRequest(FlowId flowId, APIModel.AddStageRequest addStageRequest) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FlowRuntimeGlobals.getObjectMapper().writeValue(baos, addStageRequest);
HttpClient.HttpRequest request = preparePost(apiUrlBase + "/flows/" + flowId.getId() + "/stage").withBody(baos.toByteArray());
return requestForCompletionId(request);
}
private CompletionId executeAddCompletedValueStageRequest(FlowId flowId, APIModel.AddCompletedValueStageRequest addCompletedValueStageRequest) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FlowRuntimeGlobals.getObjectMapper().writeValue(baos, addCompletedValueStageRequest);
HttpClient.HttpRequest request = preparePost(apiUrlBase + "/flows/" + flowId.getId() + "/value").withBody(baos.toByteArray());
return requestForCompletionId(request);
}
private CompletionId requestForCompletionId(HttpClient.HttpRequest request) {
try (HttpClient.HttpResponse resp = httpClient.execute(request)) {
validateSuccessful(resp);
APIModel.AddStageResponse addStageResponse = FlowRuntimeGlobals.getObjectMapper().readValue(resp.body, APIModel.AddStageResponse.class);
return new CompletionId(addStageResponse.stageId);
} catch (Exception e) {
throw new PlatformCommunicationException("Failed to add stage ", e);
}
}
private CompletionId executeAddInvokeFunctionStageRequest(FlowId flowId, APIModel.AddInvokeFunctionStageRequest addInvokeFunctionStageRequest) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FlowRuntimeGlobals.getObjectMapper().writeValue(baos, addInvokeFunctionStageRequest);
byte[] bytes = baos.toByteArray();
return requestForCompletionId(preparePost(apiUrlBase + "/flows/" + flowId.getId() + "/invoke").withBody(bytes));
}
private CompletionId executeAddDelayStageRequest(FlowId flowId, APIModel.AddDelayStageRequest addDelayStageRequest) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FlowRuntimeGlobals.getObjectMapper().writeValue(baos, addDelayStageRequest);
byte[] bytes = baos.toByteArray();
HttpClient.HttpRequest request = preparePost(apiUrlBase + "/flows/" + flowId.getId() + "/delay").withBody(bytes);
return requestForCompletionId(request);
}
private boolean completeStageExternally(FlowId flowId, CompletionId completionId, APIModel.CompletionResult completionResult, CodeLocation codeLocation) throws IOException {
APIModel.CompleteStageExternallyRequest completeStageExternallyRequest = new APIModel.CompleteStageExternallyRequest();
completeStageExternallyRequest.callerId = FlowRuntimeGlobals.getCurrentCompletionId().map(CompletionId::getId).orElse(null);
completeStageExternallyRequest.value = completionResult;
completeStageExternallyRequest.codeLocation = codeLocation.getLocation();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FlowRuntimeGlobals.getObjectMapper().writeValue(baos, completeStageExternallyRequest);
byte[] bytes = baos.toByteArray();
HttpClient.HttpRequest request = preparePost(apiUrlBase + "/flows/" + flowId.getId() + "/stages/" + completionId.getId() + "/complete").withBody(bytes);
try (HttpClient.HttpResponse resp = httpClient.execute(request)) {
return isSuccessful(resp);
} catch (Exception e) {
throw new PlatformCommunicationException("Failed to add stage ", e);
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/CodeLocation.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/CodeLocation.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import java.util.Objects;
/**
* Class used to return the code location of the caller
*/
public class CodeLocation {
private static CodeLocation UNKNOWN_LOCATION= new CodeLocation("unknown location");
private final String location;
private CodeLocation(String location) {
this.location = Objects.requireNonNull(location);
}
public String getLocation(){
return location;
}
/**
* Create a code location based on an offset of the stack of the current caller
*
* A stack offset of zero represents the calling method and one represents the caller of the calling method
* If no location information is available then an {@link #unknownLocation()} is returned
*
* @param stackOffset depth into the stack relative to the calling method to get the location
* @return the code location for the call
*/
public static CodeLocation fromCallerLocation(int stackOffset){
if(stackOffset < 0){
throw new IllegalArgumentException("stackOffset must be positive");
}
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
if(stack.length < stackOffset + 3){
return UNKNOWN_LOCATION;
} else {
StackTraceElement elem = stack[stackOffset + 2];
return new CodeLocation(elem.toString());
}
}
/**
* Creates a code location representing an unknown source location
* @return a code location
*/
public static CodeLocation unknownLocation(){
return UNKNOWN_LOCATION;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/RemoteFlow.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/RemoteFlow.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.flow.*;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CancellationException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
/**
* REST flows runtime
* <p>
* This
*/
public final class RemoteFlow implements Flow, Serializable, FlowFutureSource {
private transient CompleterClient client;
private final FlowId flowId;
RemoteFlow(FlowId flowId) {
this.flowId = Objects.requireNonNull(flowId);
}
private CompleterClient getClient() {
if (client == null) {
client = FlowRuntimeGlobals.getCompleterClientFactory().getCompleterClient();
}
return client;
}
@Override
public <V> FlowFuture<V> createFlowFuture(CompletionId completionId) {
return new RemoteFlowFuture<>(completionId);
}
public FlowId getFlowId() {
return flowId;
}
class RemoteFlowFuture<T> implements FlowFuture<T>, Serializable {
private final CompletionId completionId;
RemoteFlowFuture(CompletionId completionId) {
this.completionId = Objects.requireNonNull(completionId, "completionId");
}
@Override
public <U> FlowFuture<U> thenApply(Flows.SerFunction<T, U> fn) {
CompletionId newcid = getClient().thenApply(flowId, completionId, fn, CodeLocation.fromCallerLocation(1));
return new RemoteFlowFuture<>(newcid);
}
@Override
public <X> FlowFuture<X> thenCompose(Flows.SerFunction<T, FlowFuture<X>> fn) {
CompletionId newCid = getClient().thenCompose(flowId, completionId, fn, CodeLocation.fromCallerLocation(1));
return new RemoteFlowFuture<>(newCid);
}
@Override
public FlowFuture<T> exceptionallyCompose(Flows.SerFunction<Throwable, FlowFuture<T>> fn) {
return new RemoteFlowFuture<>(getClient().exceptionallyCompose(flowId, completionId, fn, CodeLocation.fromCallerLocation(1)));
}
@Override
public FlowFuture<T> whenComplete(Flows.SerBiConsumer<T, Throwable> fn) {
return new RemoteFlowFuture<>(getClient().whenComplete(flowId, completionId, fn, CodeLocation.fromCallerLocation(1)));
}
@Override
public boolean complete(T value) {
return getClient().complete(flowId, completionId, value, CodeLocation.fromCallerLocation(1));
}
@Override
public boolean completeExceptionally(Throwable throwable) {
return getClient().completeExceptionally(flowId, completionId, throwable, CodeLocation.fromCallerLocation(1));
}
@Override
public boolean cancel() {
return getClient().completeExceptionally(flowId, completionId, new CancellationException(), CodeLocation.fromCallerLocation(1));
}
@Override
public FlowFuture<Void> thenAccept(Flows.SerConsumer<T> fn) {
return new RemoteFlowFuture<>(getClient().thenAccept(flowId, completionId, fn, CodeLocation.fromCallerLocation(1)));
}
@Override
public FlowFuture<Void> acceptEither(FlowFuture<? extends T> alt, Flows.SerConsumer<T> fn) {
return new RemoteFlowFuture<>(getClient().acceptEither(flowId, completionId, ((RemoteFlowFuture<?>) alt).completionId, fn, CodeLocation.fromCallerLocation(1)));
}
@Override
public <X> FlowFuture<X> applyToEither(FlowFuture<? extends T> alt, Flows.SerFunction<T, X> fn) {
return new RemoteFlowFuture<>(getClient().applyToEither(flowId, completionId, ((RemoteFlowFuture<?>) alt).completionId, fn, CodeLocation.fromCallerLocation(1)));
}
@Override
public <X> FlowFuture<Void> thenAcceptBoth(FlowFuture<X> alt, Flows.SerBiConsumer<T, X> fn) {
return new RemoteFlowFuture<>(getClient().thenAcceptBoth(flowId, completionId, ((RemoteFlowFuture<?>) alt).completionId, fn, CodeLocation.fromCallerLocation(1)));
}
@Override
public FlowFuture<Void> thenRun(Flows.SerRunnable fn) {
return new RemoteFlowFuture<>(getClient().thenRun(flowId, completionId, fn, CodeLocation.fromCallerLocation(1)));
}
@Override
public <X> FlowFuture<X> handle(Flows.SerBiFunction<? super T, Throwable, ? extends X> fn) {
return new RemoteFlowFuture<>(getClient().handle(flowId, completionId, fn, CodeLocation.fromCallerLocation(1)));
}
@Override
public FlowFuture<T> exceptionally(Flows.SerFunction<Throwable, ? extends T> fn) {
return new RemoteFlowFuture<>(getClient().exceptionally(flowId, completionId, fn, CodeLocation.fromCallerLocation(1)));
}
@Override
public <U, X> FlowFuture<X> thenCombine(FlowFuture<? extends U> other, Flows.SerBiFunction<? super T, ? super U, ? extends X> fn) {
return new RemoteFlowFuture<>(getClient().thenCombine(flowId, completionId, fn, ((RemoteFlowFuture<?>) other).completionId, CodeLocation.fromCallerLocation(1)));
}
@Override
public T get() {
return (T) getClient().waitForCompletion(flowId, completionId, getClass().getClassLoader());
}
@Override
public T get(long timeout, TimeUnit unit) throws TimeoutException {
return (T) getClient().waitForCompletion(flowId, completionId, getClass().getClassLoader(), timeout, unit);
}
@Override
public T getNow(T valueIfAbsent) {
try {
return get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
return valueIfAbsent;
}
}
public String id() {
return completionId.getId();
}
}
@Override
public FlowFuture<HttpResponse> invokeFunction(String functionId, HttpMethod method, Headers headers, byte[] data) {
CompletionId cid = getClient().invokeFunction(flowId, functionId, data, method, headers, CodeLocation.fromCallerLocation(1));
return new RemoteFlowFuture<>(cid);
}
@Override
public <T extends Serializable, U> FlowFuture<T> invokeFunction(String functionId, HttpMethod method, Headers headers, U input, Class<T> responseType) {
return JsonInvoke.invokeFunction(this, functionId, method, headers, input, responseType);
}
@Override
public <U> FlowFuture<HttpResponse> invokeFunction(String functionId, HttpMethod method, Headers headers, U input) {
return JsonInvoke.invokeFunction(this, functionId, method, headers, input);
}
@Override
public <T> FlowFuture<T> supply(Flows.SerCallable<T> c) {
CompletionId cid = getClient().supply(flowId, c, CodeLocation.fromCallerLocation(1));
return new RemoteFlowFuture<>(cid);
}
@Override
public FlowFuture<Void> supply(Flows.SerRunnable runnable) {
CompletionId cid = getClient().supply(flowId, runnable, CodeLocation.fromCallerLocation(1));
return new RemoteFlowFuture<>(cid);
}
@Override
public FlowFuture<Void> delay(long i, TimeUnit tu) {
if (i < 0) {
throw new IllegalArgumentException("Delay value must be non-negative");
}
CompletionId cid = getClient().delay(flowId, tu.toMillis(i), CodeLocation.fromCallerLocation(1));
return new RemoteFlowFuture<>(cid);
}
@Override
public <T> FlowFuture<T> completedValue(T value) {
return new RemoteFlowFuture<>(getClient().completedValue(flowId, true, value, CodeLocation.fromCallerLocation(1)));
}
@Override
public <T> FlowFuture<T> failedFuture(Throwable ex) {
return new RemoteFlowFuture<>(getClient().completedValue(flowId, false, ex, CodeLocation.fromCallerLocation(1)));
}
@Override
public <T> FlowFuture<T> createFlowFuture() {
return new RemoteFlowFuture<>(getClient().createCompletion(flowId, CodeLocation.fromCallerLocation(1)));
}
@Override
public FlowFuture<Void> allOf(FlowFuture<?>... flowFutures) {
if (flowFutures.length == 0) {
throw new IllegalArgumentException("at least one future must be specified");
}
List<CompletionId> cids = Arrays.stream(flowFutures).map((cf) -> ((RemoteFlowFuture<?>) cf).completionId).collect(Collectors.toList());
CompletionId cid = getClient().allOf(flowId, cids, CodeLocation.fromCallerLocation(1));
return new RemoteFlowFuture<>(cid);
}
@Override
public FlowFuture<Object> anyOf(FlowFuture<?>... flowFutures) {
if (flowFutures.length == 0) {
throw new IllegalArgumentException("at least one future must be specified");
}
List<CompletionId> cids = Arrays.stream(flowFutures).map((cf) -> ((RemoteFlowFuture<?>) cf).completionId).collect(Collectors.toList());
CompletionId cid = getClient().anyOf(flowId, cids, CodeLocation.fromCallerLocation(1));
return new RemoteFlowFuture<>(cid);
}
@Override
public Flow addTerminationHook(Flows.SerConsumer<FlowState> hook) {
getClient().addTerminationHook(flowId, hook, CodeLocation.fromCallerLocation(1));
return this;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/FlowRuntimeGlobals.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/FlowRuntimeGlobals.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Objects;
import java.util.Optional;
/**
* Globals for injecting testing and global state into flow
*/
public class FlowRuntimeGlobals {
private static CompleterClientFactory completerClientFactory = null;
private static CompletionId currentCompletionId;
private static ObjectMapper objectMapper;
/**
* Get the default object mapper to use for Flow Invocations
*
* this will return a runtime-local
* @return an initialized objectmapper
*/
public synchronized static ObjectMapper getObjectMapper(){
if(objectMapper == null){
objectMapper = new ObjectMapper();
}
return objectMapper;
}
/**
* Get the current completion ID - returns an empty optional if the current invocation is not a completion
*
* @return a completion ID option (empty of if not in a completion
*/
public static Optional<CompletionId> getCurrentCompletionId() {
return Optional.ofNullable(currentCompletionId);
}
/**
* Set the current Completion ID
* @param completionId a completion ID - set to null to clear the current completion ID
*/
public static void setCurrentCompletionId(CompletionId completionId) {
currentCompletionId = completionId;
}
/**
* Resets the state of the completer client factory to defaults; this is primarily for testing
*/
public static void resetCompleterClientFactory() {
completerClientFactory = null;
}
/**
* override the default completer client factory
*
* @param currentClientFactory a new client factory to be used to create flows
*/
public static void setCompleterClientFactory(CompleterClientFactory currentClientFactory) {
completerClientFactory = Objects.requireNonNull(currentClientFactory);
}
/**
* return the current Fn Flow client factory;
*
* @return a factory of CompleterClient
*/
public static CompleterClientFactory getCompleterClientFactory() {
return completerClientFactory;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/JsonInvoke.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/JsonInvoke.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.flow.Flow;
import com.fnproject.fn.api.flow.FlowFuture;
import com.fnproject.fn.api.flow.HttpMethod;
import com.fnproject.fn.api.flow.HttpResponse;
import java.io.IOException;
import java.io.Serializable;
/**
* Internal Helper for calling JSON functions via the API
* <p>
* Created on 21/09/2017.
* <p>
* (c) 2017 Oracle Corporation
*/
public class JsonInvoke {
private static ObjectMapper om;
private static synchronized ObjectMapper getObjectMapper() {
if (om == null) {
om = new ObjectMapper();
}
return om;
}
/**
* Invoke a JSON function on a given flow by mapping the input to JSON and composing a result stage that maps the argument back into the requested type.
*
* @param flow the flow to invoke the subsequent call onto
* @param functionId the function ID to invoke
* @param method the HTTP method to use
* @param headers additional headers to pass - the content
* @param input the input object
* @param responseType the response type to map the function result to
* @param <T> the return type
* @param <U> the input type
* @return a future that returns the object value of JSON function or throws an error if that function fails.
*/
public static <T extends Serializable, U> FlowFuture<T> invokeFunction(Flow flow, String functionId, HttpMethod method, Headers headers, U input, Class<T> responseType) {
return invokeFunction(flow, functionId, method, headers, input)
.thenApply((httpResponse) -> {
try {
return getObjectMapper().readValue(httpResponse.getBodyAsBytes(), responseType);
} catch (IOException e) {
throw new IllegalStateException("Failed to extract function response as JSON", e);
}
});
}
/**
* Invoke a void JSON function on a given flow by mapping the input to JSON, returns a future that completes with the HttpResponse of the function
* if the function returns a successful http response, and completes with an error if the function invocation fails.
*
* @param flow the flow to invoke the subsequent call onto
* @param functionId the function ID to invoke
* @param method the HTTP method to use
* @param headers additional headers to pass - the content
* @param input the input object
* @param <U> the input type
* @return a future that returns the object value of JSON function or throws an error if that function fails.
*/
public static <U> FlowFuture<HttpResponse> invokeFunction(Flow flow, String functionId, HttpMethod method, Headers headers, U input) {
try {
String inputString = getObjectMapper().writeValueAsString(input);
Headers newHeaders;
if (!headers.get("Content-type").isPresent()) {
newHeaders = headers.addHeader("Content-type", "application/json");
} else {
newHeaders = headers;
}
return flow.invokeFunction(functionId, method, newHeaders, inputString.getBytes());
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("Failed to coerce function input to JSON", e);
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/FlowId.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/FlowId.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import java.io.Serializable;
import java.util.Objects;
/**
* Flow Identifier
* <p>
* This may be serialized within the runtime class
*/
public final class FlowId implements Serializable {
private final String id;
public FlowId(String id) {
this.id = Objects.requireNonNull(id);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FlowId flowId = (FlowId) o;
return Objects.equals(id, flowId.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
public String getId() {
return id;
}
public String toString() {
return "flow." + getId();
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/RemoteBlobStoreClient.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/RemoteBlobStoreClient.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import com.fnproject.fn.runtime.exception.PlatformCommunicationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.function.Function;
public class RemoteBlobStoreClient implements BlobStoreClient {
private final String apiUrlBase;
private final HttpClient httpClient;
public RemoteBlobStoreClient(String apiUrlBase, HttpClient httpClient) {
this.httpClient = httpClient;
this.apiUrlBase = apiUrlBase;
}
@Override
public BlobResponse writeBlob(String prefix, byte[] bytes, String contentType) {
HttpClient.HttpRequest request = HttpClient.preparePost(apiUrlBase + "/" + prefix)
.withHeader("Content-Type", contentType)
.withBody(bytes);
try (HttpClient.HttpResponse resp = httpClient.execute(request)) {
if (resp.getStatusCode() == 200) {
return FlowRuntimeGlobals.getObjectMapper().readValue(resp.getEntity(), BlobResponse.class);
} else {
throw new PlatformCommunicationException("Failed to write blob, got non 200 response:" + resp.getStatusCode() + " from blob store");
}
} catch (IOException e) {
throw new PlatformCommunicationException("Failed to write blob", e);
}
}
@Override
public <T> T readBlob(String prefix, String blobId, Function<InputStream, T> writer, String expectedContentType) {
HttpClient.HttpRequest request = HttpClient.prepareGet(apiUrlBase + "/" + prefix + "/" + blobId).withHeader("Accept", expectedContentType);
try (HttpClient.HttpResponse resp = httpClient.execute(request)) {
if (resp.getStatusCode() == 200) {
return writer.apply(resp.getContentStream());
} else {
throw new PlatformCommunicationException("Failed to read blob, got non-200 status : " + resp.getStatusCode() + " from blob store");
}
} catch (IOException e) {
throw new PlatformCommunicationException("Failed to read blob", e);
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/EntityReader.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/EntityReader.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import java.io.InputStream;
import java.util.Map;
import java.util.Optional;
/**
* Both an HTTP response and an individual part of a multipart MIME stream are constituted of
* a set of headers together with the body stream. This interface abstracts the access to those parts.
*/
interface EntityReader {
String getHeaderElement(String h, String e);
Optional<String> getHeaderValue(String header);
InputStream getContentStream();
Map<String, String> getHeaders();
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/CompleterClientFactory.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/CompleterClientFactory.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import java.io.Serializable;
public interface CompleterClientFactory extends Serializable {
CompleterClient getCompleterClient();
BlobStoreClient getBlobStoreClient();
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/FlowFeature.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/FlowFeature.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import com.fnproject.fn.api.FunctionInvoker;
import com.fnproject.fn.api.RuntimeContext;
import com.fnproject.fn.api.RuntimeFeature;
/**
*
* The flow feature enables the Flow Client SDK and runtime behaviour in a Java function in order to use Flow in a function you must add the following to the function class:
*
*
* <code>
* import com.fnproject.fn.api.FnFeature;
* import com.fnproject.fn.runtime.flow.FlowFeature;
*
* {@literal @}FnFeature(FlowFeature.class)
* public class MyFunction {
*
*
* public void myFunction(String input){
* Flows.currentFlow()....
*
* }
* }
*
* </code>
*
* Created on 10/09/2018.
* <p>
* (c) 2018 Oracle Corporation
*/
public class FlowFeature implements RuntimeFeature {
@Override
public void initialize(RuntimeContext context){
FunctionInvoker invoker = new FlowContinuationInvoker();
context.addInvoker(invoker,FunctionInvoker.Phase.PreCall);
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/FlowFutureSource.java | flow-runtime/src/main/java/com/fnproject/fn/runtime/flow/FlowFutureSource.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.flow;
import com.fnproject.fn.api.flow.FlowFuture;
/**
* Created on 27/11/2017.
* <p>
* (c) 2017 Oracle Corporation
*/
public interface FlowFutureSource {
<V> FlowFuture<V> createFlowFuture(CompletionId completionId);
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events-testing/src/test/java/com/fnproject/events/testing/Animal.java | fn-events-testing/src/test/java/com/fnproject/events/testing/Animal.java | package com.fnproject.events.testing;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Animal {
private final String name;
private final int age;
@JsonCreator
public Animal(@JsonProperty("name") String name,
@JsonProperty("age") int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Animal animal = (Animal) o;
return age == animal.age && Objects.equals(name, animal.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "Animal{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events-testing/src/test/java/com/fnproject/events/testing/NotificationTestFeatureTest.java | fn-events-testing/src/test/java/com/fnproject/events/testing/NotificationTestFeatureTest.java | package com.fnproject.events.testing;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import com.fnproject.events.input.NotificationMessage;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.testing.FnTestingRule;
import org.apache.commons.io.IOUtils;
import org.junit.Rule;
import org.junit.Test;
public class NotificationTestFeatureTest {
@Rule
public final FnTestingRule fn = FnTestingRule.createDefault();
NotificationTestFeature feature = NotificationTestFeature.createDefault(fn);
@Test
public void testObjectBody() throws Exception {
Animal animal = new Animal("foo", 3);
NotificationMessage<Animal> req = new NotificationMessage<>(animal, Headers.emptyHeaders());
NotificationTestFeature.NotificationRequestEventBuilder builder = (NotificationTestFeature.NotificationRequestEventBuilder) feature.givenEvent(req);
InputEvent inputEvent = builder.build();
String body = inputEvent.consumeBody(is -> {
try {
return IOUtils.toString(is, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Error reading input as string");
}
});
assertEquals(
"{\"name\":\"foo\",\"age\":3}",
body);
}
@Test
public void testHeadersEmptyList() throws Exception {
NotificationMessage<String> req = new NotificationMessage<>("", Headers.emptyHeaders());
NotificationTestFeature.NotificationRequestEventBuilder builder = (NotificationTestFeature.NotificationRequestEventBuilder) feature.givenEvent(req);
InputEvent inputEvent = builder.build();
assertEquals(Headers.emptyHeaders(), inputEvent.getHeaders());
}
@Test
public void testHeadersList() throws Exception {
Headers headers = Headers.emptyHeaders().addHeader("foo", "bar");
NotificationMessage<String> req = new NotificationMessage<>("", headers);
NotificationTestFeature.NotificationRequestEventBuilder builder = (NotificationTestFeature.NotificationRequestEventBuilder) feature.givenEvent(req);
InputEvent inputEvent = builder.build();
assertEquals("bar", inputEvent.getHeaders().get("foo").get());
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events-testing/src/test/java/com/fnproject/events/testing/APIGatewayTestFeatureTest.java | fn-events-testing/src/test/java/com/fnproject/events/testing/APIGatewayTestFeatureTest.java | package com.fnproject.events.testing;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fnproject.events.input.APIGatewayRequestEvent;
import com.fnproject.events.output.APIGatewayResponseEvent;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.api.httpgateway.HTTPGatewayContext;
import com.fnproject.fn.runtime.httpgateway.QueryParametersImpl;
import com.fnproject.fn.testing.FnEventBuilderJUnit4;
import com.fnproject.fn.testing.FnTestingRule;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.junit.Rule;
import org.junit.Test;
public class APIGatewayTestFeatureTest {
@Rule
public final FnTestingRule fn = FnTestingRule.createDefault();
APIGatewayTestFeature feature = APIGatewayTestFeature.createDefault(fn);
public static class Body {
public final String message;
@JsonCreator
public Body(@JsonProperty("message") String message) {
this.message = message;
}
}
/*
A minimal function that echoes input and captures request.
*/
public String handle(HTTPGatewayContext ctx, InputEvent inputEvent) {
String body = inputEvent.consumeBody(is -> {
try {
return IOUtils.toString(is, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Error reading input as string", e);
}
});
ctx.getHeaders().asMap().forEach((key, value1) -> value1.forEach(value -> {
ctx.addResponseHeader(key, value);
}));
ctx.setStatusCode(200);
return body;
}
@Test
public void testRequestStringifyBody() throws Exception {
Body reqBody = new Body("hello");
APIGatewayRequestEvent req = new APIGatewayRequestEvent(new QueryParametersImpl(), reqBody, "GET", "/v2/employee", Headers.emptyHeaders());
APIGatewayTestFeature.APIGatewayFnEventBuilder builder = (APIGatewayTestFeature.APIGatewayFnEventBuilder) feature.givenEvent(req);
InputEvent inputEvent = builder.build();
String body = inputEvent.consumeBody(is -> {
try {
return IOUtils.toString(is, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Error reading input as string");
}
});
assertEquals("{\"message\":\"hello\"}", body);
}
@Test
public void testRequestUrl() throws Exception {
APIGatewayRequestEvent req = new APIGatewayRequestEvent(new QueryParametersImpl(), null, "GET", "/v2/employee", Headers.emptyHeaders());
APIGatewayTestFeature.APIGatewayFnEventBuilder builder = (APIGatewayTestFeature.APIGatewayFnEventBuilder) feature.givenEvent(req);
InputEvent inputEvent = builder.build();
assertEquals(req.getRequestUrl(), inputEvent.getHeaders().get("Fn-Http-Request-Url").get());
}
@Test
public void testRequestHeaderMethod() throws Exception {
APIGatewayRequestEvent req = new APIGatewayRequestEvent(new QueryParametersImpl(), null, "GET", "/v2/employee", Headers.emptyHeaders());
APIGatewayTestFeature.APIGatewayFnEventBuilder builder = (APIGatewayTestFeature.APIGatewayFnEventBuilder) feature.givenEvent(req);
InputEvent inputEvent = builder.build();
assertEquals(req.getMethod(), inputEvent.getHeaders().get("Fn-Http-Method").get());
}
@Test
public void testRequestQueryParameters() throws Exception {
Map<String, List<String>> queryParams = new HashMap<>();
List<String> paramValues = new ArrayList<>();
paramValues.add("bar");
paramValues.add("foo");
queryParams.put("foo", paramValues);
queryParams.put("spaces", Collections.singletonList("this has spaces"));
APIGatewayRequestEvent req = new APIGatewayRequestEvent(new QueryParametersImpl(queryParams), null, "GET", "/v2/employee", Headers.emptyHeaders());
APIGatewayTestFeature.APIGatewayFnEventBuilder builder = (APIGatewayTestFeature.APIGatewayFnEventBuilder) feature.givenEvent(req);
InputEvent inputEvent = builder.build();
assertEquals("/v2/employee?spaces=this+has+spaces&foo=bar&foo=foo", inputEvent.getHeaders().get("Fn-Http-Request-Url").get());
}
@Test
public void testReturnObjectResponse() throws Exception {
Body reqBody = new Body("hello");
APIGatewayRequestEvent req = new APIGatewayRequestEvent(new QueryParametersImpl(), reqBody, "GET", "/v2/employee", Headers.emptyHeaders());
FnEventBuilderJUnit4 builder = feature.givenEvent(req);
builder.enqueue();
fn.thenRun(APIGatewayTestFeatureTest.class, "handle");
APIGatewayResponseEvent<Body> resp = feature.getResult(Body.class);
assertNotNull(resp.getBody());
assertEquals("hello", resp.getBody().message);
}
@Test
public void testReturnNullObjectResponse() throws Exception {
APIGatewayRequestEvent req = new APIGatewayRequestEvent(new QueryParametersImpl(), null, "GET", "/v2/employee", Headers.emptyHeaders());
FnEventBuilderJUnit4 builder = feature.givenEvent(req);
builder.enqueue();
fn.thenRun(APIGatewayTestFeatureTest.class, "handle");
APIGatewayResponseEvent<Body> resp = feature.getResult(Body.class);
assertNull(resp.getBody());
}
@Test
public void testReturnHeaderResponse() throws Exception {
Headers headers = Headers.emptyHeaders()
.addHeader("Custom", "foo")
.addHeader("Custom", "bar");
APIGatewayRequestEvent req = new APIGatewayRequestEvent(new QueryParametersImpl(), null, "GET", "/v2/employee", headers);
FnEventBuilderJUnit4 builder = feature.givenEvent(req);
builder.enqueue();
fn.thenRun(APIGatewayTestFeatureTest.class, "handle");
APIGatewayResponseEvent<Body> resp = feature.getResult(Body.class);
assertNotNull(resp.getHeaders());
assertEquals("foo", resp.getHeaders().getAllValues("Custom").get(0));
assertEquals("bar", resp.getHeaders().getAllValues("Custom").get(1));
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events-testing/src/test/java/com/fnproject/events/testing/ConnectorHubTestFeatureTest.java | fn-events-testing/src/test/java/com/fnproject/events/testing/ConnectorHubTestFeatureTest.java | package com.fnproject.events.testing;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.fnproject.events.input.ConnectorHubBatch;
import com.fnproject.events.input.sch.Datapoint;
import com.fnproject.events.input.sch.LoggingData;
import com.fnproject.events.input.sch.MetricData;
import com.fnproject.events.input.sch.StreamingData;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.testing.FnTestingRule;
import org.apache.commons.io.IOUtils;
import org.junit.Rule;
import org.junit.Test;
public class ConnectorHubTestFeatureTest {
@Rule
public final FnTestingRule fn = FnTestingRule.createDefault();
ConnectorHubTestFeature feature = ConnectorHubTestFeature.createDefault(fn);
@Test
public void testMetricDataBody() throws Exception {
ConnectorHubBatch<MetricData> req = new ConnectorHubBatch<>(Collections.singletonList(
new MetricData(
"ns",
null,
"compartment",
"name",
new HashMap<>(),
new HashMap<>(),
Collections.singletonList(new Datapoint(
new Date(1764860467553L),
Double.parseDouble("1.2"),
null)
)
)
), Headers.emptyHeaders());
ConnectorHubTestFeature.ConnectorHubRequestEventBuilder builder = (ConnectorHubTestFeature.ConnectorHubRequestEventBuilder) feature.givenEvent(req);
InputEvent inputEvent = builder.build();
String body = inputEvent.consumeBody(is -> {
try {
return IOUtils.toString(is, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Error reading input as string");
}
});
assertEquals(
"[{\"namespace\":\"ns\",\"resourceGroup\":null,\"compartmentId\":\"compartment\",\"name\":\"name\",\"dimensions\":{},\"metadata\":{},\"datapoints\":[{\"timestamp\":1764860467553,\"value\":1.2,\"count\":null}]}]",
body);
}
@Test
public void testMetricEmptyList() throws Exception {
ConnectorHubBatch<MetricData> req = new ConnectorHubBatch<>(Collections.emptyList(), Headers.emptyHeaders());
ConnectorHubTestFeature.ConnectorHubRequestEventBuilder builder = (ConnectorHubTestFeature.ConnectorHubRequestEventBuilder) feature.givenEvent(req);
InputEvent inputEvent = builder.build();
String body = inputEvent.consumeBody(is -> {
try {
return IOUtils.toString(is, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Error reading input as string");
}
});
assertEquals("[]", body);
}
@Test
public void testLoggingDataBody() throws Exception {
Map<String, String> data = new HashMap();
data.put("applicationId", "ocid1.fnapp.oc1.xyz");
data.put("containerId", "n/a");
data.put("functionId", "ocid1.fnfunc.oc1.xyz");
data.put("message", "Received function invocation request");
data.put("opcRequestId", "/abc/def");
data.put("requestId", "/def/abc");
data.put("src", "STDOUT");
Map<String, String> oracle = new HashMap();
oracle.put("compartmentid", "ocid1.tenancy.oc1.xyz");
oracle.put("ingestedtime", "2025-10-23T15:45:19.457Z");
oracle.put("loggroupid", "ocid1.loggroup.oc1.abc");
oracle.put("logid", "ocid1.log.oc1.abc");
oracle.put("tenantid", "ocid1.tenancy.oc1.xyz");
ConnectorHubBatch<LoggingData> req = new ConnectorHubBatch<>(Collections.singletonList(
new LoggingData(
"ecb37864-4396-4302-9575-981644949730",
"log-name",
"1.0",
"schedule",
"com.oraclecloud.functions.application.functioninvoke",
data,
oracle,
new Date(1764860467553L)
)
), Headers.emptyHeaders());
ConnectorHubTestFeature.ConnectorHubRequestEventBuilder builder = (ConnectorHubTestFeature.ConnectorHubRequestEventBuilder) feature.givenEvent(req);
InputEvent inputEvent = builder.build();
String body = inputEvent.consumeBody(is -> {
try {
return IOUtils.toString(is, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Error reading input as string");
}
});
assertEquals(
"[{\"id\":\"ecb37864-4396-4302-9575-981644949730\",\"source\":\"log-name\",\"specversion\":\"1.0\",\"subject\":\"schedule\",\"type\":\"com.oraclecloud.functions.application.functioninvoke\",\"data\":{\"functionId\":\"ocid1.fnfunc.oc1.xyz\",\"opcRequestId\":\"/abc/def\",\"src\":\"STDOUT\",\"requestId\":\"/def/abc\",\"applicationId\":\"ocid1.fnapp.oc1.xyz\",\"containerId\":\"n/a\",\"message\":\"Received function invocation request\"},\"oracle\":{\"compartmentid\":\"ocid1.tenancy.oc1.xyz\",\"ingestedtime\":\"2025-10-23T15:45:19.457Z\",\"loggroupid\":\"ocid1.loggroup.oc1.abc\",\"tenantid\":\"ocid1.tenancy.oc1.xyz\",\"logid\":\"ocid1.log.oc1.abc\"},\"time\":1764860467553}]",
body);
}
@Test
public void testLoggingDataEmptyList() throws Exception {
ConnectorHubBatch<LoggingData> req = new ConnectorHubBatch<>(Collections.emptyList(), Headers.emptyHeaders());
ConnectorHubTestFeature.ConnectorHubRequestEventBuilder builder = (ConnectorHubTestFeature.ConnectorHubRequestEventBuilder) feature.givenEvent(req);
InputEvent inputEvent = builder.build();
String body = inputEvent.consumeBody(is -> {
try {
return IOUtils.toString(is, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Error reading input as string");
}
});
assertEquals("[]", body);
}
@Test
public void testStreamingBody() throws Exception {
Animal animal = new Animal("foo", 4);
StreamingData<Animal> source = new StreamingData<>(
"stream-name",
"0",
null,
animal,
"3",
new Date(1764860467553L)
);
ConnectorHubBatch<StreamingData<Animal>> req = new ConnectorHubBatch<>(Collections.singletonList(
source
), Headers.emptyHeaders());
ConnectorHubTestFeature.ConnectorHubRequestEventBuilder builder = (ConnectorHubTestFeature.ConnectorHubRequestEventBuilder) feature.givenEvent(req);
InputEvent inputEvent = builder.build();
String body = inputEvent.consumeBody(is -> {
try {
return IOUtils.toString(is, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Error reading input as string");
}
});
assertEquals(
"[{\"stream\":\"stream-name\",\"partition\":\"0\",\"key\":null,\"value\":{\"name\":\"foo\",\"age\":4},\"offset\":\"3\",\"timestamp\":1764860467553}]",
body);
}
@Test
public void testStreamingStringBody() throws Exception {
StreamingData<String> source = new StreamingData<>(
"stream-name",
"0",
null,
"a plain string",
"3",
new Date(1764860467553L)
);
ConnectorHubBatch<StreamingData<String>> req = new ConnectorHubBatch<>(Collections.singletonList(
source
), Headers.emptyHeaders());
ConnectorHubTestFeature.ConnectorHubRequestEventBuilder builder = (ConnectorHubTestFeature.ConnectorHubRequestEventBuilder) feature.givenEvent(req);
InputEvent inputEvent = builder.build();
String body = inputEvent.consumeBody(is -> {
try {
return IOUtils.toString(is, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Error reading input as string");
}
});
assertEquals(
"[{\"stream\":\"stream-name\",\"partition\":\"0\",\"key\":null,\"value\":\"a plain string\",\"offset\":\"3\",\"timestamp\":1764860467553}]",
body);
}
@Test
public void testStreamingDataEmptyList() throws Exception {
ConnectorHubBatch<StreamingData<String>> req = new ConnectorHubBatch<>(Collections.emptyList(), Headers.emptyHeaders());
ConnectorHubTestFeature.ConnectorHubRequestEventBuilder builder = (ConnectorHubTestFeature.ConnectorHubRequestEventBuilder) feature.givenEvent(req);
InputEvent inputEvent = builder.build();
String body = inputEvent.consumeBody(is -> {
try {
return IOUtils.toString(is, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Error reading input as string");
}
});
assertEquals("[]", body);
}
@Test
public void testHeadersEmptyList() throws Exception {
ConnectorHubBatch<StreamingData<String>> req = new ConnectorHubBatch<>(Collections.emptyList(), Headers.emptyHeaders());
ConnectorHubTestFeature.ConnectorHubRequestEventBuilder builder = (ConnectorHubTestFeature.ConnectorHubRequestEventBuilder) feature.givenEvent(req);
InputEvent inputEvent = builder.build();
assertEquals(Headers.emptyHeaders(), inputEvent.getHeaders());
}
@Test
public void testHeadersList() throws Exception {
Headers headers = Headers.emptyHeaders().addHeader("foo", "bar");
ConnectorHubBatch<StreamingData<String>> req = new ConnectorHubBatch<>(Collections.emptyList(), headers);
ConnectorHubTestFeature.ConnectorHubRequestEventBuilder builder = (ConnectorHubTestFeature.ConnectorHubRequestEventBuilder) feature.givenEvent(req);
InputEvent inputEvent = builder.build();
assertEquals("bar", inputEvent.getHeaders().get("foo").get());
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events-testing/src/main/java/com/fnproject/events/testing/ConnectorHubTestFeature.java | fn-events-testing/src/main/java/com/fnproject/events/testing/ConnectorHubTestFeature.java | package com.fnproject.events.testing;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fnproject.events.input.ConnectorHubBatch;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.testing.FnEventBuilder;
import com.fnproject.fn.testing.FnEventBuilderJUnit4;
import com.fnproject.fn.testing.FnHttpEventBuilder;
import com.fnproject.fn.testing.FnTestingClassLoader;
import com.fnproject.fn.testing.FnTestingRule;
import com.fnproject.fn.testing.FnTestingRuleFeature;
public class ConnectorHubTestFeature implements FnTestingRuleFeature {
private final FnTestingRule rule;
private final ObjectMapper mapper;
private ConnectorHubTestFeature(FnTestingRule rule) {
this(rule, new ObjectMapper());
}
private ConnectorHubTestFeature(FnTestingRule rule, ObjectMapper mapper) {
this.rule = rule;
this.mapper = mapper;
}
public static ConnectorHubTestFeature createDefault(FnTestingRule rule) {
ConnectorHubTestFeature feature = new ConnectorHubTestFeature(rule);
rule.addFeature(feature);
return feature;
}
@Override
public void prepareTest(ClassLoader functionClassLoader, PrintStream stderr, String cls, String method) {
}
@Override
public void prepareFunctionClassLoader(FnTestingClassLoader cl) {
}
@Override
public void afterTestComplete() {
}
public FnEventBuilderJUnit4 givenEvent(ConnectorHubBatch event) throws JsonProcessingException {
return new ConnectorHubRequestEventBuilder(event);
}
class ConnectorHubRequestEventBuilder implements FnEventBuilderJUnit4 {
FnHttpEventBuilder builder = new FnHttpEventBuilder();
ConnectorHubRequestEventBuilder(ConnectorHubBatch requestEvent) throws JsonProcessingException {
withBody(mapper.writeValueAsBytes(requestEvent.getBatch()));
if (requestEvent.getHeaders() != null) {
requestEvent.getHeaders().asMap().forEach((key, headerValues) -> {
for (String headerValue : headerValues) {
withHeader(key, headerValue);
}
});
}
}
@Override
public FnEventBuilder withHeader(String key, String value) {
builder.withHeader(key, value);
return this;
}
@Override
public FnEventBuilder withBody(InputStream body) throws IOException {
builder.withBody(body);
return this;
}
@Override
public FnEventBuilder withBody(byte[] body) {
builder.withBody(body);
return this;
}
@Override
public FnEventBuilder withBody(String body) {
builder.withBody(body);
return this;
}
@Override
public FnTestingRule enqueue() {
rule.addInput(builder.buildEvent());
return rule;
}
@Override
public FnTestingRule enqueue(int n) {
if (n <= 0) {
throw new IllegalArgumentException("Invalid count");
}
for (int i = 0; i < n; i++) {
enqueue();
}
return rule;
}
InputEvent build() {
return builder.buildEvent();
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events-testing/src/main/java/com/fnproject/events/testing/APIGatewayTestFeature.java | fn-events-testing/src/main/java/com/fnproject/events/testing/APIGatewayTestFeature.java | package com.fnproject.events.testing;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.net.URLEncoder;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fnproject.events.input.APIGatewayRequestEvent;
import com.fnproject.events.output.APIGatewayResponseEvent;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.testing.FnEventBuilder;
import com.fnproject.fn.testing.FnEventBuilderJUnit4;
import com.fnproject.fn.testing.FnHttpEventBuilder;
import com.fnproject.fn.testing.FnResult;
import com.fnproject.fn.testing.FnTestingClassLoader;
import com.fnproject.fn.testing.FnTestingRule;
import com.fnproject.fn.testing.FnTestingRuleFeature;
public class APIGatewayTestFeature implements FnTestingRuleFeature {
private final FnTestingRule rule;
private final ObjectMapper mapper;
private APIGatewayTestFeature(FnTestingRule rule) {
this(rule, new ObjectMapper());
}
private APIGatewayTestFeature(FnTestingRule rule, ObjectMapper mapper) {
this.rule = rule;
this.mapper = mapper;
}
public static APIGatewayTestFeature createDefault(FnTestingRule rule) {
APIGatewayTestFeature feature = new APIGatewayTestFeature(rule);
rule.addFeature(feature);
return feature;
}
@Override
public void prepareTest(ClassLoader functionClassLoader, PrintStream stderr, String cls, String method) {
}
@Override
public void prepareFunctionClassLoader(FnTestingClassLoader cl) {
}
@Override
public void afterTestComplete() {
}
public FnEventBuilderJUnit4 givenEvent(APIGatewayRequestEvent event) throws JsonProcessingException {
return new APIGatewayFnEventBuilder(event);
}
/*
Unwrap output event to APIGatewayResponseEvent type
*/
public <T> APIGatewayResponseEvent<T> getResult(Class<T> tClass) throws IOException {
FnResult result = rule.getOnlyResult();
APIGatewayResponseEvent.Builder<T> responseBuilder =
new APIGatewayResponseEvent.Builder<T>();
if (result.getBodyAsBytes().length != 0) {
T body = mapper.readValue(result.getBodyAsBytes(), tClass);
responseBuilder
.body(body);
}
Map<String, List<String>> myHeaders = new HashMap<>();
result.getHeaders().asMap().forEach((key, headerValues) -> {
if (key.startsWith("Fn-Http-H-")) {
String httpKey = key.substring("Fn-Http-H-".length());
if (!httpKey.isEmpty()) {
myHeaders.put(httpKey, headerValues);
}
}
});
responseBuilder.headers(Headers.emptyHeaders().setHeaders(myHeaders));
if (result.getHeaders().get("Fn-Http-Status").isPresent()) {
int statusCode = Integer.parseInt(result.getHeaders().get("Fn-Http-Status").get());
responseBuilder.statusCode(statusCode);
}
return responseBuilder.build();
}
class APIGatewayFnEventBuilder implements FnEventBuilderJUnit4 {
FnHttpEventBuilder builder = new FnHttpEventBuilder();
APIGatewayFnEventBuilder(APIGatewayRequestEvent requestEvent) throws JsonProcessingException {
withBody(mapper.writeValueAsBytes(requestEvent.getBody()));
if (requestEvent.getMethod() != null) {
withHeader("Fn-Http-Method", requestEvent.getMethod());
}
if (requestEvent.getHeaders() != null) {
requestEvent.getHeaders().asMap().forEach((key, headerValues) -> {
key = "Fn-Http-H-" + key;
for (String headerValue : headerValues) {
withHeader(key, headerValue);
}
});
}
/*
This wraps the test query parameters object into a format the FunctionInvocationContext.class can consume.
*/
String baseUrl = requestEvent.getRequestUrl() != null ? requestEvent.getRequestUrl() : "";
Map<String, List<String>> params = requestEvent.getQueryParameters() != null
? requestEvent.getQueryParameters().getAll()
: Collections.emptyMap();
String query = params.entrySet().stream()
.flatMap(e -> {
String k = urlEncode(e.getKey());
List<String> vs = e.getValue();
if (vs == null || vs.isEmpty()) return Stream.of(k + "=");
return vs.stream().map(v -> k + "=" + urlEncode(v));
})
.collect(Collectors.joining("&"));
withHeader("Fn-Http-Request-Url", query.isEmpty() ? baseUrl : baseUrl + "?" + query);
}
@Override
public FnEventBuilder withHeader(String key, String value) {
builder.withHeader(key, value);
return this;
}
@Override
public FnEventBuilder withBody(InputStream body) throws IOException {
builder.withBody(body);
return this;
}
@Override
public FnEventBuilder withBody(byte[] body) {
builder.withBody(body);
return this;
}
@Override
public FnEventBuilder withBody(String body) {
builder.withBody(body);
return this;
}
@Override
public FnTestingRule enqueue() {
rule.addInput(builder.buildEvent());
return rule;
}
@Override
public FnTestingRule enqueue(int n) {
if (n <= 0) {
throw new IllegalArgumentException("Invalid count");
}
for (int i = 0; i < n; i++) {
enqueue();
}
return rule;
}
InputEvent build() {
return builder.buildEvent();
}
}
private static String urlEncode(String value) {
try {
return URLEncoder.encode(value, StandardCharsets.UTF_8.displayName());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events-testing/src/main/java/com/fnproject/events/testing/NotificationTestFeature.java | fn-events-testing/src/main/java/com/fnproject/events/testing/NotificationTestFeature.java | package com.fnproject.events.testing;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fnproject.events.input.ConnectorHubBatch;
import com.fnproject.events.input.NotificationMessage;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.testing.FnEventBuilder;
import com.fnproject.fn.testing.FnEventBuilderJUnit4;
import com.fnproject.fn.testing.FnHttpEventBuilder;
import com.fnproject.fn.testing.FnTestingClassLoader;
import com.fnproject.fn.testing.FnTestingRule;
import com.fnproject.fn.testing.FnTestingRuleFeature;
public class NotificationTestFeature implements FnTestingRuleFeature {
private final FnTestingRule rule;
private final ObjectMapper mapper;
private NotificationTestFeature(FnTestingRule rule) {
this(rule, new ObjectMapper());
}
private NotificationTestFeature(FnTestingRule rule, ObjectMapper mapper) {
this.rule = rule;
this.mapper = mapper;
}
public static NotificationTestFeature createDefault(FnTestingRule rule) {
NotificationTestFeature feature = new NotificationTestFeature(rule);
rule.addFeature(feature);
return feature;
}
@Override
public void prepareTest(ClassLoader functionClassLoader, PrintStream stderr, String cls, String method) {
}
@Override
public void prepareFunctionClassLoader(FnTestingClassLoader cl) {
}
@Override
public void afterTestComplete() {
}
public FnEventBuilderJUnit4 givenEvent(NotificationMessage<?> event) throws JsonProcessingException {
return new NotificationRequestEventBuilder(event);
}
class NotificationRequestEventBuilder implements FnEventBuilderJUnit4 {
FnHttpEventBuilder builder = new FnHttpEventBuilder();
NotificationRequestEventBuilder(NotificationMessage<?> requestEvent) throws JsonProcessingException {
withBody(mapper.writeValueAsBytes(requestEvent.getContent()));
if (requestEvent.getHeaders() != null) {
requestEvent.getHeaders().asMap().forEach((key, headerValues) -> {
for (String headerValue : headerValues) {
withHeader(key, headerValue);
}
});
}
}
@Override
public FnEventBuilder withHeader(String key, String value) {
builder.withHeader(key, value);
return this;
}
@Override
public FnEventBuilder withBody(InputStream body) throws IOException {
builder.withBody(body);
return this;
}
@Override
public FnEventBuilder withBody(byte[] body) {
builder.withBody(body);
return this;
}
@Override
public FnEventBuilder withBody(String body) {
builder.withBody(body);
return this;
}
@Override
public FnTestingRule enqueue() {
rule.addInput(builder.buildEvent());
return rule;
}
@Override
public FnTestingRule enqueue(int n) {
if (n <= 0) {
throw new IllegalArgumentException("Invalid count");
}
for (int i = 0; i < n; i++) {
enqueue();
}
return rule;
}
InputEvent build() {
return builder.buildEvent();
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/not/in/com/fnproject/fn/StacktraceFilteringTestFunctions.java | runtime/src/test/java/not/in/com/fnproject/fn/StacktraceFilteringTestFunctions.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 not.in.com.fnproject.fn;
import com.fnproject.fn.api.FnConfiguration;
public class StacktraceFilteringTestFunctions {
public static class ExceptionInConstructor {
public ExceptionInConstructor(){
throw new RuntimeException("Whoops I wrote a constructor which throws");
}
public String invoke(){
throw new RuntimeException("This should not be called");
}
}
public static class DeepExceptionInConstructor {
public DeepExceptionInConstructor(){
// "Deep" means only one level deep...
naughtyMethod();
}
private void naughtyMethod() {
throw new RuntimeException("Inside a method called by the constructor");
}
public String invoke(){
throw new RuntimeException("This should not be called");
}
}
public static class NestedExceptionInConstructor {
public NestedExceptionInConstructor(){
try {
naughtyMethod();
} catch (Exception e){
throw new RuntimeException("Oh no!", e);
}
}
private int naughtyMethod() {
int a = 1;
int b = (a*a>0?0:0);
return a/b; // Explicitly putting "1/0" is a compile-time error
}
public String invoke(){
throw new RuntimeException("This should not be called");
}
}
public static class ExceptionInConfiguration {
@FnConfiguration
public void config(){
throw new RuntimeException("Config fail");
}
public void invoke(){}
}
public static class DeepExceptionInConfiguration {
@FnConfiguration
public void config(){
throwDeep(20);
}
private void throwDeep(int n){
if (n==0) {
throw new RuntimeException("Deep config fail");
}
throwDeep(n-1);
}
public void invoke(){}
}
public static class CauseStackTraceInResult {
private void throwTwo(){
try{
throwOne();
}catch(Exception e){
throw new RuntimeException("Throw two",e);
}
}
private void throwOne(){
throw new RuntimeException("Throw one");
}
public void invoke(){
throwTwo();
}
}
public static class NestedExceptionInConfiguration {
@FnConfiguration
public void config(){
throwDeep(3);
}
private void throwDeep(int n){
if (n==0) {
throw new RuntimeException("Deep config fail");
}
try {
throwDeep(n - 1);
} catch (Exception e){
throw new RuntimeException("nested at " + n, e);
}
}
public void invoke(){}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/DataBindingTest.java | runtime/src/test/java/com/fnproject/fn/runtime/DataBindingTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime;
import com.fnproject.fn.runtime.testfns.*;
import org.junit.Rule;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* End-to-end tests for custom data binding
*/
public class DataBindingTest {
@Rule
public final FnTestHarness fn = new FnTestHarness();
@Test
public void shouldUseInputCoercionSpecifiedOnFunctionRuntimeContext() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(CustomDataBindingFnWithConfig.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("dlroW olleH");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void shouldUseInputCoercionSpecifiedWithAnnotation() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(CustomDataBindingFnWithAnnotation.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("dlroW olleH");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void shouldUseOutputCoercionSpecifiedOnFunctionRuntimeContext() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(CustomOutputDataBindingFnWithConfig.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("dlroW olleH");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void shouldUseOutputCoercionSpecifiedWithAnnotation() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(CustomOutputDataBindingFnWithAnnotation.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("dlroW olleH");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void shouldUseFirstInputCoercionSpecifiedOnFunctionRuntimeContext() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(CustomDataBindingFnWithMultipleCoercions.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("HELLO WORLD");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void shouldUseFirstOutputCoercionSpecifiedOnFunctionRuntimeContext() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(CustomOutputDataBindingFnWithMultipleCoercions.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("HELLO WORLD");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void shouldUseBuiltInInputCoercionSpecifiedOnFunctionRuntimeContext() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(CustomDataBindingFnWithNoUserCoercions.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("Hello World");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void shouldUseBuiltInOutputCoercionSpecifiedOnFunctionRuntimeContext() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(CustomOutputDataBindingFnWithNoUserCoercions.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("Hello World");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void shouldUseSecondInputCoercionSpecifiedOnFunctionRuntimeContext() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(CustomDataBindingFnWithDudCoercion.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("dlroW olleH");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void shouldUseSecondOutputCoercionSpecifiedOnFunctionRuntimeContext() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(CustomOutputDataBindingFnWithDudCoercion.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("dlroW olleH");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void shouldApplyCoercionsForInputAndOutputSpecifiedOnFunctionRuntimeContext() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(CustomDataBindingFnInputOutput.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("DLROW OLLEH");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void shouldPrioritiseAnnotationOverConfig() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(CustomDataBindingFnWithAnnotationAndConfig.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("HELLO WORLD");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/ErrorMessagesTest.java | runtime/src/test/java/com/fnproject/fn/runtime/ErrorMessagesTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime;
import com.fnproject.fn.api.OutputEvent;
import com.fnproject.fn.runtime.testfns.ErrorMessages;
import not.in.com.fnproject.fn.StacktraceFilteringTestFunctions;
import org.assertj.core.api.Assertions;
import org.junit.Rule;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ErrorMessagesTest {
@Rule
public final FnTestHarness fn = new FnTestHarness();
private void assertIsErrorWithoutStacktrace(String errorMessage) {
assertThat(fn.exitStatus()).isEqualTo(2);
assertThat(fn.getOutputs()).hasSize(1).allSatisfy(testOutput -> Assertions.assertThat(testOutput.getStatus()).isEqualTo(OutputEvent.Status.FunctionError));
assertThat(fn.getStdErrAsString()).contains(errorMessage);
assertThat(fn.getStdErrAsString().split(System.getProperty("line.separator")).length).isEqualTo(1);
}
private void assertIsEntryPointErrorWithStacktrace(String errorMessage) {
assertThat(fn.exitStatus()).isEqualTo(2);
assertThat(fn.getOutputs()).hasSize(1).allSatisfy(testOutput -> Assertions.assertThat(testOutput.getStatus()).isEqualTo(OutputEvent.Status.FunctionError));
assertThat(fn.getStdErrAsString()).contains(errorMessage);
assertThat(fn.getStdErrAsString().split(System.getProperty("line.separator")).length).isGreaterThan(1);
assertThat(fn.getStdErrAsString()).doesNotContain("at com.fnproject.fn.runtime");
}
private void assertIsFunctionErrorWithStacktrace(String errorMessage) {
assertThat(fn.exitStatus()).isEqualTo(1);
assertThat(fn.getStdErrAsString()).contains(errorMessage);
assertThat(fn.getStdErrAsString().split(System.getProperty("line.separator")).length).isGreaterThan(1);
assertThat(fn.getStdErrAsString()).doesNotContain("at com.fnproject.fn.runtime");
}
/* The test method names should be mentally prefixed with "we get a nice error message when..." */
@Test
public void userSpecifiesNonExistentClass(){
fn.givenEvent().enqueue();
fn.thenRun("NonExistentClass", "method");
assertIsErrorWithoutStacktrace("Class 'NonExistentClass' not found in function jar. It's likely that the 'cmd' entry in func.yaml is incorrect.");
}
@Test
public void userSpecifiesClassWithNoMethods(){
fn.givenEvent().enqueue();
fn.thenRun(ErrorMessages.NoMethodsClass.class, "thisClassHasNoMethods");
assertIsErrorWithoutStacktrace("Method 'thisClassHasNoMethods' was not found in class 'com.fnproject.fn.runtime.testfns.ErrorMessages.NoMethodsClass'. Available functions were: []");
}
@Test
public void userSpecifiesMethodWhichDoesNotExist(){
fn.givenEvent().enqueue();
fn.thenRun(ErrorMessages.OneMethodClass.class, "notTheMethod");
assertIsErrorWithoutStacktrace("Method 'notTheMethod' was not found in class 'com.fnproject.fn.runtime.testfns.ErrorMessages.OneMethodClass'. Available functions were: [theMethod]");
}
@Test
public void userFunctionInputCoercionError(){
fn.givenEvent().withBody("This is not a...").enqueue();
fn.thenRun(ErrorMessages.OtherMethodsClass.class, "takesAnInteger");
assertIsEntryPointErrorWithStacktrace("An exception was thrown during Input Coercion: Failed to coerce event to user function parameter type class java.lang.Integer");
}
@Test
public void objectConstructionThrowsARuntimeException(){
fn.givenEvent().enqueue();
fn.thenRun(StacktraceFilteringTestFunctions.ExceptionInConstructor.class, "invoke");
assertIsEntryPointErrorWithStacktrace("Whoops");
}
@Test
public void objectConstructionThrowsADeepException(){
fn.givenEvent().enqueue();
fn.thenRun(StacktraceFilteringTestFunctions.DeepExceptionInConstructor.class, "invoke");
assertIsEntryPointErrorWithStacktrace("Inside a method called by the constructor");
assertThat(fn.getStdErrAsString()).contains("at not.in.com.fnproject.fn.StacktraceFilteringTestFunctions$DeepExceptionInConstructor.naughtyMethod");
assertThat(fn.getStdErrAsString()).contains("at not.in.com.fnproject.fn.StacktraceFilteringTestFunctions$DeepExceptionInConstructor.<init>");
}
@Test
public void objectConstructionThrowsANestedException(){
fn.givenEvent().enqueue();
fn.thenRun(StacktraceFilteringTestFunctions.NestedExceptionInConstructor.class, "invoke");
assertIsEntryPointErrorWithStacktrace("Caused by: java.lang.RuntimeException: Oh no!");
assertThat(fn.getStdErrAsString()).contains("at not.in.com.fnproject.fn.StacktraceFilteringTestFunctions$NestedExceptionInConstructor.naughtyMethod");
assertThat(fn.getStdErrAsString()).contains("Caused by: java.lang.ArithmeticException: / by zero");
assertThat(fn.getStdErrAsString()).contains("at not.in.com.fnproject.fn.StacktraceFilteringTestFunctions$NestedExceptionInConstructor.naughtyMethod");
assertThat(fn.getStdErrAsString()).contains("at not.in.com.fnproject.fn.StacktraceFilteringTestFunctions$NestedExceptionInConstructor.<init>");
}
@Test
public void fnConfigurationThrowsARuntimeException(){
fn.givenEvent().enqueue();
fn.thenRun(StacktraceFilteringTestFunctions.ExceptionInConfiguration.class, "invoke");
assertIsEntryPointErrorWithStacktrace("Caused by: java.lang.RuntimeException: Config fail");
}
@Test
public void fnConfigurationThrowsADeepException(){
fn.givenEvent().enqueue();
fn.thenRun(StacktraceFilteringTestFunctions.DeepExceptionInConfiguration.class, "invoke");
assertIsEntryPointErrorWithStacktrace("Caused by: java.lang.RuntimeException: Deep config fail");
assertThat(fn.getStdErrAsString()).contains("at not.in.com.fnproject.fn.StacktraceFilteringTestFunctions$DeepExceptionInConfiguration.throwDeep");
assertThat(fn.getStdErrAsString()).contains("at not.in.com.fnproject.fn.StacktraceFilteringTestFunctions$DeepExceptionInConfiguration.config");
}
@Test
public void fnConfigurationThrowsANestedException(){
fn.givenEvent().enqueue();
fn.thenRun(StacktraceFilteringTestFunctions.NestedExceptionInConfiguration.class, "invoke");
assertIsEntryPointErrorWithStacktrace("Error invoking configuration method: config");
assertThat(fn.getStdErrAsString()).contains("Caused by: java.lang.RuntimeException: nested at 3");
assertThat(fn.getStdErrAsString()).contains("Caused by: java.lang.RuntimeException: nested at 2");
assertThat(fn.getStdErrAsString()).contains("Caused by: java.lang.RuntimeException: nested at 1");
assertThat(fn.getStdErrAsString()).contains("Caused by: java.lang.RuntimeException: Deep config fail");
assertThat(fn.getStdErrAsString()).contains("at not.in.com.fnproject.fn.StacktraceFilteringTestFunctions$NestedExceptionInConfiguration.config");
}
@Test
public void functionThrowsNestedException(){
fn.givenEvent().enqueue();
fn.thenRun(StacktraceFilteringTestFunctions.CauseStackTraceInResult.class, "invoke");
assertIsFunctionErrorWithStacktrace("An error occurred in function: Throw two");
assertThat(fn.getStdErrAsString()).contains("Caused by: java.lang.RuntimeException: Throw two");
assertThat(fn.getStdErrAsString()).contains("Caused by: java.lang.RuntimeException: Throw one");
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/JacksonCoercionTest.java | runtime/src/test/java/com/fnproject/fn/runtime/JacksonCoercionTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.api.MethodWrapper;
import com.fnproject.fn.runtime.coercion.jackson.JacksonCoercion;
import com.fnproject.fn.runtime.testfns.Animal;
import org.junit.Assert;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class JacksonCoercionTest {
public String testMethod(List<Animal> ss) {
// This method isn't actually called, it only exists to have its parameter types examined by the JacksonCoercion
return ss.get(0).getName();
}
@Test
public void listOfCustomObjects() throws NoSuchMethodException {
JacksonCoercion jc = new JacksonCoercion();
MethodWrapper method = new DefaultMethodWrapper(JacksonCoercionTest.class, "testMethod");
FunctionRuntimeContext frc = new FunctionRuntimeContext(method, new HashMap<>());
FunctionInvocationContext invocationContext = new FunctionInvocationContext(frc,new ReadOnceInputEvent(new ByteArrayInputStream(new byte[0]),Headers.emptyHeaders(),"callID",Instant.now()));
Map<String, String> headers = new HashMap<>();
headers.put("content-type", "application/json");
ByteArrayInputStream body = new ByteArrayInputStream("[{\"name\":\"Spot\",\"age\":6},{\"name\":\"Jason\",\"age\":16}]".getBytes());
InputEvent inputEvent = new ReadOnceInputEvent( body, Headers.fromMap(headers),"call",Instant.now());
Optional<Object> object = jc.tryCoerceParam(invocationContext, 0, inputEvent, method);
List<Animal> animals = (List<Animal>) (object.get());
Animal first = animals.get(0);
Assert.assertEquals("Spot", first.getName());
}
@Test
public void failureToParseIsUserFriendlyError() throws NoSuchMethodException {
JacksonCoercion jc = new JacksonCoercion();
MethodWrapper method = new DefaultMethodWrapper(JacksonCoercionTest.class, "testMethod");
FunctionRuntimeContext frc = new FunctionRuntimeContext(method, new HashMap<>());
FunctionInvocationContext invocationContext = new FunctionInvocationContext(frc,new ReadOnceInputEvent(new ByteArrayInputStream(new byte[0]),Headers.emptyHeaders(),"callID",Instant.now()));
Map<String, String> headers = new HashMap<>();
headers.put("content-type", "application/json");
ByteArrayInputStream body = new ByteArrayInputStream("INVALID JSON".getBytes());
InputEvent inputEvent = new ReadOnceInputEvent( body, Headers.fromMap(headers), "call",Instant.now());
boolean causedExpectedError;
try {
Optional<Object> object = jc.tryCoerceParam(invocationContext, 0, inputEvent, method);
causedExpectedError = false;
} catch (RuntimeException e) {
causedExpectedError = true;
Assert.assertEquals("Failed to coerce event to user function parameter type java.util.List<com.fnproject.fn.runtime.testfns.Animal>", e.getMessage());
Assert.assertTrue(e.getCause().getMessage().startsWith("Unrecognized token 'INVALID':"));
}
Assert.assertTrue(causedExpectedError);
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/HeaderBuilder.java | runtime/src/test/java/com/fnproject/fn/runtime/HeaderBuilder.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime;
import com.fnproject.fn.api.Headers;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
class HeaderBuilder {
static Map.Entry<String, List<String>> headerEntry(String key, String... values) {
return new AbstractMap.SimpleEntry<>(Headers.canonicalKey(key), Arrays.asList(values));
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/FunctionConstructionTest.java | runtime/src/test/java/com/fnproject/fn/runtime/FunctionConstructionTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime;
import com.fnproject.fn.api.OutputEvent;
import com.fnproject.fn.runtime.testfns.TestFnConstructors;
import org.assertj.core.api.Assertions;
import org.junit.Rule;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* End-to-end tests for function configuration methods
*/
public class FunctionConstructionTest {
@Rule
public final FnTestHarness fn = new FnTestHarness();
@Test
public void shouldConstructWithDefaultConstructor() {
fn.givenEvent().enqueue();
fn.thenRun(TestFnConstructors.DefaultEmptyConstructor.class, "invoke");
assertThat(fn.exitStatus()).isEqualTo(0);
assertThat(fn.getOnlyOutputAsString()).isEqualTo("OK");
}
@Test
public void shouldConstructWithExplicitConstructor() {
fn.givenEvent().enqueue();
fn.thenRun(TestFnConstructors.ExplicitEmptyConstructor.class, "invoke");
assertThat(fn.exitStatus()).isEqualTo(0);
assertThat(fn.getOnlyOutputAsString()).isEqualTo("OK");
}
@Test
public void shouldInjectConfigIntoConstructor() {
fn.givenEvent().enqueue();
fn.thenRun(TestFnConstructors.ConfigurationOnConstructor.class, "invoke");
assertThat(fn.exitStatus()).isEqualTo(0);
assertThat(fn.getOnlyOutputAsString()).isEqualTo("OK");
}
@Test
public void shouldFailWithInaccessibleConstructor() {
fn.givenEvent().enqueue();
fn.thenRun(TestFnConstructors.BadConstructorNotAccessible.class, "invoke");
assertThat(fn.exitStatus()).isEqualTo(2);
assertThat(fn.getOutputs()).hasSize(1).allSatisfy(testOutput -> Assertions.assertThat(testOutput.getStatus()).isEqualTo(OutputEvent.Status.FunctionError));
assertThat(fn.getStdErrAsString()).contains("cannot be instantiated as it has no public constructors");
}
@Test
public void shouldFailFunctionWithTooManyConstructorArgs() {
fn.givenEvent().enqueue();
fn.thenRun(TestFnConstructors.BadConstructorTooManyArgs.class, "invoke");
assertThat(fn.exitStatus()).isEqualTo(2);
assertThat(fn.getOutputs()).hasSize(1).allSatisfy(testOutput -> Assertions.assertThat(testOutput.getStatus()).isEqualTo(OutputEvent.Status.FunctionError));
assertThat(fn.getStdErrAsString()).contains("cannot be instantiated as its constructor takes more than one argument");
}
@Test
public void shouldFailFunctionWithAmbiguousConstructors() {
fn.givenEvent().enqueue();
fn.thenRun(TestFnConstructors.BadConstructorAmbiguousConstructors.class, "invoke");
assertThat(fn.exitStatus()).isEqualTo(2);
assertThat(fn.getOutputs()).hasSize(1).allSatisfy(testOutput -> Assertions.assertThat(testOutput.getStatus()).isEqualTo(OutputEvent.Status.FunctionError));
assertThat(fn.getStdErrAsString()).contains("cannot be instantiated as it has multiple public constructors");
}
@Test
public void shouldFailFunctionWithErrorInConstructor() {
fn.givenEvent().enqueue();
fn.thenRun(TestFnConstructors.BadConstructorThrowsException.class, "invoke");
assertThat(fn.exitStatus()).isEqualTo(2);
assertThat(fn.getOutputs()).hasSize(1).allSatisfy(testOutput -> Assertions.assertThat(testOutput.getStatus()).isEqualTo(OutputEvent.Status.FunctionError));
assertThat(fn.getStdErrAsString()).contains("An error occurred in the function constructor while instantiating class");
}
@Test
public void shouldFailFunctionWithBadSingleConstructConstructorArg() {
fn.givenEvent().enqueue();
fn.thenRun(TestFnConstructors.BadConstructorUnrecognisedArg.class, "invoke");
assertThat(fn.exitStatus()).isEqualTo(2);
assertThat(fn.getOutputs()).hasSize(1).allSatisfy(testOutput -> Assertions.assertThat(testOutput.getStatus()).isEqualTo(OutputEvent.Status.FunctionError));
assertThat(fn.getStdErrAsString()).contains("cannot be instantiated as its constructor takes an unrecognized argument of type int");
}
@Test
public void shouldFailNonStaticInnerClassWithANiceMessage(){
fn.givenEvent().enqueue();
fn.thenRun(TestFnConstructors.NonStaticInnerClass.class, "invoke");
assertThat(fn.exitStatus()).isEqualTo(2);
assertThat(fn.getOutputs()).hasSize(1).allSatisfy(testOutput -> Assertions.assertThat(testOutput.getStatus()).isEqualTo(OutputEvent.Status.FunctionError));
assertThat(fn.getStdErrAsString()).contains("cannot be instantiated as it is a non-static inner class");
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/QueryParametersParserTest.java | runtime/src/test/java/com/fnproject/fn/runtime/QueryParametersParserTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime;
import com.fnproject.fn.api.QueryParameters;
import com.fnproject.fn.runtime.httpgateway.QueryParametersParser;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
public class QueryParametersParserTest {
@Test
public void noUrlParametersProducesEmptyMap() {
QueryParameters params = QueryParametersParser.getParams("www.example.com");
assertThat(params.getAll().size()).isEqualTo(0);
}
@Test
public void gettingNonExistentParameterProducesOptionalEmpty() {
QueryParameters params = QueryParametersParser.getParams("www.example.com");
assertThat(params.getValues("var")).isEmpty();
}
@Test
public void singleEmptyParameter() {
QueryParameters params = QueryParametersParser.getParams("www.example.com/route?var");
assertThat(params.getAll().size()).isEqualTo(1);
assertThat(params.get("var")).hasValue("");
}
@Test
public void multipleEmptyParameters() {
QueryParameters params = QueryParametersParser.getParams("www.example.com/myapp/route?var&var2");
assertThat(params.getAll().size()).isEqualTo(2);
assertThat(params.get("var")).hasValue("");
assertThat(params.get("var2")).hasValue("");
}
@Test
public void singleParameterWithValue() {
QueryParameters params = QueryParametersParser.getParams("www.example.com/myapp/route?var=val");
assertThat(params.getAll().size()).isEqualTo(1);
assertThat(params.get("var")).hasValue("val");
}
@Test
public void multipleParametersWithValues() {
QueryParameters params = QueryParametersParser.getParams("www.example.com/myapp/route?var1=val1&var2=val2");
assertThat(params.getAll().size()).isEqualTo(2);
assertThat(params.get("var1")).hasValue("val1");
assertThat(params.get("var2")).hasValue("val2");
}
@Test
public void singleParameterWithMultipleValues() {
QueryParameters params = QueryParametersParser.getParams("www.example.com/myapp/route?var=val1&var=val2");
assertThat(params.getAll().size()).isEqualTo(1);
assertThat(params.getValues("var")).containsOnly("val1", "val2");
}
@Test
public void multipleParametersMultipleValues() {
QueryParameters params = QueryParametersParser.getParams("www.example.com/myapp/route?var=val1&var=val2&var2=val&var2=val2");
assertThat(params.getAll().size()).isEqualTo(2);
assertThat(params.getValues("var")).containsOnly("val1", "val2");
assertThat(params.getValues("var2")).containsOnly("val", "val2");
}
@Test
public void urlEncodedParameterWithUrlEncodedValue() {
QueryParameters params = QueryParametersParser.getParams("/myapp/route?var+blah=val+foo%26%3D%3d");
assertThat(params.getAll().size()).isEqualTo(1);
assertThat(params.getValues("var blah")).containsOnly("val foo&==");
}
@Test
public void colonSeparatedParameters() {
QueryParameters params = QueryParametersParser.getParams("/myapp/route?var=val;var2=val;var=val2");
assertThat(params.getAll().size()).isEqualTo(2);
assertThat(params.getValues("var")).containsOnly("val", "val2");
assertThat(params.get("var2")).hasValue("val");
}
@Test
public void enumeratingQueryParameters() {
QueryParameters params = QueryParametersParser.getParams("/myapp/route?var1=val1&var2=val2&var3=val3");
Map<String, List<String>> expectedParams = new HashMap<>();
expectedParams.put("var1", Collections.singletonList("val1"));
expectedParams.put("var2", Collections.singletonList("val2"));
expectedParams.put("var3", Collections.singletonList("val3"));
for (Map.Entry<String, List<String>> entry : params.getAll().entrySet()) {
assertThat(entry.getValue()).isEqualTo(expectedParams.get(entry.getKey()));
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/EndToEndInvokeTest.java | runtime/src/test/java/com/fnproject/fn/runtime/EndToEndInvokeTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime;
import java.util.Arrays;
import java.util.List;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.api.OutputEvent;
import com.fnproject.fn.runtime.testfns.BadTestFnDuplicateMethods;
import com.fnproject.fn.runtime.testfns.TestFn;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* End-to-end tests on Stdin/Stdout contract
*/
public class EndToEndInvokeTest {
@Rule
public final FnTestHarness fn = new FnTestHarness();
@BeforeClass
public static void setup() {
TestFn.reset();
}
@Test
public void shouldResolveTestCallWithEnvVarParams() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
TestFn.setOutput("Hello World Out");
fn.thenRun(TestFn.class, "fnStringInOut");
assertThat(TestFn.getInput()).isEqualTo("Hello World");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("Hello World Out");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void shouldResolveTestCallFromHotCall() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
TestFn.setOutput("Hello World Out");
fn.thenRun(TestFn.class, "fnStringInOut");
assertThat(TestFn.getInput()).isEqualTo("Hello World");
}
@Test
public void shouldSerializeGenericCollections() throws Exception {
fn.givenEvent().withBody("four").enqueue();
fn.thenRun(TestFn.class, "fnGenericCollections");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("[\"one\",\"two\",\"three\",\"four\"]");
}
@Test
public void shouldSerializeAnimalCollections() throws Exception {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "fnGenericAnimal");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("[{\"name\":\"Spot\",\"age\":6},{\"name\":\"Jason\",\"age\":16}]");
}
@Test
public void shouldDeserializeGenericCollections() throws Exception {
fn.givenEvent()
.withHeader("Content-type", "application/json")
.withBody("[\"one\",\"two\",\"three\",\"four\"]")
.enqueue();
fn.thenRun(TestFn.class, "fnGenericCollectionsInput");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("ONE");
}
@Test
public void shouldDeserializeCustomObjects() throws Exception {
fn.givenEvent()
.withHeader("Content-type", "application/json")
.withBody("[{\"name\":\"Spot\",\"age\":6},{\"name\":\"Jason\",\"age\":16}]")
.enqueue();
fn.thenRun(TestFn.class, "fnCustomObjectsCollectionsInput");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("Spot");
}
@Test
public void shouldDeserializeComplexCustomObjects() throws Exception {
fn.givenEvent()
.withHeader("Content-type", "application/json")
.withBody("{\"number1\":[{\"name\":\"Spot\",\"age\":6}]," +
"\"number2\":[{\"name\":\"Spot\",\"age\":16}]}")
.enqueue();
fn.thenRun(TestFn.class, "fnCustomObjectsNestedCollectionsInput");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("Spot");
}
@Test
public void shouldHandledStreamedHotInputEvent() throws Exception {
fn.givenEvent()
.withBody("message1")
.enqueue();
fn.givenEvent()
.withBody("message2")
.enqueue();
fn.thenRun(TestFn.class, "fnEcho");
List<FnTestHarness.TestOutput> responses = fn.getOutputs();
assertThat(responses).size().isEqualTo(2);
FnTestHarness.TestOutput r1 = responses.get(0);
assertThat(new String(r1.getBody())).isEqualTo("message1");
FnTestHarness.TestOutput r2 = responses.get(1);
assertThat(new String(r2.getBody())).isEqualTo("message2");
}
@Test
public void shouldPrintErrorOnUnknownMethod() throws Exception {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "unknownMethod");
assertThat(fn.exitStatus()).isEqualTo(2);
assertThat(fn.getOutputs()).hasSize(1).allSatisfy(testOutput -> assertThat(testOutput.getStatus()).isEqualTo(OutputEvent.Status.FunctionError));
assertThat(fn.getStdErrAsString()).startsWith("Method 'unknownMethod' was not found in class 'com.fnproject.fn.runtime.testfns.TestFn'");
}
@Test
public void shouldPrintErrorOnUnknownClass() throws Exception {
fn.givenEvent().enqueue();
fn.thenRun("com.fnproject.unknown.Class", "unknownMethod");
assertThat(fn.exitStatus()).isEqualTo(2);
assertThat(fn.getOutputs()).hasSize(1).allSatisfy(testOutput -> assertThat(testOutput.getStatus()).isEqualTo(OutputEvent.Status.FunctionError));
assertThat(fn.getStdErrAsString()).startsWith("Class 'com.fnproject.unknown.Class' not found in function jar");
}
@Test
public void shouldDirectStdOutToStdErrForFunctions() throws Exception {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "fnWritesToStdout");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("");
assertThat(fn.getStdErrAsString()).isEqualTo("STDOUT");
}
@Test
public void shouldTerminateDefaultContainerOnExceptionWithError() throws Exception {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "fnThrowsException");
assertThat(fn.getStdErrAsString()).startsWith("An error occurred in function:");
assertThat(fn.getOnlyOutputAsString()).isEmpty();
assertThat(fn.exitStatus()).isEqualTo(1);
}
@Test
public void shouldReadJsonObject() throws Exception {
fn.givenEvent()
.withHeader("Content-type", "application/json")
.withBody("{\"foo\":\"bar\"}")
.enqueue();
fn.thenRun(TestFn.class, "fnReadsJsonObj");
assertThat(((TestFn.JsonData) TestFn.getInput()).foo).isEqualTo("bar");
}
@Test
public void shouldWriteJsonData() throws Exception {
fn.givenEvent().enqueue();
TestFn.JsonData data = new TestFn.JsonData();
data.foo = "bar";
TestFn.setOutput(data);
fn.thenRun(TestFn.class, "fnWritesJsonObj");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("{\"foo\":\"bar\"}");
}
@Test
public void shouldReadBytesOnDefaultCodec() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(TestFn.class, "fnReadsBytes");
assertThat(TestFn.getInput()).isEqualTo("Hello World".getBytes());
}
@Test
public void shouldPrintLogFrame() throws Exception {
fn.setConfig("FN_LOGFRAME_NAME", "containerID");
fn.setConfig("FN_LOGFRAME_HDR", "fnID");
fn.givenEvent().withHeader("fnID", "fnIDVal").withBody( "Hello world!").enqueue();
fn.thenRun(TestFn.class, "fnEcho");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("Hello world!");
// stdout gets redirected to stderr - hence printing out twice
assertThat(fn.getStdErrAsString()).isEqualTo("\ncontainerID=fnIDVal\n\n\ncontainerID=fnIDVal\n\n");
}
@Test
public void shouldWriteBytesOnDefaultCodec() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
TestFn.setOutput("OK".getBytes());
fn.thenRun(TestFn.class, "fnWritesBytes");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("OK");
}
@Test
public void shouldRejectDuplicateMethodsInFunctionClass() throws Exception {
fn.givenEvent().enqueue();
fn.thenRun(BadTestFnDuplicateMethods.class, "fn");
assertThat(fn.exitStatus()).isEqualTo(2);
assertThat(fn.getOutputs()).hasSize(1).allSatisfy(testOutput -> assertThat(testOutput.getStatus()).isEqualTo(OutputEvent.Status.FunctionError));
assertThat(fn.getStdErrAsString()).startsWith("Multiple methods match");
}
@Test
public void shouldReadRawJson() throws Exception {
fn.givenEvent()
.withHeader("Content-type", "application/json")
.withBody("[\"foo\",\"bar\"]")
.enqueue();
fn.thenRun(TestFn.class, "fnReadsRawJson");
assertThat(TestFn.getInput()).isEqualTo(Arrays.asList("foo", "bar"));
}
@Test
public void shouldReadInputHeaders() throws Exception{
fn.givenEvent()
.withHeader("myHeader", "Foo")
.withHeader("a-n-header", "b0o","b10")
.enqueue();
fn.thenRun(TestFn.class, "readRawEvent");
InputEvent iev = (InputEvent)TestFn.getInput();
assertThat(iev).isNotNull();
assertThat(iev.getHeaders().getAllValues("Myheader")).contains("Foo");
assertThat(iev.getHeaders().getAllValues("A-N-Header")).contains("b0o","b10");
}
@Test
public void shouldExposeOutputHeaders() throws Exception{
fn.givenEvent()
.enqueue();
fn.thenRun(TestFn.class, "setsOutputHeaders");
FnTestHarness.TestOutput to = fn.getOutputs().get(0);
System.err.println("got response" + to );
assertThat(to.getContentType()).contains("foo-ct");
assertThat(to.getHeaders().get("Header-1")).contains("v1");
assertThat(to.getHeaders().getAllValues("A")).contains("b1","b2");
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/FnTestHarness.java | runtime/src/test/java/com/fnproject/fn/runtime/FnTestHarness.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.api.OutputEvent;
import org.apache.commons.io.output.TeeOutputStream;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import java.io.*;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
/**
* Function internal testing harness - this provides access the call-side of the functions contract excluding the codec which is mocked
*/
public class FnTestHarness implements TestRule {
private final List<InputEvent> pendingInput = Collections.synchronizedList(new ArrayList<>());
private final List<TestOutput> output = Collections.synchronizedList(new ArrayList<>());
private final ByteArrayOutputStream stdErr = new ByteArrayOutputStream();
private int exitStatus = -1;
private final Map<String, String> config = new HashMap<>();
/**
* Add a config variable to the function
* <p>
* Config names will be translated to upper case with hyphens and spaces translated to _
* <p>
* clashing config keys will be overwritten
*
* @param key the configuration key
* @param value the configuration value
*/
public void setConfig(String key, String value) {
config.put(key.toUpperCase().replaceAll("[- ]", "_"), value);
}
/**
* Gets a function config variable by key, or null if absent
*
* @param key the configuration key
*/
public String getConfig(String key) {
return config.get(key.toUpperCase().replaceAll("[- ]", "_"));
}
public String getOnlyOutputAsString() {
if (output.size() != 1) {
throw new IllegalStateException("expecting exactly one result, got " + output.size());
}
return new String(output.get(0).getBody());
}
/**
* Builds a mocked input event into the function runtime
*/
public final class EventBuilder {
InputStream body = new ByteArrayInputStream(new byte[0]);
String contentType = null;
String callID = "callID";
Instant deadline = Instant.now().plus(1, ChronoUnit.HOURS);
Headers headers = Headers.emptyHeaders();
/**
* Add a header to the input
* Duplicate headers will be overwritten
*
* @param key header key
* @param v1 header value
* @param vs other header values
*/
public EventBuilder withHeader(String key, String v1, String... vs) {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(v1, "value");
Objects.requireNonNull(vs, "vs");
Arrays.stream(vs).forEach(v -> Objects.requireNonNull(v, "null value in varags list "));
headers = headers.addHeader(key, v1);
for (String v : vs) {
headers = headers.addHeader(key, v);
}
return this;
}
/**
* Add a series of headers to the input
* This may override duplicate headers
*
* @param headers Map of headers to add
*/
public EventBuilder withHeaders(Map<String, String> headers) {
headers.forEach(this::withHeader);
return this;
}
/**
* Set the body of the request by providing an InputStream
*
* @param body the bytes of the body
*/
public EventBuilder withBody(InputStream body) {
Objects.requireNonNull(body, "body");
this.body = body;
return this;
}
/**
* Set the body of the request as a byte array
*
* @param body the bytes of the body
*/
public EventBuilder withBody(byte[] body) {
Objects.requireNonNull(body, "body");
return withBody(new ByteArrayInputStream(body));
}
/**
* Set the body of the request as a string
*
* @param body the bytes of the body
*/
public EventBuilder withBody(String body) {
byte stringAsBytes[] = Objects.requireNonNull(body, "body").getBytes();
return withBody(stringAsBytes);
}
/**
* Prepare an event for the configured codec - this sets appropriate environment variable in the Env mock and StdIn mocks.
* <p>
*
* @throws IllegalStateException If the the codec only supports one event and an event has already been enqueued.
*/
public void enqueue() {
InputEvent event = new ReadOnceInputEvent(body, headers, callID, deadline);
pendingInput.add(event);
}
Map<String, String> commonEnv() {
Map<String, String> env = new HashMap<>(config);
env.put("FN_APP_ID", "appID");
env.put("FN_FN_ID", "fnID");
return env;
}
}
static class TestOutput implements OutputEvent {
private final OutputEvent from;
byte[] body;
TestOutput(OutputEvent from) throws IOException {
this.from = from;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
from.writeToOutput(bos);
body = bos.toByteArray();
}
@Override
public Status getStatus() {
return from.getStatus();
}
@Override
public Optional<String> getContentType() {
return from.getContentType();
}
@Override
public Headers getHeaders() {
return from.getHeaders();
}
@Override
public void writeToOutput(OutputStream out) throws IOException {
out.write(body);
}
public byte[] getBody() {
return body;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("TestOutput{");
sb.append("body=");
if (body == null) sb.append("null");
else {
sb.append('[');
for (int i = 0; i < body.length; ++i)
sb.append(i == 0 ? "" : ", ").append(body[i]);
sb.append(']');
}
sb.append(", status=").append(getStatus());
sb.append(", contentType=").append(getContentType());
sb.append(", headers=").append(getHeaders());
sb.append('}');
return sb.toString();
}
}
/**
* Runs the function runtime with the specified class and method
*
* @param cls class to thenRun
* @param method the method name
*/
public void thenRun(Class<?> cls, String method) {
thenRun(cls.getName(), method);
}
static class TestCodec implements EventCodec {
private final List<InputEvent> input;
private final List<TestOutput> output;
TestCodec(List<InputEvent> input, List<TestOutput> output) {
this.input = input;
this.output = output;
}
@Override
public void runCodec(Handler h) {
for (InputEvent in : input) {
try {
output.add(new TestOutput(h.handle(in)));
} catch (IOException e) {
throw new RuntimeException("Unexpected exception in test", e);
}
}
}
}
/**
* Runs the function runtime with the specified class and method
*
* @param cls class to thenRun
* @param method the method name
*/
public void thenRun(String cls, String method) {
InputStream oldSystemIn = System.in;
PrintStream oldSystemOut = System.out;
PrintStream oldSystemErr = System.err;
try {
PrintStream functionErr = new PrintStream(new TeeOutputStream(stdErr, oldSystemErr));
System.setOut(functionErr);
System.setErr(functionErr);
Map<String, String> fnConfig = new HashMap<>(config);
fnConfig.put("FN_APP_ID", "appID");
fnConfig.put("FN_FORMAT", "http-stream");
fnConfig.put("FN_FN_ID", "fnID");
exitStatus = new EntryPoint().run(
fnConfig,
new TestCodec(pendingInput, output),
functionErr,
cls + "::" + method);
stdErr.flush();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
System.out.flush();
System.err.flush();
System.setIn(oldSystemIn);
System.setOut(oldSystemOut);
System.setErr(oldSystemErr);
}
}
/**
* Get the exit status of the runtime;
*
* @return the system exit status
*/
public int exitStatus() {
return exitStatus;
}
/**
* mock an HTTP event (Input and stdOut encoded as HTTP frames)
*
* @return a new event builder.
*/
public EventBuilder givenEvent() {
return new EventBuilder();
}
/**
* Get the stderr stream returned by the function as a byte array
*
* @return the stderr stream as bytes from the runtime
*/
public byte[] getStdErr() {
return stdErr.toByteArray();
}
/**
* Gets the stderr stream returned by the function as a String
*
* @return the stderr stream as a string from the function
*/
public String getStdErrAsString() {
return new String(stdErr.toByteArray());
}
/**
* Get the output produced by the runtime as a byte array
*
* @return the bytes returned by the function runtime;
*/
public List<TestOutput> getOutputs() {
return output;
}
@Override
public Statement apply(Statement base, Description description) {
return base;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/MethodWrapperTests.java | runtime/src/test/java/com/fnproject/fn/runtime/MethodWrapperTests.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime;
import com.fnproject.fn.api.MethodWrapper;
import org.assertj.core.api.AbstractIntegerAssert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(Parameterized.class)
public class MethodWrapperTests {
private final Class srcClass;
private final String methodName;
private final int parameterIndex;
private final Class[] methodParameterTypes;
private final Class<?> expectedType;
public MethodWrapperTests(Class srcClass, String methodName, Class[] methodParameterTypes, int parameterIndex, Class<?> expectedType) throws Exception {
this.srcClass = srcClass;
this.methodName = methodName;
this.parameterIndex = parameterIndex;
this.methodParameterTypes = methodParameterTypes;
this.expectedType = expectedType;
}
@Test
public void testMethodParameterHasExpectedType() throws NoSuchMethodException {
MethodWrapper method = new DefaultMethodWrapper(srcClass, srcClass.getMethod(this.methodName, this.methodParameterTypes));
if (parameterIndex >= 0) {
assertThat(method.getParamType(parameterIndex).getParameterClass()).isEqualTo(expectedType);
} else {
AbstractIntegerAssert<?> withFailMessage = assertThat(parameterIndex)
.isEqualTo(-1)
.withFailMessage("You can only use non negative parameter indices or -1 to represent return value in this test suite");
assertThat(method.getReturnType().getParameterClass()).isEqualTo(expectedType);
}
}
@Parameterized.Parameters
public static Collection<Object[]> data() throws Exception {
return Arrays.asList(new Object[][] {
{ ConcreteTypeExamples.class, "voidReturnType", new Class[]{ }, -1, Void.class },
{ ConcreteTypeExamples.class, "singleParameter", new Class[]{ String.class }, 0, String.class },
{ ConcreteTypeExamples.class, "singlePrimitiveParameter", new Class[]{ boolean.class}, 0, Boolean.class },
{ ConcreteTypeExamples.class, "singlePrimitiveParameter", new Class[]{ byte.class }, 0, Byte.class },
{ ConcreteTypeExamples.class, "singlePrimitiveParameter", new Class[]{ char.class }, 0, Character.class },
{ ConcreteTypeExamples.class, "singlePrimitiveParameter", new Class[]{ short.class }, 0, Short.class },
{ ConcreteTypeExamples.class, "singlePrimitiveParameter", new Class[]{ int.class }, 0, Integer.class },
{ ConcreteTypeExamples.class, "singlePrimitiveParameter", new Class[]{ long.class }, 0, Long.class },
{ ConcreteTypeExamples.class, "singlePrimitiveParameter", new Class[]{ float.class }, 0, Float.class },
{ ConcreteTypeExamples.class, "singlePrimitiveParameter", new Class[]{ double.class }, 0, Double.class },
{ ConcreteTypeExamples.class, "multipleParameters", new Class[] { String.class, double.class }, 0, String.class },
{ ConcreteTypeExamples.class, "multipleParameters", new Class[]{ String.class, double.class }, 1, Double.class },
{ ConcreteTypeExamples.class, "singleGenericParameter", new Class[]{ List.class }, 0, List.class },
{ ConcreteTypeExamples.class, "noArgs", new Class[]{}, -1, String.class },
{ ConcreteTypeExamples.class, "noArgsWithPrimitiveReturnType", new Class[]{}, -1, Integer.class },
{ ConcreteSubclassOfGenericParent.class, "singleGenericArg", new Class[] { Object.class }, 0, String.class },
{ ConcreteSubclassOfGenericParent.class, "returnsGeneric", new Class[] { }, -1, String.class },
{ ConcreteSubclassOfNestedGenericAncestors.class, "methodWithGenericParamAndReturnType", new Class[]{ Object.class }, 0, Integer.class },
{ ConcreteSubclassOfNestedGenericAncestors.class, "methodWithGenericParamAndReturnType", new Class[]{ Object.class }, -1, String.class }
});
}
static class ConcreteTypeExamples {
public void voidReturnType() { }
public void singleParameter(String s) { }
public void singlePrimitiveParameter(boolean i) { }
public void singlePrimitiveParameter(byte i) { }
public void singlePrimitiveParameter(char i) { }
public void singlePrimitiveParameter(short i) { }
public void singlePrimitiveParameter(int i) { }
public void singlePrimitiveParameter(long i) { }
public void singlePrimitiveParameter(float i) { }
public void singlePrimitiveParameter(double i) { }
public void multipleParameters(String s, double i) { }
public String noArgs() { return ""; }
public int noArgsWithPrimitiveReturnType() { return 1; }
public void singleGenericParameter(List<String> s) { }
}
static class ParentClassWithGenericType<T> {
public void singleGenericArg(T t) { };
public T returnsGeneric() { return null; };
}
static class ConcreteSubclassOfGenericParent extends ParentClassWithGenericType<String> { }
static class GenericParent<T, U> {
public T methodWithGenericParamAndReturnType(U u) { return null; }
}
static class SpecialisedGenericParent<T> extends GenericParent<T, Integer> { }
static class ConcreteSubclassOfNestedGenericAncestors extends SpecialisedGenericParent<String> { }
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/ConfigurationMethodsTest.java | runtime/src/test/java/com/fnproject/fn/runtime/ConfigurationMethodsTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime;
import com.fnproject.fn.api.OutputEvent;
import com.fnproject.fn.runtime.testfns.TestFnWithConfigurationMethods;
import org.junit.Rule;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* End-to-end tests for function configuration methods
*/
public class ConfigurationMethodsTest {
@Rule
public final FnTestHarness fn = new FnTestHarness();
@Test
public void staticTargetWithNoConfigurationIsOK() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(TestFnWithConfigurationMethods.StaticTargetNoConfiguration.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("StaticTargetNoConfiguration\nHello World");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void instanceTargetWithNoConfigurationIsOK() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(TestFnWithConfigurationMethods.InstanceTargetNoConfiguration.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("InstanceTargetNoConfiguration\nHello World");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void staticTargetWithStaticConfigurationIsOK() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(TestFnWithConfigurationMethods.StaticTargetStaticConfiguration.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("StaticTargetStaticConfiguration\nHello World");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void instanceTargetWithStaticConfigurationIsOK() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(TestFnWithConfigurationMethods.InstanceTargetStaticConfiguration.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("InstanceTargetStaticConfiguration\nHello World");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void staticTargetWithInstanceConfigurationIsAnError() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
String expectedMessage = "Configuration method " +
"'config'" +
" cannot be an instance method if the function method is a static method";
fn.thenRun(TestFnWithConfigurationMethods.StaticTargetInstanceConfiguration.class, "echo");
assertThat(fn.getOutputs()).hasSize(1).allSatisfy(testOutput -> assertThat(testOutput.getStatus()).isEqualTo(OutputEvent.Status.FunctionError));
assertThat(fn.getStdErrAsString()).startsWith(expectedMessage);
assertThat(fn.exitStatus()).isEqualTo(2);
}
@Test
public void instanceTargetWithInstanceConfigurationIsOK() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(TestFnWithConfigurationMethods.InstanceTargetInstanceConfiguration.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("InstanceTargetInstanceConfiguration\nHello World");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void staticTargetWithStaticConfigurationWithoutRuntimeContextParameterIsOK() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(TestFnWithConfigurationMethods.StaticTargetStaticConfigurationNoRuntime.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("StaticTargetStaticConfigurationNoRuntime\nHello World");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void instanceTargetWithStaticConfigurationWithoutRuntimeContextParameterIsOK() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(TestFnWithConfigurationMethods.InstanceTargetStaticConfigurationNoRuntime.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("InstanceTargetStaticConfigurationNoRuntime\nHello World");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void instanceTargetWithInstanceConfigurationWithoutRuntimeContextParameterIsOK() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(TestFnWithConfigurationMethods.InstanceTargetInstanceConfigurationNoRuntime.class, "echo");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("InstanceTargetInstanceConfigurationNoRuntime\nHello World");
assertThat(fn.getStdErrAsString()).isEmpty();
assertThat(fn.exitStatus()).isZero();
}
@Test
public void shouldReturnDefaultParameterIfNotProvided() {
fn.givenEvent().enqueue();
fn.thenRun(TestFnWithConfigurationMethods.WithGetConfigurationByKey.class, "getParam");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("default");
}
@Test
public void shouldReturnSetConfigParameterWhenProvided() {
String value = "value";
fn.setConfig("PARAM", value);
fn.givenEvent().enqueue();
fn.thenRun(TestFnWithConfigurationMethods.WithGetConfigurationByKey.class, "getParam");
assertThat(fn.getOnlyOutputAsString()).isEqualTo(value);
}
@Test
public void nonVoidConfigurationMethodIsAnError() throws Exception {
fn.givenEvent().withBody("Hello World").enqueue();
fn.thenRun(TestFnWithConfigurationMethods.ConfigurationMethodIsNonVoid.class, "echo");
String expectedMessage = "Configuration method " +
"'config'" +
" does not have a void return type";
assertThat(fn.getOutputs()).hasSize(1).allSatisfy(testOutput -> {
assertThat(testOutput.getStatus()).isEqualTo(OutputEvent.Status.FunctionError);
});
assertThat(fn.getStdErrAsString()).startsWith(expectedMessage);
assertThat(fn.exitStatus()).isEqualTo(2);
}
@Test
public void shouldBeAbleToAccessConfigInConfigurationMethodWhenDefault() {
fn.setConfig("FOO", "BAR");
fn.givenEvent()
.withBody("FOO")
.enqueue();
fn.thenRun(TestFnWithConfigurationMethods.ConfigurationMethodWithAccessToConfig.class, "configByKey");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("ConfigurationMethodWithAccessToConfig\nBAR");
}
@Test
public void shouldBeAbleToAccessConfigInConfigurationMethodWhenHttp() {
fn.setConfig("FOO", "BAR");
fn.givenEvent()
.withBody("FOO")
.enqueue();
fn.thenRun(TestFnWithConfigurationMethods.ConfigurationMethodWithAccessToConfig.class, "configByKey");
assertThat(fn.getOnlyOutputAsString()).contains("ConfigurationMethodWithAccessToConfig\nBAR");
}
@Test
public void shouldOnlyExtractConfigFromEnvironmentNotHeaderWhenHttp() {
fn.givenEvent()
.withHeader("FOO", "BAR")
.withBody("FOO")
.enqueue();
fn.thenRun(TestFnWithConfigurationMethods.ConfigurationMethodWithAccessToConfig.class, "configByKey");
assertThat(fn.getOnlyOutputAsString()).doesNotContain("BAR");
}
@Test
public void shouldNotBeAbleToAccessHeadersInConfigurationWhenDefault() {
fn.givenEvent()
.withHeader("FOO", "BAR")
.withBody("HEADER_FOO")
.enqueue();
fn.thenRun(TestFnWithConfigurationMethods.ConfigurationMethodWithAccessToConfig.class, "configByKey");
assertThat(fn.getOnlyOutputAsString()).doesNotContain("ConfigurationMethodWithAccessToConfig\nBAR");
}
@Test
public void shouldNotBeAbleToAccessHeadersInConfigurationWhenHttp() {
fn.givenEvent()
.withHeader("FOO", "BAR")
.withBody("HEADER_FOO")
.enqueue();
fn.thenRun(TestFnWithConfigurationMethods.ConfigurationMethodWithAccessToConfig.class, "configByKey");
assertThat(fn.getOnlyOutputAsString()).doesNotContain("ConfigurationMethodWithAccessToConfig\nBAR");
}
@Test
public void shouldCallInheritedConfigMethodsInRightOrder() {
fn.givenEvent().enqueue();
TestFnWithConfigurationMethods.SubConfigClass.order = "";
fn.thenRun(TestFnWithConfigurationMethods.SubConfigClass.class, "invoke");
assertThat(fn.getOnlyOutputAsString()).isEqualTo("OK");
assertThat(TestFnWithConfigurationMethods.SubConfigClass.order)
.matches("\\.baseStatic1\\.subStatic1\\.baseFn\\d\\.baseFn\\d\\.subFn\\d\\.subFn\\d\\.subFn\\d\\.subFn\\d");
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/HTTPStreamCodecTest.java | runtime/src/test/java/com/fnproject/fn/runtime/HTTPStreamCodecTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.api.OutputEvent;
import org.apache.commons.io.IOUtils;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.client.util.BytesContentProvider;
import org.eclipse.jetty.client.util.StringContentProvider;
import org.eclipse.jetty.unixsocket.client.HttpClientTransportOverUnixSockets;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import static org.assertj.core.api.Assertions.assertThat;
/**
* This uses the Jetty client largely as witness of "good HTTP behaviour"
* Created on 24/08/2018.
* <p>
* (c) 2018 Oracle Corporation
*/
public class HTTPStreamCodecTest {
private static final String VERSION = "FDK_TEST_VERSION";
private static final String RUNTIME_VERSION = "FDK_TEST_RUNTIME";
@Rule
public final Timeout to = Timeout.builder().withTimeout(60, TimeUnit.SECONDS).withLookingForStuckThread(true).build();
private static final Map<String, String> defaultEnv;
private final List<Runnable> cleanups = new ArrayList<>();
private static File generateSocketFile() {
File f;
try {
f = File.createTempFile("socket", ".sock");
f.delete();
f.deleteOnExit();
} catch (IOException e) {
throw new RuntimeException("Error creating socket file", e);
}
return f;
}
static {
if (System.getenv("RUNTIME_BUILD_DIR") == null) {
System.setProperty("com.fnproject.java.native.libdir", new File("src/main/c/").getAbsolutePath());
}else{
System.setProperty("com.fnproject.java.native.libdir", new File(System.getenv("RUNTIME_BUILD_DIR")).getAbsolutePath());
}
System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
System.setProperty("org.eclipse.jetty.LEVEL", "WARN");
Map<String, String> env = new HashMap<>();
env.put("FN_APP_NAME", "myapp");
env.put("FN_PATH", "mypath");
defaultEnv = Collections.unmodifiableMap(env);
}
private HttpClient createClient(File unixSocket) throws Exception {
HttpClient client = new HttpClient(new HttpClientTransportOverUnixSockets(unixSocket.getAbsolutePath()), null);
client.start();
cleanups.add(() -> {
try {
client.stop();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
return client;
}
private Request defaultRequest(HttpClient httpClient) {
return httpClient.newRequest("http://localhost/call")
.method("POST")
.header("Fn-Call-Id", "callID")
.header("Fn-Deadline", "2002-10-02T10:00:00.992Z")
.header("Custom-header", "v1")
.header("Custom-header", "v2")
.header("Content-Type", "text/plain")
.content(new StringContentProvider("hello "));
}
@After
public void cleanup() {
cleanups.forEach(Runnable::run);
}
File startCodec(Map<String, String> env, EventCodec.Handler h) {
Map<String, String> newEnv = new HashMap<>(env);
File socket = generateSocketFile();
newEnv.put("FN_LISTENER", "unix:" + socket.getAbsolutePath());
HTTPStreamCodec codec = new HTTPStreamCodec(newEnv, VERSION, RUNTIME_VERSION);
Thread t = new Thread(() -> codec.runCodec(h));
t.start();
cleanups.add(() -> {
try {
codec.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
return socket;
}
@Test
public void shouldAcceptDataOnHttp() throws Exception {
CompletableFuture<InputEvent> lastEvent = new CompletableFuture<>();
File socketFile = startCodec(defaultEnv, (in) -> {
lastEvent.complete(in);
return OutputEvent.fromBytes("hello".getBytes(), OutputEvent.Status.Success, "text/plain", Headers.emptyHeaders().addHeader("x-test", "bar"));
});
HttpClient client = createClient(socketFile);
ContentResponse resp = client.newRequest("http://localhost/call")
.method("POST")
.header("Fn-Call-Id", "callID")
.header("Fn-Deadline", "2002-10-02T10:00:00.992Z")
.header("Custom-header", "v1")
.header("Custom-header", "v2")
.header("Content-Type", "text/plain")
.content(new StringContentProvider("hello ")).send();
assertThat(resp.getStatus()).isEqualTo(200);
assertThat(resp.getContent()).isEqualTo("hello".getBytes());
assertThat(resp.getHeaders().get("x-test")).isEqualTo("bar");
assertThat(resp.getHeaders().get("fn-fdk-version")).isEqualTo(VERSION);
assertThat(resp.getHeaders().get("fn-fdk-runtime")).isEqualTo(RUNTIME_VERSION);
InputEvent evt = lastEvent.get(1, TimeUnit.MILLISECONDS);
assertThat(evt.getCallID()).isEqualTo("callID");
assertThat(evt.getDeadline().toEpochMilli()).isEqualTo(1033552800992L);
assertThat(evt.getHeaders()).isEqualTo(Headers.emptyHeaders().addHeader("Fn-Call-Id", "callID").addHeader("Fn-Deadline", "2002-10-02T10:00:00.992Z").addHeader("Custom-header", "v1", "v2").addHeader("Content-Type", "text/plain").addHeader("Content-Length", "6"));
}
@Test
public void shouldRejectFnMissingHeaders() throws Exception {
Map<String, String> headers = new HashMap<>();
headers.put("Fn-Call-Id", "callID");
headers.put("Fn-Deadline", "2002-10-02T10:00:00.992Z");
File socket = startCodec(defaultEnv, (in) -> OutputEvent.emptyResult(OutputEvent.Status.Success));
HttpClient client = createClient(socket);
Request positive = client.newRequest("http://localhost/call")
.method("POST");
headers.forEach(positive::header);
assertThat(positive.send().getStatus()).withFailMessage("Expecting req with mandatory headers to pass").isEqualTo(200);
for (String h : headers.keySet()) {
Request r = client.newRequest("http://localhost/call")
.method("POST");
headers.forEach((k, v) -> {
if (!k.equals(h)) {
r.header(k, v);
}
});
ContentResponse resp = r.send();
assertThat(resp.getStatus()).withFailMessage("Expected failure error code for missing header " + h).isEqualTo(500);
}
}
@Test
public void shouldHandleMultipleRequests() throws Exception {
AtomicReference<byte[]> lastInput = new AtomicReference<>();
AtomicInteger count = new AtomicInteger(0);
File socket = startCodec(defaultEnv, (in) -> {
byte[] body = in.consumeBody((is) -> {
try {
return IOUtils.toByteArray(is);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
lastInput.set(body);
return OutputEvent.fromBytes(body, OutputEvent.Status.Success, "application/octet-stream", Headers.emptyHeaders());
});
HttpClient httpClient = createClient(socket);
for (int i = 0; i < 200; i++) {
byte[] body = randomBytes(i * 1997);
ContentResponse resp = httpClient.newRequest("http://localhost/call")
.method("POST")
.header("Fn-Call-Id", "callID")
.header("Fn-Deadline", "2002-10-02T10:00:00.992Z")
.header("Custom-header", "v1")
.header("Custom-header", "v2")
.header("Content-Type", "text/plain")
.content(new BytesContentProvider(body)).send();
assertThat(resp.getStatus()).isEqualTo(200);
assertThat(resp.getContent()).isEqualTo(body);
assertThat(lastInput).isNotNull();
assertThat(lastInput.get()).isEqualTo(body);
}
}
@Test
public void shouldHandleLargeBodies() throws Exception {
// Round trips 10 meg of data through the codec and validates it got the right stuff back
byte[] randomString = randomBytes(1024 * 1024 * 10);
byte[] inDigest = MessageDigest.getInstance("SHA-256").digest(randomString);
File socket = startCodec(defaultEnv, (in) -> {
byte[] content = in.consumeBody((is) -> {
try {
return IOUtils.toByteArray(is);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
return OutputEvent.fromBytes(content, OutputEvent.Status.Success, "application/octet-binary", Headers.emptyHeaders());
});
HttpClient client = createClient(socket);
CompletableFuture<Result> cdl = new CompletableFuture<>();
MessageDigest readDigest = MessageDigest.getInstance("SHA-256");
defaultRequest(client)
.content(new BytesContentProvider(randomString))
.onResponseContent((response, byteBuffer) -> readDigest.update(byteBuffer))
.send(cdl::complete);
Result r = cdl.get();
assertThat(r.getResponse().getStatus()).isEqualTo(200);
assertThat(readDigest.digest()).isEqualTo(inDigest);
}
private byte[] randomBytes(int sz) {
Random sr = new Random();
byte[] part = new byte[997];
sr.nextBytes(part);
// Make random ascii for convenience in debugging
for (int i = 0; i < part.length; i++) {
part[i] = (byte) ((part[i] % 26) + 65);
}
byte[] randomString = new byte[sz];
int left = sz;
for (int i = 0; i < randomString.length; i += part.length) {
int copy = Math.min(left, part.length);
System.arraycopy(part, 0, randomString, i, copy);
left -= part.length;
}
return randomString;
}
@Test
public void shouldConvertStatusResponses() throws Exception {
for (OutputEvent.Status s : OutputEvent.Status.values()) {
CompletableFuture<InputEvent> lastEvent = new CompletableFuture<>();
File socket = startCodec(defaultEnv, (in) -> {
lastEvent.complete(in);
return OutputEvent.fromBytes("hello".getBytes(), s, "text/plain", Headers.emptyHeaders());
});
HttpClient client = createClient(socket);
ContentResponse resp = defaultRequest(client).send();
assertThat(resp.getStatus()).isEqualTo(s.getCode());
}
}
@Test
public void shouldStripHopToHopHeadersFromFunctionInput() throws Exception {
for (String[] header : new String[][] {
{"Transfer-encoding", "chunked"},
{"Connection", "close"},
}) {
CompletableFuture<InputEvent> lastEvent = new CompletableFuture<>();
File socket = startCodec(defaultEnv, (in) -> {
lastEvent.complete(in);
return OutputEvent.fromBytes("hello".getBytes(), OutputEvent.Status.Success, "text/plain", Headers.emptyHeaders().addHeader(header[0], header[1]));
});
HttpClient client = createClient(socket);
ContentResponse resp = defaultRequest(client).send();
assertThat(resp.getHeaders().get(header[0])).isNull();
}
}
@Test
public void socketShouldHaveCorrectPermissions() throws Exception {
File listener = startCodec(defaultEnv, (in) -> OutputEvent.fromBytes("hello".getBytes(), OutputEvent.Status.Success, "text/plain", Headers.emptyHeaders()));
assertThat(Files.getPosixFilePermissions(listener.toPath())).isEqualTo(PosixFilePermissions.fromString("rw-rw-rw-"));
cleanup();
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/tracing/OCITracingContextTest.java | runtime/src/test/java/com/fnproject/fn/runtime/tracing/OCITracingContextTest.java | package com.fnproject.fn.runtime.tracing;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.InvocationContext;
import com.fnproject.fn.api.MethodWrapper;
import com.fnproject.fn.runtime.FunctionRuntimeContext;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
public class OCITracingContextTest {
@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Mock
InvocationContext ctxMock;
@Mock
FunctionRuntimeContext runtimeContextMock;
@Mock
MethodWrapper methodWrapperMock;
private Map<String, String> getConfig(Boolean enabled) {
Map<String, String> env = new HashMap<>();
env.put("FN_APP_NAME", "myapp");
env.put("FN_FN_NAME", "myFunction");
env.put("OCI_TRACE_COLLECTOR_URL", "tracingPath");
env.put("OCI_TRACING_ENABLED", enabled ? "1" : "0");
return Collections.unmodifiableMap(env);
}
@Test
public void configureRuntimeContext() {
Map<String, String> config = getConfig(false);
runtimeContextMock = new FunctionRuntimeContext(methodWrapperMock, config);
OCITracingContext tracingContext = new OCITracingContext(ctxMock, runtimeContextMock);
assertThat(tracingContext.isTracingEnabled()).isEqualTo(false);
assertThat(tracingContext.getAppName()).isEqualToIgnoringCase("myapp");
assertThat(tracingContext.getFunctionName()).isEqualToIgnoringCase("myFunction");
assertThat(tracingContext.getTraceCollectorURL()).isEqualToIgnoringCase("tracingPath");
}
@Test
public void getServiceName() {
Map<String, String> config = getConfig(false);
runtimeContextMock = new FunctionRuntimeContext(methodWrapperMock, config);
OCITracingContext tracingContext = new OCITracingContext(ctxMock, runtimeContextMock);
assertThat(tracingContext.getServiceName()).isEqualToIgnoringCase("myapp::myFunction");
}
@Test
public void shouldAbleToConfigureWithNoHeaderData() {
Map<String, String> config = getConfig(true);
runtimeContextMock = new FunctionRuntimeContext(methodWrapperMock, config);
Mockito.when(ctxMock.getRequestHeaders()).thenReturn(Headers.emptyHeaders());
OCITracingContext tracingContext = new OCITracingContext(ctxMock, runtimeContextMock);
assertThat(tracingContext.isSampled()).isEqualTo(true);
assertThat(tracingContext.getTraceId()).isEqualTo("1");
assertThat(tracingContext.getSpanId()).isEqualTo("1");
assertThat(tracingContext.getParentSpanId()).isEqualTo("1");
}
@Test
public void shouldAbleToConfigureWithHeaderDataNotSampled() {
Map<String, String> config = getConfig(true);
runtimeContextMock = new FunctionRuntimeContext(methodWrapperMock, config);
Map<String, String> headerData = new HashMap();
headerData.put("x-b3-sampled","0");
Headers headers = Headers.fromMap(headerData);
Mockito.when(ctxMock.getRequestHeaders()).thenReturn(headers);
OCITracingContext tracingContext = new OCITracingContext(ctxMock, runtimeContextMock);
assertThat(tracingContext.isSampled()).isEqualTo(false);
}
@Test
public void shouldAbleToConfigureWithHeaderData() {
Map<String, String> config = getConfig(true);
runtimeContextMock = new FunctionRuntimeContext(methodWrapperMock, config);
Map<String, String> headerData = new HashMap();
headerData.put("x-b3-sampled","1");
headerData.put("x-b3-flags","<implementation-specific data>");
headerData.put("x-b3-traceid","213454321432");
headerData.put("x-b3-spanid","244342r343");
headerData.put("x-b3-parentspanid","32142r231242");
Headers headers = Headers.fromMap(headerData);
Mockito.when(ctxMock.getRequestHeaders()).thenReturn(headers);
OCITracingContext tracingContext = new OCITracingContext(ctxMock, runtimeContextMock);
assertThat(tracingContext.isSampled()).isEqualTo(true);
assertThat(tracingContext.getTraceId()).isEqualTo("213454321432");
assertThat(tracingContext.getSpanId()).isEqualTo("244342r343");
assertThat(tracingContext.getParentSpanId()).isEqualTo("32142r231242");
assertThat(tracingContext.getFlags()).isEqualTo("<implementation-specific data>");
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomDataBindingFnWithNoUserCoercions.java | runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomDataBindingFnWithNoUserCoercions.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.testfns;
import com.fnproject.fn.api.FnConfiguration;
import com.fnproject.fn.api.RuntimeContext;
public class CustomDataBindingFnWithNoUserCoercions {
@FnConfiguration
public static void inputConfig(RuntimeContext ctx){
}
public String echo(String s){
return s;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomDataBindingFnWithAnnotation.java | runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomDataBindingFnWithAnnotation.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.testfns;
import com.fnproject.fn.api.InputBinding;
import com.fnproject.fn.runtime.testfns.coercions.StringReversalCoercion;
public class CustomDataBindingFnWithAnnotation {
public String echo(@InputBinding(coercion=StringReversalCoercion.class) String s){
return s;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/testfns/Animal.java | runtime/src/test/java/com/fnproject/fn/runtime/testfns/Animal.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.testfns;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Animal {
private String name;
private int age;
@JsonCreator
public Animal(@JsonProperty("name") String name,
@JsonProperty("age") int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomDataBindingFnWithDudCoercion.java | runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomDataBindingFnWithDudCoercion.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.testfns;
import com.fnproject.fn.api.FnConfiguration;
import com.fnproject.fn.api.RuntimeContext;
import com.fnproject.fn.runtime.testfns.coercions.DudCoercion;
import com.fnproject.fn.runtime.testfns.coercions.StringReversalCoercion;
public class CustomDataBindingFnWithDudCoercion {
@FnConfiguration
public static void inputConfig(RuntimeContext ctx){
ctx.addInputCoercion(new DudCoercion());
ctx.addInputCoercion(new StringReversalCoercion());
}
public String echo(String s){
return s;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomOutputDataBindingFnWithNoUserCoercions.java | runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomOutputDataBindingFnWithNoUserCoercions.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.testfns;
import com.fnproject.fn.api.FnConfiguration;
import com.fnproject.fn.api.RuntimeContext;
public class CustomOutputDataBindingFnWithNoUserCoercions {
@FnConfiguration
public static void outputConfig(RuntimeContext ctx){
}
public String echo(String s){ return s; }
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomOutputDataBindingFnWithAnnotation.java | runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomOutputDataBindingFnWithAnnotation.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.testfns;
import com.fnproject.fn.api.OutputBinding;
import com.fnproject.fn.runtime.testfns.coercions.StringReversalCoercion;
public class CustomOutputDataBindingFnWithAnnotation {
@OutputBinding(coercion=StringReversalCoercion.class)
public String echo(String s){ return s; }
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomOutputDataBindingFnWithMultipleCoercions.java | runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomOutputDataBindingFnWithMultipleCoercions.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.testfns;
import com.fnproject.fn.api.FnConfiguration;
import com.fnproject.fn.api.RuntimeContext;
import com.fnproject.fn.runtime.testfns.coercions.StringReversalCoercion;
import com.fnproject.fn.runtime.testfns.coercions.StringUpperCaseCoercion;
public class CustomOutputDataBindingFnWithMultipleCoercions {
@FnConfiguration
public static void outputConfig(RuntimeContext ctx){
ctx.addOutputCoercion(new StringUpperCaseCoercion());
ctx.addOutputCoercion(new StringReversalCoercion());
}
public String echo(String s){ return s; }
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/testfns/ErrorMessages.java | runtime/src/test/java/com/fnproject/fn/runtime/testfns/ErrorMessages.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.testfns;
public class ErrorMessages {
public class NoMethodsClass {
}
public class OneMethodClass {
public String theMethod(String x){
return x;
}
}
public static class OtherMethodsClass {
public String takesAnInteger(Integer x){
return "It was " + x;
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/testfns/TestFn.java | runtime/src/test/java/com/fnproject/fn/runtime/testfns/TestFn.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.testfns;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.api.InvocationContext;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Test function class for e2e tests
*/
public class TestFn {
private static final Object NOTHING = new Object();
private static Object input = NOTHING;
private static Object output = NOTHING;
private static int count = 0;
public static class JsonData {
public String foo;
}
public String fnStringInOutInstance(String in) {
input = in;
return (String) output;
}
public static String fnStringInOut(String in) {
input = in;
return (String) output;
}
public static String fnEcho(String in) {
return in;
}
public static void fnReadsBytes(byte[] in) {
input = in;
}
public static byte[] fnWritesBytes() {
return (byte[]) output;
}
public static void fnWritesToStdout() {
System.out.print("STDOUT");
}
public static void fnThrowsException() {
throw new RuntimeException("ERRTAG");
}
public static void fnReadsRawJson(List<String> strings) {
input = strings;
}
public JsonData fnWritesJsonObj() {
return (JsonData) output;
}
public static void fnReadsJsonObj(JsonData data) {
input = data;
}
public static List<String> fnGenericCollections(String four) {
return Arrays.asList("one", "two", "three", four);
}
public static String fnGenericCollectionsInput(List<String> strings) {
return strings.get(0).toUpperCase();
}
public static String fnCustomObjectsCollectionsInput(List<Animal> animals) {
return animals.get(0).getName();
}
public static String fnCustomObjectsNestedCollectionsInput(Map<String, List<Animal>> animals) {
return animals.values().stream().findFirst().get().get(0).getName(); // !
}
public static String readSecondInput(InputEvent evt) {
count++;
if (count > 1) {
return evt.consumeBody((is) -> {
try {
return IOUtils.toString(is, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
} else {
return "first;";
}
}
public static void readRawEvent(InputEvent evt) {
input = evt;
}
public static void setsOutputHeaders(InvocationContext ic) {
ic.addResponseHeader("Header-1","v1");
ic.setResponseContentType("foo-ct");
ic.addResponseHeader("a","b1");
ic.addResponseHeader("a","b2");
}
public static List<Animal> fnGenericAnimal() {
Animal dog = new Animal("Spot", 6);
Animal cat = new Animal("Jason", 16);
return Arrays.asList(dog, cat);
}
/**
* Reset the internal (static) state
* Should be called between runs;
*/
public static void reset() {
input = NOTHING;
output = NOTHING;
count = 0;
}
public static Object getInput() {
return input;
}
public static void setOutput(Object output) {
TestFn.output = output;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomOutputDataBindingFnWithConfig.java | runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomOutputDataBindingFnWithConfig.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.testfns;
import com.fnproject.fn.api.FnConfiguration;
import com.fnproject.fn.api.RuntimeContext;
import com.fnproject.fn.runtime.testfns.coercions.StringReversalCoercion;
public class CustomOutputDataBindingFnWithConfig {
@FnConfiguration
public static void outputConfig(RuntimeContext ctx){
ctx.addOutputCoercion(new StringReversalCoercion());
}
public String echo(String s){ return s; }
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/testfns/TestFnConstructors.java | runtime/src/test/java/com/fnproject/fn/runtime/testfns/TestFnConstructors.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.testfns;
import com.fnproject.fn.api.RuntimeContext;
import java.util.Objects;
public class TestFnConstructors {
public static class DefaultEmptyConstructor {
public String invoke() {
return "OK";
}
}
public static class ExplicitEmptyConstructor {
public ExplicitEmptyConstructor() {
}
public String invoke() {
return "OK";
}
}
public static class ConfigurationOnConstructor {
final RuntimeContext ctx;
public ConfigurationOnConstructor(RuntimeContext ctx) {
this.ctx = Objects.requireNonNull(ctx);
}
public String invoke() {
Objects.requireNonNull(ctx);
return "OK";
}
}
public static class BadConstructorThrowsException {
public BadConstructorThrowsException() {
throw new RuntimeException("error in constructor");
}
public String invoke() {
throw new RuntimeException("should not run");
}
}
public static class BadConstructorUnrecognisedArg {
public BadConstructorUnrecognisedArg(int x) {
}
public String invoke() {
throw new RuntimeException("should not run");
}
}
public static class BadConstructorAmbiguousConstructors {
public BadConstructorAmbiguousConstructors(RuntimeContext x) {
}
public BadConstructorAmbiguousConstructors() {
}
public String invoke() {
throw new RuntimeException("should not run");
}
}
public static class BadConstructorTooManyArgs {
public BadConstructorTooManyArgs(RuntimeContext ctx, int x) {
}
public String invoke() {
throw new RuntimeException("should not run");
}
}
private static abstract class BadClassAbstract {
public String invoke() {
throw new RuntimeException("should not run");
}
}
public static class BadConstructorNotAccessible {
private BadConstructorNotAccessible() {
}
public String invoke() {
throw new RuntimeException("should not run");
}
}
public class NonStaticInnerClass {
public String invoke(String x) {
throw new RuntimeException("should not run");
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomDataBindingFnWithAnnotationAndConfig.java | runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomDataBindingFnWithAnnotationAndConfig.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.testfns;
import com.fnproject.fn.api.FnConfiguration;
import com.fnproject.fn.api.InputBinding;
import com.fnproject.fn.api.RuntimeContext;
import com.fnproject.fn.runtime.testfns.coercions.StringReversalCoercion;
import com.fnproject.fn.runtime.testfns.coercions.StringUpperCaseCoercion;
public class CustomDataBindingFnWithAnnotationAndConfig {
@FnConfiguration
public static void inputConfig(RuntimeContext ctx){
ctx.addInputCoercion(new StringReversalCoercion());
}
public String echo(@InputBinding(coercion=StringUpperCaseCoercion.class) String s){
return s;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/testfns/TestFnWithConfigurationMethods.java | runtime/src/test/java/com/fnproject/fn/runtime/testfns/TestFnWithConfigurationMethods.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.testfns;
import com.fnproject.fn.api.FnConfiguration;
import com.fnproject.fn.api.RuntimeContext;
import java.util.Map;
/**
* Test function class for e2e tests
*/
public class TestFnWithConfigurationMethods {
public static class StaticTargetNoConfiguration {
public static String echo(String s) {
return "StaticTargetNoConfiguration\n" + s;
}
}
public static class InstanceTargetNoConfiguration {
public String echo(String s) {
return "InstanceTargetNoConfiguration\n" + s;
}
}
public static class StaticTargetStaticConfiguration {
static String toPrint = null;
@FnConfiguration
public static void config(RuntimeContext ctx) {
toPrint = "StaticTargetStaticConfiguration\n";
}
public static String echo(String s) {
return toPrint + s;
}
}
public static class WithGetConfigurationByKey {
private final String param;
public WithGetConfigurationByKey(RuntimeContext ctx) {
param = ctx.getConfigurationByKey("PARAM").orElse("default");
}
public String getParam() { return param; }
}
public static class InstanceTargetStaticConfiguration {
static String toPrint = null;
@FnConfiguration
public static void config(RuntimeContext ctx) {
toPrint = "InstanceTargetStaticConfiguration\n";
}
public static String echo(String s) {
return toPrint + s;
}
}
public static class StaticTargetInstanceConfiguration {
String toPrint = null;
@FnConfiguration
public void config(RuntimeContext ctx) {
toPrint = "StaticTargetInstanceConfiguration\n";
}
public static String echo(String s) throws Exception {
// This is a static method so it cannot access the instance
// variable that we set in configuration. This is actually a
// configuration error case and so this code will not run.
throw new Exception("This code should not be run!");
}
}
public static class InstanceTargetInstanceConfiguration {
String toPrint = null;
@FnConfiguration
public void config(RuntimeContext ctx) {
toPrint = "InstanceTargetInstanceConfiguration\n";
}
public String echo(String s) {
return toPrint + s;
}
}
public static class StaticTargetStaticConfigurationNoRuntime {
static String toPrint = null;
@FnConfiguration
public static void config() {
toPrint = "StaticTargetStaticConfigurationNoRuntime\n";
}
public static String echo(String s) {
return toPrint + s;
}
}
public static class InstanceTargetStaticConfigurationNoRuntime {
static String toPrint = null;
@FnConfiguration
public static void config() {
toPrint = "InstanceTargetStaticConfigurationNoRuntime\n";
}
public static String echo(String s) {
return toPrint + s;
}
}
public static class InstanceTargetInstanceConfigurationNoRuntime {
String toPrint = null;
@FnConfiguration
public void config() {
toPrint = "InstanceTargetInstanceConfigurationNoRuntime\n";
}
public String echo(String s) {
return toPrint + s;
}
}
public static class ConfigurationMethodIsNonVoid {
@FnConfiguration
public static String config() {
return "ConfigurationMethodIsNonVoid\n";
}
public static String echo(String s) throws Exception {
// This code will not run as the runtime should error out because
// the configuration method is non-void.
throw new Exception("This code should not be run!");
}
}
public static class ConfigurationMethodWithAccessToConfig {
private static Map<String, String> configFromContext;
@FnConfiguration
public static void configure(RuntimeContext ctx) {
configFromContext = ctx.getConfiguration();
}
public static String configByKey(String key) {
return "ConfigurationMethodWithAccessToConfig\n" + configFromContext.get(key);
}
}
public interface CallOrdered {
void called(String point);
}
public interface ConfigBaseInterface extends CallOrdered {
@FnConfiguration
default void ignoredInterfaceDefaultMethod() {
throw new RuntimeException("bad");
}
// Interface static methods are excluded
@FnConfiguration
static void ignoredStaticConfigMethod() {
throw new RuntimeException("bad");
}
void overriddenInterface();
}
public static abstract class ConfigBaseClass implements ConfigBaseInterface ,CallOrdered{
public static String order = "";
@Override
public void called(String point){
order += point;
}
@FnConfiguration
public static void baseStatic1() {
order += ".baseStatic1";
}
@FnConfiguration
public void baseFn1() {
called(".baseFn1");
}
@FnConfiguration
public void baseFn2() {
called( ".baseFn2");
}
@FnConfiguration
public abstract void orNotRun();
public abstract void orRun();
public void notConfig() {
throw new RuntimeException("bad");
}
}
public interface ConfigSubInterface extends CallOrdered{
void overriddenSubInterface();
@FnConfiguration
default void ignoredConfigDefaultMethod() {
throw new RuntimeException("bad");
}
@FnConfiguration
static void ignoredSubStaticConfigMethod() {
throw new RuntimeException("bad");
}
}
public static class SubConfigClass extends ConfigBaseClass implements ConfigSubInterface {
@FnConfiguration
public static void subStatic1() {
order += ".subStatic1";
}
@FnConfiguration
public void subFn1() {
called(".subFn1");
}
@FnConfiguration
public void overriddenSubInterface() {
called(".subFn2");
}
@FnConfiguration
public void overriddenInterface() {
called(".subFn3");
}
@Override
public void orNotRun() { // overrides without annotations are not called
throw new RuntimeException("bad");
}
@Override
@FnConfiguration
public void orRun() {
order += ".subFn4";
}
public String invoke() {
return "OK";
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomDataBindingFnWithConfig.java | runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomDataBindingFnWithConfig.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.testfns;
import com.fnproject.fn.api.FnConfiguration;
import com.fnproject.fn.api.RuntimeContext;
import com.fnproject.fn.runtime.testfns.coercions.StringReversalCoercion;
public class CustomDataBindingFnWithConfig {
@FnConfiguration
public static void inputConfig(RuntimeContext ctx){
ctx.addInputCoercion(new StringReversalCoercion());
}
public String echo(String s){
return s;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomOutputDataBindingFnWithDudCoercion.java | runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomOutputDataBindingFnWithDudCoercion.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.testfns;
import com.fnproject.fn.api.FnConfiguration;
import com.fnproject.fn.api.RuntimeContext;
import com.fnproject.fn.runtime.testfns.coercions.DudCoercion;
import com.fnproject.fn.runtime.testfns.coercions.StringReversalCoercion;
public class CustomOutputDataBindingFnWithDudCoercion {
@FnConfiguration
public static void outputConfig(RuntimeContext ctx){
ctx.addOutputCoercion(new DudCoercion());
ctx.addOutputCoercion(new StringReversalCoercion());
}
public String echo(String s){ return s; }
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/runtime/src/test/java/com/fnproject/fn/runtime/testfns/BadTestFnDuplicateMethods.java | runtime/src/test/java/com/fnproject/fn/runtime/testfns/BadTestFnDuplicateMethods.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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
*
* 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 com.fnproject.fn.runtime.testfns;
/**
* Test function class for e2e tests
*/
public class BadTestFnDuplicateMethods {
public void fn(String string){}
public void fn(int integer){}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.