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/runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomDataBindingFnInputOutput.java
runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomDataBindingFnInputOutput.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 CustomDataBindingFnInputOutput { @FnConfiguration public static void configure(RuntimeContext ctx){ ctx.addInputCoercion(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/CustomDataBindingFnWithMultipleCoercions.java
runtime/src/test/java/com/fnproject/fn/runtime/testfns/CustomDataBindingFnWithMultipleCoercions.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 CustomDataBindingFnWithMultipleCoercions { @FnConfiguration public static void inputConfig(RuntimeContext ctx){ ctx.addInputCoercion(new StringUpperCaseCoercion()); 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/coercions/StringUpperCaseCoercion.java
runtime/src/test/java/com/fnproject/fn/runtime/testfns/coercions/StringUpperCaseCoercion.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.coercions; import com.fnproject.fn.api.*; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Optional; public class StringUpperCaseCoercion implements InputCoercion<String>, OutputCoercion { @Override public Optional<String> tryCoerceParam(InvocationContext currentContext, int arg, InputEvent input, MethodWrapper methodWrapper) { return Optional.of( input.consumeBody(is -> { try { return IOUtils.toString(is, StandardCharsets.UTF_8).toUpperCase(); } catch (IOException e) { return null; // Tests will fail if we end up here } }) ); } @Override public Optional<OutputEvent> wrapFunctionResult(InvocationContext ctx, MethodWrapper method, Object value) { if (ctx.getRuntimeContext().getMethod().getTargetMethod().getReturnType().equals(String.class)) { try { String capitalizedOutput = ((String) value).toUpperCase(); return Optional.of(OutputEvent.fromBytes(capitalizedOutput.getBytes(), OutputEvent.Status.Success, "text/plain")); } catch (ClassCastException e) { return Optional.empty(); } } else { return Optional.empty(); } } }
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/coercions/StringReversalCoercion.java
runtime/src/test/java/com/fnproject/fn/runtime/testfns/coercions/StringReversalCoercion.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.coercions; import com.fnproject.fn.api.*; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Optional; public class StringReversalCoercion implements InputCoercion<String>, OutputCoercion { @Override public Optional<String> tryCoerceParam(InvocationContext currentContext, int arg, InputEvent input, MethodWrapper methodWrapper) { return Optional.of( input.consumeBody(is -> { try { return new StringBuffer(IOUtils.toString(is, StandardCharsets.UTF_8)).reverse().toString(); } catch (IOException e) { return null; // Tests will fail if we end up here } }) ); } @Override public Optional<OutputEvent> wrapFunctionResult(InvocationContext ctx, MethodWrapper method, Object value) { if (ctx.getRuntimeContext().getMethod().getTargetMethod().getReturnType().equals(String.class)) { try { String reversedOutput = new StringBuffer((String) value).reverse().toString(); return Optional.of(OutputEvent.fromBytes(reversedOutput.getBytes(), OutputEvent.Status.Success, "text/plain")); } catch (ClassCastException e) { return Optional.empty(); } } else { return Optional.empty(); } } }
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/coercions/DudCoercion.java
runtime/src/test/java/com/fnproject/fn/runtime/testfns/coercions/DudCoercion.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.coercions; import com.fnproject.fn.api.*; import java.util.Optional; public class DudCoercion implements InputCoercion<Object>, OutputCoercion { @Override public Optional<Object> tryCoerceParam(InvocationContext currentContext, int arg, InputEvent input, MethodWrapper methodWrapper) { return Optional.empty(); } @Override public Optional<OutputEvent> wrapFunctionResult(InvocationContext ctx, MethodWrapper method, Object value) { return Optional.empty(); } }
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/ntv/UnixSocketTest.java
runtime/src/test/java/com/fnproject/fn/runtime/ntv/UnixSocketTest.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.ntv; import org.assertj.core.api.Assertions; import org.junit.BeforeClass; import org.junit.Test; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; /** * Created on 12/09/2018. * <p> * (c) 2018 Oracle Corporation */ public class UnixSocketTest { @BeforeClass public static void setup() { 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()); } } File createSocketFile() throws IOException { File f = File.createTempFile("socket", "sock"); f.delete(); f.deleteOnExit(); return f; } public byte[] roundTripViaEcho(byte[] data) throws Exception { File f = createSocketFile(); try (UnixServerSocket ss = UnixServerSocket.listen(f.getPath(), 1)) { CompletableFuture<byte[]> result = new CompletableFuture<>(); CountDownLatch cdl = new CountDownLatch(1); Thread client = new Thread(() -> { try { cdl.await(); try (UnixSocket us = UnixSocket.connect(f.getPath())) { us.setReceiveBufferSize(65535); us.setSendBufferSize(65535); byte[] buf = new byte[data.length]; us.getOutputStream().write(data); DataInputStream dis = new DataInputStream(us.getInputStream()); dis.readFully(buf); result.complete(buf); } } catch (Exception e) { result.completeExceptionally(e); } }); client.start(); cdl.countDown(); UnixSocket in = ss.accept(1000); byte[] sbuf = new byte[data.length]; in.setReceiveBufferSize(65535); in.setSendBufferSize(65535); new DataInputStream(in.getInputStream()).readFully(sbuf); in.getOutputStream().write(sbuf); in.close(); return result.get(); } } @Test public void shouldHandleEmptyData() throws Exception { byte[] data = "hello".getBytes(); Assertions.assertThat(roundTripViaEcho(data)).isEqualTo(data); } @Test public void shouldHandleBigData() throws Exception { Random r = new Random(); byte[] dataPart = new byte[2048]; r.nextBytes(dataPart); byte[] data = new byte[1024 * 1024 * 10]; for (int i = 0 ; i < data.length ;i += dataPart.length){ System.arraycopy(dataPart,0,data,i,dataPart.length); } Assertions.assertThat(roundTripViaEcho(data)).isEqualTo(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/ntv/UnixSocketNativeTest.java
runtime/src/test/java/com/fnproject/fn/runtime/ntv/UnixSocketNativeTest.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.ntv; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; /** * Created on 12/09/2018. * <p> * (c) 2018 Oracle Corporation */ public class UnixSocketNativeTest { @BeforeClass public static void init() { 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()); } } File createSocketFile() throws IOException { File f = File.createTempFile("socket", "sock"); f.delete(); f.deleteOnExit(); return f; } @Test public void shouldHandleBind() throws Exception { try { // invalid socket UnixSocketNative.bind(-1, createSocketFile().getAbsolutePath()); fail("should have thrown an invalid argument"); } catch (UnixSocketException ignored) { } int socket = UnixSocketNative.socket(); try { // invalid file location UnixSocketNative.bind(socket, "/tmp/foodir/socket"); fail("should have thrown an invalid argument"); } catch (UnixSocketException ignored) { } finally { UnixSocketNative.close(socket); } socket = UnixSocketNative.socket(); File socketFile = createSocketFile(); try { // valid bind UnixSocketNative.bind(socket, socketFile.getAbsolutePath()); } finally { UnixSocketNative.close(socket); } } public <T> CompletableFuture<T> runServerLoop(Callable<T> loop) { CompletableFuture<T> result = new CompletableFuture<>(); Thread t = new Thread(() -> { try { result.complete(loop.call()); } catch (Exception e) { result.completeExceptionally(e); } }); t.start(); return result; } @Test public void shouldHandleConnectAccept() throws Exception { // invalid socket { try { UnixSocketNative.connect(-1, "/tmp/nonexistant_path.sock"); fail("should have failed"); } catch (UnixSocketException ignored) { } } // unknown path { int socket = UnixSocketNative.socket(); try { UnixSocketNative.connect(socket, "/tmp/nonexistant_path.sock"); fail("should have failed"); } catch (UnixSocketException ignored) { } finally { UnixSocketNative.close(socket); } } // accept rejects <zero timeout { File serverSocket = createSocketFile(); int ss = UnixSocketNative.socket(); long startTime = System.currentTimeMillis(); try { UnixSocketNative.bind(ss, serverSocket.getAbsolutePath()); UnixSocketNative.listen(ss, 1); int cs = UnixSocketNative.accept(ss, -1); } catch (IllegalArgumentException ignored) { } finally { UnixSocketNative.close(ss); } } // accept honors timeout { File serverSocket = createSocketFile(); int ss = UnixSocketNative.socket(); long startTime = System.currentTimeMillis(); try { UnixSocketNative.bind(ss, serverSocket.getAbsolutePath()); UnixSocketNative.listen(ss, 1); int cs = UnixSocketNative.accept(ss, 100); } catch (UnixSocketException ignored) { } finally { UnixSocketNative.close(ss); } assertThat(System.currentTimeMillis() - startTime).isGreaterThanOrEqualTo(100); } // valid connect { CountDownLatch ready = new CountDownLatch(1); File serverSocket = createSocketFile(); CompletableFuture<Boolean> sresult = runServerLoop(() -> { int ss = UnixSocketNative.socket(); try { UnixSocketNative.bind(ss, serverSocket.getAbsolutePath()); UnixSocketNative.listen(ss, 1); ready.countDown(); int cs = UnixSocketNative.accept(ss, 0); return cs > 0; } finally { UnixSocketNative.close(ss); } }); ready.await(); int cs; cs = UnixSocketNative.socket(); UnixSocketNative.connect(cs, serverSocket.getAbsolutePath()); assertThat(sresult.get()).isTrue(); } } @Test public void shouldHonorWrites() throws Exception { CountDownLatch ready = new CountDownLatch(1); File serverSocket = createSocketFile(); CompletableFuture<byte[]> result = runServerLoop(() -> { int ss = UnixSocketNative.socket(); try { UnixSocketNative.bind(ss, serverSocket.getAbsolutePath()); UnixSocketNative.listen(ss, 1); ready.countDown(); int cs = UnixSocketNative.accept(ss, 0); byte[] buf = new byte[100]; int read = UnixSocketNative.recv(cs, buf, 0, buf.length); byte[] newBuf = new byte[read]; System.arraycopy(buf, 0, newBuf, 0, read); return newBuf; } finally { UnixSocketNative.close(ss); } }); {// zero byte write is a noop ready.await(); int cs = UnixSocketNative.socket(); UnixSocketNative.connect(cs, serverSocket.getAbsolutePath()); // must NPE on buff try { UnixSocketNative.send(cs, null, 0, 10); fail("should have NPEd"); } catch (NullPointerException ignored) { } // invalid offset try { UnixSocketNative.send(cs, "hello".getBytes(), 100, 10); fail("should have IAEd"); } catch (IllegalArgumentException ignored) { } // invalid offset try { UnixSocketNative.send(cs, "hello".getBytes(), -1, 10); fail("should have IAEd"); } catch (IllegalArgumentException ignored) { } // invalid offset try { UnixSocketNative.send(cs, "hello".getBytes(), 0, 10); fail("should have IAEd"); } catch (IllegalArgumentException ignored) { } try { // Must nop on write UnixSocketNative.send(cs, new byte[0], 0, 0); fail("should have IAEd"); } catch (IllegalArgumentException ignored) { } // validate a real write to be sure UnixSocketNative.send(cs, "hello".getBytes(), 0, 5); byte[] got = result.get(); assertThat(got).isEqualTo("hello".getBytes()); } } @Test public void shouldHonorReads() throws Exception { CountDownLatch ready = new CountDownLatch(1); File serverSocket = createSocketFile(); CompletableFuture<Boolean> result = runServerLoop(() -> { int ss = UnixSocketNative.socket(); try { UnixSocketNative.bind(ss, serverSocket.getAbsolutePath()); UnixSocketNative.listen(ss, 1); ready.countDown(); int cs = UnixSocketNative.accept(ss, 0); int read = UnixSocketNative.send(cs, "hello".getBytes(), 0, 5); UnixSocketNative.close(cs); return true; } finally { UnixSocketNative.close(ss); } }); {// zero byte write is a noop ready.await(); int cs = UnixSocketNative.socket(); UnixSocketNative.connect(cs, serverSocket.getAbsolutePath()); // must NPE on buff try { UnixSocketNative.recv(cs, null, 0, 10); fail("should have NPEd"); } catch (NullPointerException ignored) { } // invalid offset try { UnixSocketNative.recv(cs, new byte[5], -1, 1); fail("should have IAEd"); } catch (IllegalArgumentException ignored) { } // invalid length try { UnixSocketNative.recv(cs, new byte[5], 0, -1); fail("should have IAEd"); } catch (IllegalArgumentException ignored) { } // invalid length try { UnixSocketNative.recv(cs, new byte[5], 0, 0); fail("should have IAEd"); } catch (IllegalArgumentException ignored) { } // invalid offset beyond buffer try { UnixSocketNative.recv(cs, new byte[5], 100, 10); fail("should have IAEd"); } catch (IllegalArgumentException ignored) { } // invalid offset try { UnixSocketNative.recv(cs, "hello".getBytes(), -1, 10); fail("should have IAEd"); } catch (IllegalArgumentException ignored) { } // validate a real write to be sure byte[] buf = new byte[5]; int count = UnixSocketNative.recv(cs, buf, 0, 5); assertThat(count).isEqualTo(5); assertThat(buf).isEqualTo("hello".getBytes()); } } @Test public void shouldSetSocketOpts() throws Exception { int sock = UnixSocketNative.socket(); try { try { UnixSocketNative.setSendBufSize(-1, 1); fail("should have failed"); } catch (UnixSocketException ignored) { } try { UnixSocketNative.setSendBufSize(sock, -1); fail("should have IAEd"); } catch (IllegalArgumentException ignored) { } UnixSocketNative.setSendBufSize(sock, 65535); try { UnixSocketNative.setRecvBufSize(-1, 1); fail("should have failed"); } catch (UnixSocketException ignored) { } try { UnixSocketNative.setRecvBufSize(sock, -1); fail("should have IAEd"); } catch (IllegalArgumentException ignored) { } UnixSocketNative.setRecvBufSize(sock, 65535); try { UnixSocketNative.setSendTimeout(-1, 1); fail("should have failed"); } catch (UnixSocketException ignored) { } try { UnixSocketNative.setSendTimeout(sock, -1); fail("should have IAEd"); } catch (IllegalArgumentException ignored) { } UnixSocketNative.setSendTimeout(sock, 2000); assertThat(UnixSocketNative.getSendTimeout(sock)).isEqualTo(2000); try { UnixSocketNative.setRecvTimeout(-1, 1); fail("should have failed"); } catch (UnixSocketException ignored) { } try { UnixSocketNative.setRecvTimeout(sock, -1); fail("should have IAEd"); } catch (IllegalArgumentException ignored) { } UnixSocketNative.setRecvTimeout(sock, 3000); assertThat(UnixSocketNative.getRecvTimeout(sock)).isEqualTo(3000); } finally { UnixSocketNative.close(sock); } } @Test public void shouldHandleReadTimeouts() throws Exception { CountDownLatch ready = new CountDownLatch(1); File serverSocket = createSocketFile(); CompletableFuture<Boolean> result = runServerLoop(() -> { int ss = UnixSocketNative.socket(); try { UnixSocketNative.bind(ss, serverSocket.getAbsolutePath()); UnixSocketNative.listen(ss, 1); ready.countDown(); int cs = UnixSocketNative.accept(ss, 0); Thread.sleep(100); int read = UnixSocketNative.send(cs, "hello".getBytes(), 0, 5); UnixSocketNative.close(cs); return true; } finally { UnixSocketNative.close(ss); } }); int clientFd = UnixSocketNative.socket(); UnixSocketNative.setRecvTimeout(clientFd,50); ready.await(); UnixSocketNative.connect(clientFd,serverSocket.getAbsolutePath()); byte[] buf = new byte[100]; try { UnixSocketNative.recv(clientFd, buf, 0, buf.length); fail("should have timed out"); }catch (SocketTimeoutException ignored){ } } @Test public void shouldHandleConnectTimeouts() throws Exception { CountDownLatch ready = new CountDownLatch(1); File serverSocket = createSocketFile(); CompletableFuture<Boolean> result = runServerLoop(() -> { int ss = UnixSocketNative.socket(); try { UnixSocketNative.bind(ss, serverSocket.getAbsolutePath()); UnixSocketNative.listen(ss, 1); ready.countDown(); Thread.sleep(1000); return true; } finally { UnixSocketNative.close(ss); } }); int clientFd = UnixSocketNative.socket(); UnixSocketNative.setSendTimeout(clientFd,50); ready.await(); try { UnixSocketNative.connect(clientFd,serverSocket.getAbsolutePath()); }catch (SocketTimeoutException ignored){ } } }
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/httpgateway/FunctionHTTPGatewayContextTest.java
runtime/src/test/java/com/fnproject/fn/runtime/httpgateway/FunctionHTTPGatewayContextTest.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.httpgateway; import com.fnproject.fn.api.Headers; import com.fnproject.fn.api.InvocationContext; 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 static org.assertj.core.api.Assertions.assertThat; /** * Created on 20/09/2018. * <p> * (c) 2018 Oracle Corporation */ public class FunctionHTTPGatewayContextTest { @Rule public MockitoRule rule = MockitoJUnit.rule(); @Mock InvocationContext ctx; @Test public void shouldCreateGatewayContextFromInputs() { Headers h = Headers.emptyHeaders() .setHeader("H1", "h1val") .setHeader("Fn-Http-Method", "PATCH") .setHeader("Fn-Http-Request-Url", "http://blah.com?a=b&c=d&c=e") .setHeader("Fn-Http-H-", "ignored") .setHeader("Fn-Http-H-A", "b") .setHeader("Fn-Http-H-mv", "c", "d"); Mockito.when(ctx.getRequestHeaders()).thenReturn(h); FunctionHTTPGatewayContext hctx = new FunctionHTTPGatewayContext(ctx); assertThat(hctx.getHeaders()) .isEqualTo(Headers.emptyHeaders() .addHeader("A", "b") .addHeader("mv", "c", "d")); assertThat(hctx.getRequestURL()) .isEqualTo("http://blah.com?a=b&c=d&c=e"); assertThat(hctx.getQueryParameters().get("a")).contains("b"); assertThat(hctx.getQueryParameters().getValues("c")).contains("d", "e"); assertThat(hctx.getMethod()).isEqualTo("PATCH"); } @Test public void shouldCreateGatewayContextFromEmptyHeaders() { Mockito.when(ctx.getRequestHeaders()).thenReturn(Headers.emptyHeaders()); FunctionHTTPGatewayContext hctx = new FunctionHTTPGatewayContext(ctx); assertThat(hctx.getMethod()).isEqualTo(""); assertThat(hctx.getRequestURL()).isEqualTo(""); assertThat(hctx.getHeaders()).isEqualTo(Headers.emptyHeaders()); assertThat(hctx.getQueryParameters().getAll()).isEmpty(); } @Test public void shouldPassThroughResponseAttributes() { Mockito.when(ctx.getRequestHeaders()).thenReturn(Headers.emptyHeaders()); FunctionHTTPGatewayContext hctx = new FunctionHTTPGatewayContext(ctx); hctx.setResponseHeader("My-Header", "foo", "bar"); Mockito.verify(ctx).setResponseHeader("Fn-Http-H-My-Header", "foo", "bar"); hctx.setResponseHeader("Content-Type", "my/ct", "ignored"); Mockito.verify(ctx).setResponseContentType("my/ct"); Mockito.verify(ctx).setResponseHeader("Fn-Http-H-Content-Type", "my/ct"); hctx.addResponseHeader("new-H", "v1"); Mockito.verify(ctx).addResponseHeader("Fn-Http-H-new-H", "v1"); hctx.setStatusCode(101); Mockito.verify(ctx).setResponseHeader("Fn-Http-Status", "101"); } }
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/main/java/com/fnproject/fn/runtime/MethodFunctionInvoker.java
runtime/src/main/java/com/fnproject/fn/runtime/MethodFunctionInvoker.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.lang.reflect.InvocationTargetException; import java.util.Optional; import com.fnproject.fn.api.FunctionInvoker; 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.api.exception.FunctionInputHandlingException; import com.fnproject.fn.api.exception.FunctionOutputHandlingException; import com.fnproject.fn.runtime.exception.InternalFunctionInvocationException; /** * Method function invoker * <p> * <p> * This handles the binding and invocation of function calls via java methods. */ public class MethodFunctionInvoker implements FunctionInvoker { /** * Invoke the function wrapped by this loader * * @param evt The function event * @return the function response * @throws InternalFunctionInvocationException if the invocation fails */ @Override public Optional<OutputEvent> tryInvoke(InvocationContext ctx, InputEvent evt) throws InternalFunctionInvocationException { FunctionRuntimeContext runtimeContext = (FunctionRuntimeContext) ctx.getRuntimeContext(); MethodWrapper method = runtimeContext.getMethodWrapper(); Object[] userFunctionParams = coerceParameters(ctx, method, evt); Object rawResult; try { rawResult = method.getTargetMethod().invoke(ctx.getRuntimeContext().getInvokeInstance().orElse(null), userFunctionParams); } catch (IllegalAccessException | InvocationTargetException e) { throw new InternalFunctionInvocationException(e.getCause().getMessage(), e.getCause()); } return coerceReturnValue(ctx, method, rawResult); } protected 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 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")); } protected 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); } } }
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/main/java/com/fnproject/fn/runtime/PrimitiveTypeResolver.java
runtime/src/main/java/com/fnproject/fn/runtime/PrimitiveTypeResolver.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.HashMap; import java.util.Map; public class PrimitiveTypeResolver { private static final Map<Class<?>, Class<?>> boxedTypes = new HashMap<>(); static { boxedTypes.put(void.class, Void.class); boxedTypes.put(boolean.class, Boolean.class); boxedTypes.put(byte.class, Byte.class); boxedTypes.put(char.class, Character.class); boxedTypes.put(short.class, Short.class); boxedTypes.put(int.class, Integer.class); boxedTypes.put(long.class, Long.class); boxedTypes.put(float.class, Float.class); boxedTypes.put(double.class, Double.class); } /** * Resolves cls from a possibly primitive class to a boxed type otherwise just returns cls */ public static Class<?> resolve(Class<?> cls) { if (cls.isPrimitive()) { return boxedTypes.get(cls); } 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/runtime/src/main/java/com/fnproject/fn/runtime/ReadOnceInputEvent.java
runtime/src/main/java/com/fnproject/fn/runtime/ReadOnceInputEvent.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.exception.FunctionInputHandlingException; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.time.Instant; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; /** * Wrapper for an incoming fn invocation event * <p> * This in */ public class ReadOnceInputEvent implements InputEvent { private final BufferedInputStream body; private final AtomicBoolean consumed = new AtomicBoolean(false); private final Headers headers; private final Instant deadline; private final String callID; public ReadOnceInputEvent(InputStream body, Headers headers, String callID, Instant deadline) { this.body = new BufferedInputStream(Objects.requireNonNull(body, "body")); this.headers = Objects.requireNonNull(headers, "headers"); this.callID = Objects.requireNonNull(callID, "callID"); this.deadline = Objects.requireNonNull(deadline, "deadline"); body.mark(Integer.MAX_VALUE); } /** * Consume the input stream of this event - * This may be done exactly once per event * * @param dest a consumer for the body * @throws IllegalStateException if the input has been consumed */ @Override public <T> T consumeBody(Function<InputStream, T> dest) { if (consumed.compareAndSet(false, true)) { try (InputStream rb = body) { return dest.apply(rb); } catch (IOException e) { throw new FunctionInputHandlingException("Error reading input stream", e); } } else { throw new IllegalStateException("Body has already been consumed"); } } @Override public String getCallID() { return callID; } @Override public Instant getDeadline() { return deadline; } @Override public Headers getHeaders() { return headers; } @Override public void close() throws IOException { body.close(); } }
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/main/java/com/fnproject/fn/runtime/EventCodec.java
runtime/src/main/java/com/fnproject/fn/runtime/EventCodec.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.InputEvent; import com.fnproject.fn.api.OutputEvent; /** * Event Codec - deals with different calling conventions between fn and the function docker container */ public interface EventCodec { /** * Handler handles function content based on codec events * <p> * A handler should generally deal with all exceptions (except errors) and convert them into appropriate OutputEvents */ interface Handler { /** * Handle a function input event and generate a response * * @param event the event to handle * @return an output event indicating the result of calling a function or an error */ OutputEvent handle(InputEvent event); } /** * Run Codec should continuously run the function event loop until either the FDK should exit normally (returning normally) or an error occurred. * <p> * Codec should invoke the handler for each received event * * @param h the handler to run */ void runCodec(Handler h); }
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/main/java/com/fnproject/fn/runtime/FunctionRuntimeContext.java
runtime/src/main/java/com/fnproject/fn/runtime/FunctionRuntimeContext.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.*; import com.fnproject.fn.api.exception.FunctionConfigurationException; import com.fnproject.fn.api.exception.FunctionInputHandlingException; import com.fnproject.fn.runtime.coercion.*; import com.fnproject.fn.runtime.coercion.jackson.JacksonCoercion; import com.fnproject.fn.runtime.exception.FunctionClassInstantiationException; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; public class FunctionRuntimeContext implements RuntimeContext { private final Map<String, String> config; private final MethodWrapper method; private final Map<String, Object> attributes = new HashMap<>(); private final List<FunctionInvoker> preCallHandlers = new ArrayList<>(); private final List<FunctionInvoker> configuredInvokers = new ArrayList<>(); private Object instance; private final List<InputCoercion> builtinInputCoercions = Arrays.asList(new ContextCoercion(), new StringCoercion(), new ByteArrayCoercion(), new InputEventCoercion(), JacksonCoercion.instance()); private final List<InputCoercion> userInputCoercions = new LinkedList<>(); private final List<OutputCoercion> builtinOutputCoercions = Arrays.asList(new StringCoercion(), new ByteArrayCoercion(), new VoidCoercion(), new OutputEventCoercion(), JacksonCoercion.instance()); private final List<OutputCoercion> userOutputCoercions = new LinkedList<>(); public FunctionRuntimeContext(MethodWrapper method, Map<String, String> config) { this.method = method; this.config = Objects.requireNonNull(config); configuredInvokers.add(new MethodFunctionInvoker()); } @Override public String getAppID() { return config.getOrDefault("FN_APP_ID", ""); } @Override public String getFunctionID() { return config.getOrDefault("FN_FN_ID", ""); } @Override public String getAppName() { return config.getOrDefault("FN_APP_NAME", ""); } @Override public String getFunctionName() { return config.getOrDefault("FN_FN_NAME", ""); } @Override public Optional<Object> getInvokeInstance() { if (!Modifier.isStatic(getMethod().getTargetMethod().getModifiers())) { if (instance == null) { try { Constructor<?> constructors[] = getMethod().getTargetClass().getConstructors(); if (constructors.length == 1) { Constructor<?> ctor = constructors[0]; if (ctor.getParameterTypes().length == 0) { instance = ctor.newInstance(); } else if (ctor.getParameterTypes().length == 1) { if (RuntimeContext.class.isAssignableFrom(ctor.getParameterTypes()[0])) { instance = ctor.newInstance(FunctionRuntimeContext.this); } else { if (getMethod().getTargetClass().getEnclosingClass() != null && !Modifier.isStatic(getMethod().getTargetClass().getModifiers())) { throw new FunctionClassInstantiationException("The function " + getMethod().getTargetClass() + " cannot be instantiated as it is a non-static inner class"); } else { throw new FunctionClassInstantiationException("The function " + getMethod().getTargetClass() + " cannot be instantiated as its constructor takes an unrecognized argument of type " + constructors[0].getParameterTypes()[0] + ". Function classes should have a single public constructor that takes either no arguments or a RuntimeContext argument"); } } } else { throw new FunctionClassInstantiationException("The function " + getMethod().getTargetClass() + " cannot be instantiated as its constructor takes more than one argument. Function classes should have a single public constructor that takes either no arguments or a RuntimeContext argument"); } } else { if (constructors.length == 0) { throw new FunctionClassInstantiationException("The function " + getMethod().getTargetClass() + " cannot be instantiated as it has no public constructors. Function classes should have a single public constructor that takes either no arguments or a RuntimeContext argument"); } else { throw new FunctionClassInstantiationException("The function " + getMethod().getTargetClass() + " cannot be instantiated as it has multiple public constructors. Function classes should have a single public constructor that takes either no arguments or a RuntimeContext argument"); } } } catch (InvocationTargetException e) { throw new FunctionClassInstantiationException("An error occurred in the function constructor while instantiating " + getMethod().getTargetClass(), e.getCause()); } catch (InstantiationException | IllegalAccessException e) { throw new FunctionClassInstantiationException("The function class " + getMethod().getTargetClass() + " could not be instantiated", e); } } return Optional.of(instance); } return Optional.empty(); } @Override public Optional<String> getConfigurationByKey(String key) { return Optional.ofNullable(config.get(key)); } @Override public Map<String, String> getConfiguration() { return config; } @Override public <T> Optional<T> getAttribute(String att, Class<T> type) { Objects.requireNonNull(att); Objects.requireNonNull(type); return Optional.ofNullable(type.cast(attributes.get(att))); } @Override public void setAttribute(String att, Object val) { Objects.requireNonNull(att); attributes.put(att, val); } @Override public void addInputCoercion(InputCoercion ic) { userInputCoercions.add(Objects.requireNonNull(ic)); } @Override public List<InputCoercion> getInputCoercions(MethodWrapper targetMethod, int param) { Annotation parameterAnnotations[] = targetMethod.getTargetMethod().getParameterAnnotations()[param]; Optional<Annotation> coercionAnnotation = Arrays.stream(parameterAnnotations) .filter((ann) -> ann.annotationType().equals(InputBinding.class)) .findFirst(); if (coercionAnnotation.isPresent()) { try { List<InputCoercion> coercionList = new ArrayList<>(); InputBinding inputBindingAnnotation = (InputBinding) coercionAnnotation.get(); coercionList.add(inputBindingAnnotation.coercion().getDeclaredConstructor().newInstance()); return coercionList; } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { throw new FunctionInputHandlingException("Unable to instantiate input coercion class for argument " + param + " of " + targetMethod); } } List<InputCoercion> inputList = new ArrayList<>(); inputList.addAll(userInputCoercions); inputList.addAll(builtinInputCoercions); return inputList; } @Override public void addOutputCoercion(OutputCoercion oc) { userOutputCoercions.add(Objects.requireNonNull(oc)); } @Override public void addInvoker(FunctionInvoker invoker, FunctionInvoker.Phase phase) { switch (phase) { case PreCall: preCallHandlers.add(0, invoker); break; case Call: configuredInvokers.add(0, invoker); break; default: throw new IllegalArgumentException("Unsupported phase " + phase); } } @Override public MethodWrapper getMethod() { return method; } public FunctionInvocationContext newInvocationContext(InputEvent inputEvent) { return new FunctionInvocationContext(this, inputEvent); } public OutputEvent tryInvoke(InputEvent evt, InvocationContext entryPoint) { for (FunctionInvoker invoker : preCallHandlers) { Optional<OutputEvent> result = invoker.tryInvoke(entryPoint, evt); if (result.isPresent()) { return result.get(); } } for (FunctionInvoker invoker : configuredInvokers) { Optional<OutputEvent> result = invoker.tryInvoke(entryPoint, evt); if (result.isPresent()) { return result.get(); } } return null; } @Override public List<OutputCoercion> getOutputCoercions(Method method) { OutputBinding coercionAnnotation = method.getAnnotation(OutputBinding.class); if (coercionAnnotation != null) { try { List<OutputCoercion> coercionList = new ArrayList<>(); coercionList.add(coercionAnnotation.coercion().getDeclaredConstructor().newInstance()); return coercionList; } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { throw new FunctionConfigurationException("Unable to instantiate output coercion class for method " + getMethod()); } } List<OutputCoercion> outputList = new ArrayList<>(); outputList.addAll(userOutputCoercions); outputList.addAll(builtinOutputCoercions); return outputList; } public MethodWrapper getMethodWrapper() { return method; } }
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/main/java/com/fnproject/fn/runtime/EntryPoint.java
runtime/src/main/java/com/fnproject/fn/runtime/EntryPoint.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.IOException; import java.io.PrintStream; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.regex.Pattern; import com.fnproject.fn.api.FnFeature; import com.fnproject.fn.api.FnFeatures; import com.fnproject.fn.api.InputEvent; import com.fnproject.fn.api.MethodWrapper; import com.fnproject.fn.api.OutputEvent; import com.fnproject.fn.api.RuntimeFeature; import com.fnproject.fn.api.exception.FunctionInputHandlingException; import com.fnproject.fn.api.exception.FunctionLoadException; import com.fnproject.fn.api.exception.FunctionOutputHandlingException; import com.fnproject.fn.runtime.exception.FunctionInitializationException; import com.fnproject.fn.runtime.exception.InternalFunctionInvocationException; import com.fnproject.fn.runtime.exception.InvalidEntryPointException; /** * Main entry point */ public class EntryPoint { // regex to sanitize version properties on the off chance they fall outside of acceptable header values private static final Pattern safeVersion = Pattern.compile("[^\\w ()._-]+"); public static void main(String... args) { PrintStream originalSystemOut = System.out; System.setOut(System.err); String format = System.getenv("FN_FORMAT"); EventCodec codec; if (format.equals(HTTPStreamCodec.HTTP_STREAM_FORMAT)) { // reduce risk of confusion due to non-header like system properties String jvmName = safeVersion.matcher(System.getProperty("java.vm.name")).replaceAll(""); String jvmVersion = safeVersion.matcher(System.getProperty("java.version")).replaceAll(""); String fdkVersion = "fdk-java/" + Version.FDK_VERSION + " (jvm=" + (jvmName + ", jvmv=" + jvmVersion + ")"); String runtimeVersion = "java/" + jvmName + " " + jvmVersion; codec = new HTTPStreamCodec(System.getenv(), fdkVersion, runtimeVersion); } else { throw new FunctionInputHandlingException("Unsupported function format:" + format); } int exitCode = new EntryPoint().run(System.getenv(), codec, System.err, args); System.setOut(originalSystemOut); System.exit(exitCode); } /* * If enabled, print the logging framing content otherwise do nothing */ private Consumer<InputEvent> logFramer(Map<String, String> config) { String framer = config.getOrDefault("FN_LOGFRAME_NAME", ""); if (!framer.isEmpty()) { String valueSrc = config.getOrDefault("FN_LOGFRAME_HDR", ""); if (!valueSrc.isEmpty()) { return (evt) -> { String id = evt.getHeaders().get(valueSrc).orElse(""); if (!id.isEmpty()) { System.out.println("\n" + framer + "=" + id + "\n"); System.err.println("\n" + framer + "=" + id + "\n"); } }; } } return (event) -> { }; } /** * Entry point runner - this executes the whole lifecycle of the fn Java FDK runtime - including multiple invocations in the function for hot functions * * @param env the map of environment variables to run the function with (typically System.getenv but may be customised for testing) * @param codec the codec to run the function with * @param loggingOutput the stream to send function error/logging to - this will be wrapped into System.err within the funciton * @param args any further args passed to the entry point - specifically the class/method name * @return the desired process exit status */ public int run(Map<String, String> env, EventCodec codec, PrintStream loggingOutput, String... args) { if (args.length != 1) { throw new InvalidEntryPointException("Expected one argument, of the form com.company.project.MyFunctionClass::myFunctionMethod"); } // TODO better parsing of class stuff String[] classMethod = args[0].split("::"); if (classMethod.length != 2) { throw new InvalidEntryPointException("Entry point is malformed expecting a string of the form com.company.project.MyFunctionClass::myFunctionMethod"); } String cls = classMethod[0]; String mth = classMethod[1]; // TODO deprecate with default contract final AtomicInteger lastStatus = new AtomicInteger(); try { final Map<String, String> configFromEnvVars = Collections.unmodifiableMap(excludeInternalConfigAndHeaders(env)); Consumer<InputEvent> logFramer = logFramer(configFromEnvVars); codec.runCodec(new EventCodec.Handler() { FunctionRuntimeContext _runtimeContext; // Create runtime context within first call to ensure that init errors are propagated private FunctionRuntimeContext getRuntimeContext() { if (_runtimeContext == null) { FunctionLoader functionLoader = new FunctionLoader(); MethodWrapper method = functionLoader.loadClass(cls, mth); FunctionRuntimeContext runtimeContext = new FunctionRuntimeContext(method, configFromEnvVars); FnFeature f = method.getTargetClass().getAnnotation(FnFeature.class); if (f != null) { enableFeature(runtimeContext, f); } FnFeatures fs = method.getTargetClass().getAnnotation(FnFeatures.class); if (fs != null) { for (FnFeature fnFeature : fs.value()) { enableFeature(runtimeContext, fnFeature); } } FunctionConfigurer functionConfigurer = new FunctionConfigurer(); functionConfigurer.configure(runtimeContext); _runtimeContext = runtimeContext; } return _runtimeContext; } @Override public OutputEvent handle(InputEvent evt) { try { // output log frame prior to any user code execution logFramer.accept(evt); FunctionRuntimeContext runtimeContext = getRuntimeContext(); FunctionInvocationContext fic = runtimeContext.newInvocationContext(evt); try (InputEvent myEvt = evt) { OutputEvent output = runtimeContext.tryInvoke(evt, fic); if (output == null) { throw new FunctionInputHandlingException("No invoker found for input event"); } if (output.isSuccess()) { lastStatus.set(0); fic.fireOnSuccessfulInvocation(); } else { lastStatus.set(1); fic.fireOnFailedInvocation(); } return output.withHeaders(output.getHeaders().setHeaders(fic.getAdditionalResponseHeaders())); } catch (IOException err) { fic.fireOnFailedInvocation(); throw new FunctionInputHandlingException("Error closing function input", err); } catch (Exception e) { // Make sure we commit any pending Flows, then rethrow fic.fireOnFailedInvocation(); throw e; } } catch (InternalFunctionInvocationException fie) { loggingOutput.println("An error occurred in function: " + filterStackTraceToOnlyIncludeUsersCode(fie)); loggingOutput.flush(); // Here: completer-invoked continuations are *always* reported as successful to the Fn platform; // the completer interprets the embedded HTTP-framed response. lastStatus.set(fie.toOutput().isSuccess() ? 0 : 1); return fie.toOutput(); } catch (FunctionLoadException | FunctionInputHandlingException | FunctionOutputHandlingException e) { // catch all block; loggingOutput.println(filterStackTraceToOnlyIncludeUsersCode(e)); loggingOutput.flush(); lastStatus.set(2); return new InternalFunctionInvocationException("Error initializing function", e).toOutput(); } } }); } catch (Exception ee) { loggingOutput.println("An unexpected error occurred:"); ee.printStackTrace(loggingOutput); return 1; } return lastStatus.get(); } private void enableFeature(FunctionRuntimeContext runtimeContext, FnFeature f) { RuntimeFeature rf; try { Class<? extends RuntimeFeature> featureClass = f.value(); rf = featureClass.newInstance(); } catch (Exception e) { throw new FunctionInitializationException("Could not load feature class " + f.value().toString(), e); } try { rf.initialize(runtimeContext); } catch (Exception e) { throw new FunctionInitializationException("Exception while calling initialization on runtime feature " + f.value(), e); } } /** * Produces a string representation of the supplied Throwable. * <p> * Exception causes are walked until the end, each exception has its stack walked until either: * - the end, or * - a class in `com.fnproject.fn` * <p> * This means the user sees a full stack trace of their code, messages without stacktraces from * the layers of com.fnproject.fn which are passed through, with the root cause at the top of * the trace */ private String filterStackTraceToOnlyIncludeUsersCode(Throwable t) { StringBuilder sb = new StringBuilder(); Throwable current = t; while (current != null) { addExceptionToStringBuilder(sb, current); current = current.getCause(); } return sb.toString(); } private void addExceptionToStringBuilder(StringBuilder sb, Throwable t) { if (t.toString().startsWith("com.fnproject.fn")) { // This elides the FQCN of the exception class if it's from our runtime. sb.append(t.getMessage()); } else { sb.append("Caused by: ").append(t.toString()); } for (StackTraceElement elem : t.getStackTrace()) { if (elem.getClassName().startsWith("com.fnproject.fn")) { break; } sb.append("\n at ").append(elem.toString()); } sb.append("\n"); } /** * @return a map of all the values in env having excluded any internal config variables that the platform uses and * any headers that were added to env. Headers are identified as being variables prepended with 'HEADER_'. */ private Map<String, String> excludeInternalConfigAndHeaders(Map<String, String> env) { Set<String> nonConfigEnvKeys = new HashSet<>(Arrays.asList("fn_path", "fn_method", "fn_request_url", "fn_format", "content-length", "fn_call_id")); Map<String, String> config = new HashMap<>(); for (Map.Entry<String, String> entry : env.entrySet()) { String lowerCaseKey = entry.getKey().toLowerCase(); if (!lowerCaseKey.startsWith("header_") && !nonConfigEnvKeys.contains(lowerCaseKey)) { config.put(entry.getKey(), entry.getValue()); } } return config; } }
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/main/java/com/fnproject/fn/runtime/FunctionInvocationCallback.java
runtime/src/main/java/com/fnproject/fn/runtime/FunctionInvocationCallback.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; public interface FunctionInvocationCallback { void fireOnSuccessfulInvocation(); void fireOnFailedInvocation(); }
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/main/java/com/fnproject/fn/runtime/FunctionInvocationContext.java
runtime/src/main/java/com/fnproject/fn/runtime/FunctionInvocationContext.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.InvocationContext; import com.fnproject.fn.api.InvocationListener; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; /** * Function invocation context implementation, * Delegates invocation callbacks to configured listeners */ public class FunctionInvocationContext implements InvocationContext, FunctionInvocationCallback { private final FunctionRuntimeContext runtimeContext; private final List<InvocationListener> invocationListeners = new CopyOnWriteArrayList<>(); private final InputEvent event; private final Map<String, List<String>> additionalResponseHeaders = new ConcurrentHashMap<>(); FunctionInvocationContext(FunctionRuntimeContext ctx, InputEvent event) { this.runtimeContext = ctx; this.event = event; } @Override public FunctionRuntimeContext getRuntimeContext() { return runtimeContext; } @Override public void addListener(InvocationListener listener) { invocationListeners.add(listener); } @Override public Headers getRequestHeaders() { return event.getHeaders(); } @Override public void addResponseHeader(String key, String value) { Objects.requireNonNull(key, "key"); Objects.requireNonNull(value, "value"); additionalResponseHeaders.merge(key, Collections.singletonList(value), (a, b) -> { List<String> l = new ArrayList<>(a); l.addAll(b); return l; }); } /** * returns the internal map of added response headers * * @return mutable map of internal response headers */ Map<String, List<String>> getAdditionalResponseHeaders() { return additionalResponseHeaders; } @Override public void setResponseHeader(String key, String value, String... vs) { Objects.requireNonNull(key, "key"); Objects.requireNonNull(vs, "vs"); Arrays.stream(vs).forEach(v->Objects.requireNonNull(v,"null value in list ")); String cKey = Headers.canonicalKey(key); if (value == null) { additionalResponseHeaders.remove(cKey); return; } additionalResponseHeaders.put(cKey, Collections.singletonList(value)); } @Override public void fireOnSuccessfulInvocation() { for (InvocationListener listener : invocationListeners) { try { listener.onSuccess(); } catch (Exception ignored) { } } } @Override public void fireOnFailedInvocation() { for (InvocationListener listener : invocationListeners) { try { listener.onFailure(); } catch (Exception ignored) { } } } }
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/main/java/com/fnproject/fn/runtime/DefaultFunctionInvocationContext.java
runtime/src/main/java/com/fnproject/fn/runtime/DefaultFunctionInvocationContext.java
package com.fnproject.fn.runtime; import java.util.List; import java.util.Map; import com.fnproject.fn.api.InputEvent; public class DefaultFunctionInvocationContext extends FunctionInvocationContext { public DefaultFunctionInvocationContext(FunctionRuntimeContext ctx, InputEvent event) { super(ctx, event); } public Map<String, List<String>> getAdditionalResponseHeaders() { return super.getAdditionalResponseHeaders(); } }
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/main/java/com/fnproject/fn/runtime/MethodTypeWrapper.java
runtime/src/main/java/com/fnproject/fn/runtime/MethodTypeWrapper.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 com.fnproject.fn.api.TypeWrapper; import net.jodah.typetools.TypeResolver; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; public final class MethodTypeWrapper implements TypeWrapper { private final Class<?> parameterClass; private MethodTypeWrapper(Class<?> parameterClass) { this.parameterClass = parameterClass; } @Override public Class<?> getParameterClass() { return parameterClass; } static Class<?> resolveType(Type type, MethodWrapper src) { if (type instanceof Class) { return PrimitiveTypeResolver.resolve((Class<?>) type); } else if (type instanceof ParameterizedType) { return (Class<?>) ((ParameterizedType) type).getRawType(); } Class<?> resolvedType = TypeResolver.resolveRawArgument(type, src.getTargetClass()); if (resolvedType == TypeResolver.Unknown.class) { // TODO: Decide what exception to throw here throw new RuntimeException("Cannot infer type of method parameter"); } else { return resolvedType; } } public static TypeWrapper fromParameter(MethodWrapper method, int paramIndex) { return new MethodTypeWrapper(resolveType(method.getTargetMethod().getGenericParameterTypes()[paramIndex], method)); } public static TypeWrapper fromReturnType(MethodWrapper method) { return new MethodTypeWrapper(resolveType(method.getTargetMethod().getGenericReturnType(), method)); } }
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/main/java/com/fnproject/fn/runtime/HTTPStreamCodec.java
runtime/src/main/java/com/fnproject/fn/runtime/HTTPStreamCodec.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.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.attribute.PosixFilePermissions; import java.time.Instant; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import com.fasterxml.jackson.core.io.CharTypes; import com.fnproject.fn.api.Headers; import com.fnproject.fn.api.InputEvent; import com.fnproject.fn.api.OutputEvent; import com.fnproject.fn.api.exception.FunctionInputHandlingException; import com.fnproject.fn.api.exception.FunctionOutputHandlingException; import com.fnproject.fn.runtime.exception.FunctionIOException; import com.fnproject.fn.runtime.exception.FunctionInitializationException; import com.fnproject.fn.runtime.ntv.UnixServerSocket; import com.fnproject.fn.runtime.ntv.UnixSocket; import org.apache.http.Header; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpVersion; import org.apache.http.ParseException; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.DefaultBHttpServerConnection; import org.apache.http.impl.io.EmptyInputStream; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicStatusLine; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpService; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.UriHttpRequestHandlerMapper; /** * Fn HTTP Stream over Unix domain sockets codec * <p> * <p> * This creates a new unix socket on the address specified by env["FN_LISTENER"] - and accepts requests. * <p> * This currently only handles exactly one concurrent connection * <p> * Created on 24/08/2018. * <p> * (c) 2018 Oracle Corporation */ public final class HTTPStreamCodec implements EventCodec, Closeable { public static final String HTTP_STREAM_FORMAT = "http-stream"; private static final String FN_LISTENER = "FN_LISTENER"; private static final Set<String> stripInputHeaders; private static final Set<String> stripOutputHeaders; private final Map<String, String> env; private final String fdkVersion; private final String runtimeVersion; private final AtomicBoolean stopping = new AtomicBoolean(false); private final File socketFile; private final CompletableFuture<Boolean> stopped = new CompletableFuture<>(); private final UnixServerSocket socket; private final File tempFile; static { Set<String> hin = new HashSet<>(); hin.add("Host"); hin.add("Accept-Encoding"); hin.add("Transfer-Encoding"); hin.add("User-Agent"); hin.add("Connection"); hin.add("TE"); stripInputHeaders = Collections.unmodifiableSet(hin); Set<String> hout = new HashSet<>(); hout.add("Content-Length"); hout.add("Transfer-Encoding"); hout.add("Connection"); hout.add("Fn-Fdk-Version"); stripOutputHeaders = Collections.unmodifiableSet(hout); } private String randomString() { int leftLimit = 97; int rightLimit = 122; int targetStringLength = 10; Random random = new Random(); StringBuilder buffer = new StringBuilder(targetStringLength); for (int i = 0; i < targetStringLength; i++) { int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1)); buffer.append((char) randomLimitedInt); } return buffer.toString(); } /** * Construct a new HTTPStreamCodec based on the environment * * @param env an env map * @param fdkVersion the version to report to the runtime * @param runtimeVersion underlying JVM version to report to the runtime */ HTTPStreamCodec(Map<String, String> env, String fdkVersion, String runtimeVersion) { this.env = Objects.requireNonNull(env, "env"); this.fdkVersion = Objects.requireNonNull(fdkVersion, "fdkVersion"); this.runtimeVersion = Objects.requireNonNull(runtimeVersion, "runtimeVersion"); String listenerAddress = getRequiredEnv(FN_LISTENER); if (!listenerAddress.startsWith("unix:/")) { throw new FunctionInitializationException("Invalid listener address - it should start with unix:/ :'" + listenerAddress + "'"); } String listenerFile = listenerAddress.substring("unix:".length()); socketFile = new File(listenerFile); UnixServerSocket serverSocket = null; File listenerDir = socketFile.getParentFile(); tempFile = new File(listenerDir, randomString() + ".sock"); try { serverSocket = UnixServerSocket.listen(tempFile.getAbsolutePath(), 1); // Adjust socket permissions and move file Files.setPosixFilePermissions(tempFile.toPath(), PosixFilePermissions.fromString("rw-rw-rw-")); Files.createSymbolicLink(socketFile.toPath(), tempFile.toPath().getFileName()); this.socket = serverSocket; } catch (IOException e) { if (serverSocket != null) { try { serverSocket.close(); } catch (IOException ignored) { } } throw new FunctionInitializationException("Unable to bind to unix socket in " + socketFile, e); } } private String jsonError(String message, String detail) { if (message == null) { message = ""; } StringBuilder sb = new StringBuilder(); sb.append("{ \"message\":\""); CharTypes.appendQuoted(sb, message); sb.append("\""); if (detail != null) { sb.append(", \"detail\":\""); CharTypes.appendQuoted(sb, detail); sb.append("\""); } sb.append("}"); return sb.toString(); } @Override public void runCodec(Handler h) { UriHttpRequestHandlerMapper mapper = new UriHttpRequestHandlerMapper(); mapper.register("/call", ((request, response, context) -> { InputEvent evt; try { evt = readEvent(request); } catch (FunctionInputHandlingException e) { response.setStatusCode(500); response.setEntity(new StringEntity(jsonError("Invalid input for function", e.getMessage()), ContentType.APPLICATION_JSON)); return; } OutputEvent outEvt; try { outEvt = h.handle(evt); } catch (Exception e) { response.setStatusCode(500); response.setEntity(new StringEntity(jsonError("Unhandled internal error in FDK", e.getMessage()), ContentType.APPLICATION_JSON)); return; } try { writeEvent(outEvt, response); } catch (Exception e) { // TODO strange edge cases might appear with headers where the response is half written here response.setStatusCode(500); response.setEntity(new StringEntity(jsonError("Unhandled internal error while writing FDK response", e.getMessage()), ContentType.APPLICATION_JSON)); } } )); ImmutableHttpProcessor requestProcess = new ImmutableHttpProcessor(new HttpRequestInterceptor[0], new HttpResponseInterceptor[0]); HttpService svc = new HttpService(requestProcess, mapper); try { while (!stopping.get()) { try (UnixSocket sock = socket.accept(100)) { if (sock == null) { // timeout during accept, try again continue; } // TODO tweak these properly sock.setSendBufferSize(65535); sock.setReceiveBufferSize(65535); if (stopping.get()) { // ignore IO errors on stop return; } try { DefaultBHttpServerConnection con = new DefaultBHttpServerConnection(65535); con.bind(sock); while (!sock.isClosed()) { try { svc.handleRequest(con, new BasicHttpContext()); } catch (HttpException e) { sock.close(); throw e; } } } catch (HttpException | IOException e) { System.err.println("FDK Got Exception while handling HTTP request" + e.getMessage()); e.printStackTrace(); // we continue here and leave the container hot } } catch (IOException e) { if (stopping.get()) { // ignore IO errors on stop return; } throw new FunctionIOException("failed to accept connection from platform, terminating", e); } } } finally { stopped.complete(true); } } private String getRequiredEnv(String name) { String val = env.get(name); if (val == null) { throw new FunctionInputHandlingException("Required environment variable " + name + " is not set - are you running a function outside of fn run?"); } return val; } private static String getRequiredHeader(HttpRequest request, String headerName) { Header header = request.getFirstHeader(headerName); if (header == null) { throw new FunctionInputHandlingException("Required FDK header variable " + headerName + " is not set, check you are using the latest fn and FDK versions"); } return header.getValue(); } private InputEvent readEvent(HttpRequest request) { InputStream bodyStream; if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) request; try { bodyStream = entityEnclosingRequest.getEntity().getContent(); } catch (IOException exception) { throw new FunctionInputHandlingException("error handling input", exception); } } else { bodyStream = EmptyInputStream.INSTANCE; } String deadline = getRequiredHeader(request, "Fn-Deadline"); String callID = getRequiredHeader(request, "Fn-Call-Id"); if (callID == null) { callID = ""; } Instant deadlineDate = Instant.now().plus(1, ChronoUnit.HOURS); if (deadline != null) { try { deadlineDate = Instant.parse(deadline); } catch (DateTimeParseException e) { throw new FunctionInputHandlingException("Invalid deadline date format", e); } } Headers headersIn = Headers.emptyHeaders(); for (Header h : request.getAllHeaders()) { if (stripInputHeaders.contains(Headers.canonicalKey(h.getName()))) { continue; } headersIn = headersIn.addHeader(h.getName(), h.getValue()); } return new ReadOnceInputEvent(bodyStream, headersIn, callID, deadlineDate); } private void writeEvent(OutputEvent evt, HttpResponse response) { evt.getHeaders().asMap() .entrySet() .stream() .filter(e -> !stripOutputHeaders.contains(e.getKey())) .flatMap(e -> e.getValue().stream().map((v) -> new BasicHeader(e.getKey(), v))) .forEachOrdered(response::addHeader); ContentType contentType = evt.getContentType().map(c -> { try { return ContentType.parse(c); } catch (ParseException e) { return ContentType.DEFAULT_BINARY; } }).orElse(ContentType.DEFAULT_BINARY); response.setHeader("Content-Type", contentType.toString()); response.setHeader("Fn-Fdk-Version", fdkVersion); response.setHeader("Fn-Fdk-Runtime", runtimeVersion); response.setStatusLine(new BasicStatusLine(HttpVersion.HTTP_1_1, evt.getStatus().getCode(), evt.getStatus().name())); ByteArrayOutputStream bos = new ByteArrayOutputStream(); // TODO remove output buffering here - possibly change OutputEvent contract to support providing an InputStream? try { evt.writeToOutput(bos); } catch (IOException e) { throw new FunctionOutputHandlingException("Error writing output", e); } byte[] data = bos.toByteArray(); response.setEntity(new ByteArrayEntity(data, contentType)); } @Override public void close() throws IOException { if (stopping.compareAndSet(false, true)) { socket.close(); try { stopped.get(); } catch (Exception ignored) { } socketFile.delete(); tempFile.delete(); } } }
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/main/java/com/fnproject/fn/runtime/FunctionConfigurer.java
runtime/src/main/java/com/fnproject/fn/runtime/FunctionConfigurer.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.FnConfiguration; import com.fnproject.fn.api.MethodWrapper; import com.fnproject.fn.api.exception.FunctionConfigurationException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Comparator; import java.util.Optional; /** * Loads function entry points based on their class name and method name creating a {@link FunctionRuntimeContext} */ public class FunctionConfigurer { /** * create a function runtime context for a given class and method name * * @param runtimeContext The runtime context encapsulating the function to be run */ public void configure(FunctionRuntimeContext runtimeContext) { validateConfigurationMethods(runtimeContext.getMethodWrapper()); applyUserConfigurationMethod(runtimeContext.getMethodWrapper(), runtimeContext); } private void validateConfigurationMethods(MethodWrapper function) { // Function configuration methods must have a void return type. Arrays.stream(function.getTargetClass().getMethods()) .filter(this::isConfigurationMethod) .filter((m) -> !m.getReturnType().equals(Void.TYPE)) .forEach((m) -> { throw new FunctionConfigurationException("Configuration method '" + m.getName() + "' does not have a void return type"); }); // If target method is static, configuration methods cannot be non-static. if (Modifier.isStatic(function.getTargetMethod().getModifiers())) { Arrays.stream(function.getTargetClass().getMethods()) .filter(this::isConfigurationMethod) .filter((m) -> !(Modifier.isStatic(m.getModifiers()))) .forEach((m) -> { throw new FunctionConfigurationException("Configuration method '" + m.getName() + "' cannot be an instance method if the function method is a static method"); }); } } private void applyUserConfigurationMethod(MethodWrapper targetClass, FunctionRuntimeContext runtimeContext) { Arrays.stream(targetClass.getTargetClass().getMethods()) .filter(this::isConfigurationMethod) .sorted(Comparator.<Method>comparingInt((m) -> Modifier.isStatic(m.getModifiers()) ? 0 : 1) // run static methods first .thenComparing(Comparator.<Method>comparingInt((m) -> { // depth first in implementation int depth = 0; Class<?> cc = m.getDeclaringClass(); while (null != cc) { depth++; cc = cc.getSuperclass(); } return depth; }))) .forEach(configMethod -> { try { Optional<Object> fnInstance = runtimeContext.getInvokeInstance(); // Allow the runtime context parameter to be optional if (configMethod.getParameterCount() == 0) { configMethod.invoke(fnInstance.orElse(null)); } else { configMethod.invoke(fnInstance.orElse(null), runtimeContext); } } catch ( InvocationTargetException e){ throw new FunctionConfigurationException("Error invoking configuration method: " + configMethod.getName(), e.getCause()); } catch (IllegalAccessException e) { throw new FunctionConfigurationException("Error invoking configuration method: " + configMethod.getName(), e); } }); } private boolean isConfigurationMethod(Method m) { return m.getDeclaredAnnotationsByType(FnConfiguration.class).length > 0 && !m.getDeclaringClass().isInterface(); } }
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/main/java/com/fnproject/fn/runtime/DefaultMethodWrapper.java
runtime/src/main/java/com/fnproject/fn/runtime/DefaultMethodWrapper.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 com.fnproject.fn.api.TypeWrapper; import java.lang.reflect.Method; import java.util.Arrays; /** * Wrapper class around {@link java.lang.reflect.Method} to provide type * resolution for methods with generic arguments */ public class DefaultMethodWrapper implements MethodWrapper { private final Class<?> srcClass; private final Method srcMethod; public DefaultMethodWrapper(Class<?> srcClass, Method srcMethod) { this.srcClass = srcClass; this.srcMethod = srcMethod; } public DefaultMethodWrapper(Class<?> srcClass, String srcMethod) { this(srcClass, Arrays.stream(srcClass.getMethods()) .filter((m) -> m.getName().equals(srcMethod)) .findFirst() .orElseThrow(() -> new RuntimeException(new NoSuchMethodException(srcClass.getCanonicalName() + "::" + srcMethod)))); } @Override public Class<?> getTargetClass() { return srcClass; } @Override public Method getTargetMethod() { return srcMethod; } @Override public TypeWrapper getParamType(int index) { return MethodTypeWrapper.fromParameter(this, index); } @Override public TypeWrapper getReturnType() { return MethodTypeWrapper.fromReturnType(this); } @Override public String toString() { return getLongName(); } }
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/main/java/com/fnproject/fn/runtime/FunctionLoader.java
runtime/src/main/java/com/fnproject/fn/runtime/FunctionLoader.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 com.fnproject.fn.runtime.exception.InvalidFunctionDefinitionException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class FunctionLoader { private static ClassLoader contextClassLoader = FunctionLoader.class.getClassLoader(); /** * create a function runtime context for a given class and method name * * @param className the class name to load * @param fnName the function in the class * @return a new runtime context */ public MethodWrapper loadClass(String className, String fnName) { Class<?> targetClass = loadClass(className); return new DefaultMethodWrapper(targetClass, getTargetMethod(targetClass, fnName)); } private Method getTargetMethod(Class<?> targetClass, String method) { List<Method> namedMethods = findMethodsByName(method, targetClass); if (namedMethods.isEmpty()) { String names = Arrays.stream(targetClass.getDeclaredMethods()) .filter((m) -> !m.getDeclaringClass().equals(Object.class)) .map(Method::getName) .filter((name) -> !name.startsWith("$")) .reduce((x, y) -> (x + "," + y)).orElseGet(() -> ""); throw new InvalidFunctionDefinitionException("Method '" + method + "' was not found " + "in class '" + targetClass.getCanonicalName() + "'. Available functions were: [" + names + "]"); } if (namedMethods.size() > 1) { throw new InvalidFunctionDefinitionException("Multiple methods match name " + method + " in " + targetClass.getCanonicalName() + " matching methods were [" + namedMethods.stream().map(Object::toString).collect(Collectors.joining(","))); } return namedMethods.get(0); } private List<Method> findMethodsByName(String fnName, Class<?> fnClass) { return Arrays.stream(fnClass.getMethods()) .filter((m) -> !m.getDeclaringClass().equals(Object.class)) .filter(m -> fnName.equals(m.getName())) .filter(m -> !m.isBridge()) .collect(Collectors.toList()); } private Class<?> loadClass(String className) { Class<?> fnClass; try { fnClass = Class.forName(className); } catch (ClassNotFoundException e) { throw new InvalidFunctionDefinitionException(String.format("Class '%s' not found in function jar. " + "It's likely that the 'cmd' entry in func.yaml is incorrect.", className)); } return fnClass; } /** * Override the classloader used for fn class resolution * Primarily for testing, otherwise the system/default classloader is used. * * @param loader the context class loader to use for this function */ public static void setContextClassLoader(ClassLoader loader) { contextClassLoader = loader; } }
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/main/java/com/fnproject/fn/runtime/tracing/OCITracingContext.java
runtime/src/main/java/com/fnproject/fn/runtime/tracing/OCITracingContext.java
package com.fnproject.fn.runtime.tracing; import com.fnproject.fn.api.Headers; import com.fnproject.fn.api.InvocationContext; import com.fnproject.fn.api.RuntimeContext; import com.fnproject.fn.api.tracing.TracingContext; public class OCITracingContext implements TracingContext { private final InvocationContext invocationContext; private final RuntimeContext runtimeContext; private String traceCollectorURL; private String traceId; private String spanId; private String parentSpanId; private Boolean sampled = true; private String flags; private Boolean tracingEnabled; private String appName; private String fnName; private static final String PLACEHOLDER_TRACE_COLLECTOR_URL = "http://localhost:9411/api/v2/span"; private static final String PLACEHOLDER_TRACE_ID = "1"; public OCITracingContext(InvocationContext invocationContext, RuntimeContext runtimeContext) { this.invocationContext = invocationContext; this.runtimeContext = runtimeContext; configureDefaultValue(); configure(runtimeContext); if(tracingEnabled) configure(invocationContext.getRequestHeaders()); } private void configureDefaultValue() { this.traceCollectorURL = PLACEHOLDER_TRACE_COLLECTOR_URL; this.traceId = PLACEHOLDER_TRACE_ID; this.spanId = PLACEHOLDER_TRACE_ID; this.parentSpanId = PLACEHOLDER_TRACE_ID; } private void configure(RuntimeContext runtimeContext) { if(runtimeContext != null && runtimeContext.getConfigurationByKey("OCI_TRACE_COLLECTOR_URL").get() != null && runtimeContext.getConfigurationByKey("OCI_TRACING_ENABLED").get() != null) { this.traceCollectorURL = runtimeContext.getConfigurationByKey("OCI_TRACE_COLLECTOR_URL").get().isEmpty() ?PLACEHOLDER_TRACE_COLLECTOR_URL :runtimeContext.getConfigurationByKey("OCI_TRACE_COLLECTOR_URL").get(); try { Integer tracingEnabledAsInt = Integer.parseInt(runtimeContext.getConfigurationByKey("OCI_TRACING_ENABLED").get()); this.tracingEnabled = tracingEnabledAsInt != 0; } catch(java.lang.NumberFormatException ex) { this.tracingEnabled = false; } this.appName = runtimeContext.getAppName(); this.fnName = runtimeContext.getFunctionName(); } } private void configure(Headers headers) { this.flags = headers.get("x-b3-flags").orElse(""); if (headers.get("x-b3-sampled").isPresent() && Integer.parseInt(headers.get("x-b3-sampled").get()) == 0) { this.sampled = false; return; } this.sampled = true; this.traceId = headers.get("x-b3-traceid").orElse(PLACEHOLDER_TRACE_ID); this.spanId = headers.get("x-b3-spanid").orElse(PLACEHOLDER_TRACE_ID); this.parentSpanId = headers.get("x-b3-parentspanid").orElse(PLACEHOLDER_TRACE_ID); } @Override public InvocationContext getInvocationContext() { return invocationContext; } @Override public RuntimeContext getRuntimeContext() { return runtimeContext; } @Override public String getServiceName() { return this.appName.toLowerCase() + "::" + this.fnName.toLowerCase(); } @Override public String getTraceCollectorURL() { return traceCollectorURL; } @Override public String getTraceId() { return traceId; } @Override public String getSpanId() { return spanId; } @Override public String getParentSpanId() { return parentSpanId; } @Override public Boolean isSampled() { return sampled; } @Override public String getFlags() { return flags; } @Override public Boolean isTracingEnabled() { return tracingEnabled; } @Override public String getAppName() { return appName; } @Override public String getFunctionName() { return fnName; } }
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/main/java/com/fnproject/fn/runtime/exception/FunctionClassInstantiationException.java
runtime/src/main/java/com/fnproject/fn/runtime/exception/FunctionClassInstantiationException.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.exception; import com.fnproject.fn.api.exception.FunctionLoadException; public class FunctionClassInstantiationException extends FunctionLoadException { public FunctionClassInstantiationException(String message, Throwable cause) { super(message, cause); } public FunctionClassInstantiationException(String s) { super(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/main/java/com/fnproject/fn/runtime/exception/InvalidFunctionDefinitionException.java
runtime/src/main/java/com/fnproject/fn/runtime/exception/InvalidFunctionDefinitionException.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.exception; import com.fnproject.fn.api.exception.FunctionLoadException; /** * the function definition passed was invalid (e.g. class or method did not exist in jar, or method did not match required signature) */ public class InvalidFunctionDefinitionException extends FunctionLoadException { public InvalidFunctionDefinitionException(String message, Throwable cause) { super(message, cause); } public InvalidFunctionDefinitionException(String message) { super(message); } }
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/main/java/com/fnproject/fn/runtime/exception/FunctionInitializationException.java
runtime/src/main/java/com/fnproject/fn/runtime/exception/FunctionInitializationException.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.exception; /** * The FDK was not able to start up */ public final class FunctionInitializationException extends RuntimeException { /** * create a function invocation exception * * @param message private message for this exception - * @param target the underlying user exception that triggered this failure */ public FunctionInitializationException(String message, Throwable target) { super(message, target); } public FunctionInitializationException(String message) { super(message); } }
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/main/java/com/fnproject/fn/runtime/exception/InvalidEntryPointException.java
runtime/src/main/java/com/fnproject/fn/runtime/exception/InvalidEntryPointException.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.exception; import com.fnproject.fn.api.exception.FunctionLoadException; /** * The function entry point spec was malformed. */ public class InvalidEntryPointException extends FunctionLoadException { public InvalidEntryPointException(String msg) { super(msg); } public InvalidEntryPointException(String msg, Throwable e) { super(msg, e); } }
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/main/java/com/fnproject/fn/runtime/exception/PlatformCommunicationException.java
runtime/src/main/java/com/fnproject/fn/runtime/exception/PlatformCommunicationException.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.exception; /** * An error occurred in the */ public class PlatformCommunicationException extends RuntimeException { public PlatformCommunicationException(String message) { super(message); } public PlatformCommunicationException(String message, Exception e) { super(message, e); } }
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/main/java/com/fnproject/fn/runtime/exception/InternalFunctionInvocationException.java
runtime/src/main/java/com/fnproject/fn/runtime/exception/InternalFunctionInvocationException.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.exception; import com.fnproject.fn.api.OutputEvent; /** * The user's code caused an exception - this carries an elided stack trace of the error with respect to only the user's code. */ public final class InternalFunctionInvocationException extends RuntimeException { private final Throwable cause; private final OutputEvent event; /** * create a function invocation exception * * @param message private message for this exception - * @param target the underlying user exception that triggered this failure */ public InternalFunctionInvocationException(String message, Throwable target) { super(message); this.cause = target; this.event = OutputEvent.fromBytes(new byte[0], OutputEvent.Status.FunctionError, null); } /** * create a function invocation exception * * @param message private message for this exception - * @param target the underlying user exception that triggered this failure * @param event the output event */ public InternalFunctionInvocationException(String message, Throwable target, OutputEvent event) { super(message); this.cause = target; this.event = event; } @Override public Throwable getCause() { return cause; } /** * map this exception to an output event * @return the output event associated with this exception */ public OutputEvent toOutput() { return event; } }
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/main/java/com/fnproject/fn/runtime/exception/FunctionIOException.java
runtime/src/main/java/com/fnproject/fn/runtime/exception/FunctionIOException.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.exception; /** * The FDK experienced a terminal issue communicating with the platform */ public final class FunctionIOException extends RuntimeException { /** * create a function invocation exception * * @param message private message for this exception - * @param target the underlying user exception that triggered this failure */ public FunctionIOException(String message, Throwable target) { super(message, target); } }
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/main/java/com/fnproject/fn/runtime/ntv/UnixSocketException.java
runtime/src/main/java/com/fnproject/fn/runtime/ntv/UnixSocketException.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.ntv; import java.net.SocketException; /** * Created on 12/09/2018. * <p> * (c) 2018 Oracle Corporation */ public class UnixSocketException extends SocketException { public UnixSocketException(String message, String detail) { super(message + ":" + detail); } public UnixSocketException(String message) { super(message); } }
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/main/java/com/fnproject/fn/runtime/ntv/UnixSocket.java
runtime/src/main/java/com/fnproject/fn/runtime/ntv/UnixSocket.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.ntv; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.*; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; /** * This approximates a Java.net.socket for many operations but not by any means all * Created on 12/09/2018. * <p> * (c) 2018 Oracle Corporation */ public final class UnixSocket extends Socket { // Fall back to WTF for most unsupported operations private static final SocketImpl fakeSocketImpl = new SocketImpl() { @Override protected void create(boolean stream) throws IOException { throw new UnsupportedOperationException(); } @Override protected void connect(String host, int port) throws IOException { throw new UnsupportedOperationException(); } @Override protected void connect(InetAddress address, int port) throws IOException { throw new UnsupportedOperationException(); } @Override protected void connect(SocketAddress address, int timeout) throws IOException { throw new UnsupportedOperationException(); } @Override protected void bind(InetAddress host, int port) throws IOException { throw new UnsupportedOperationException(); } @Override protected void listen(int backlog) throws IOException { throw new UnsupportedOperationException(); } @Override protected void accept(SocketImpl s) throws IOException { throw new UnsupportedOperationException(); } @Override protected InputStream getInputStream() throws IOException { throw new UnsupportedOperationException(); } @Override protected OutputStream getOutputStream() throws IOException { throw new UnsupportedOperationException(); } @Override protected int available() throws IOException { throw new UnsupportedOperationException(); } @Override protected void close() throws IOException { throw new UnsupportedOperationException(); } @Override protected void sendUrgentData(int data) throws IOException { throw new UnsupportedOperationException(); } @Override public void setOption(int optID, Object value) throws SocketException { throw new UnsupportedOperationException(); } @Override public Object getOption(int optID) throws SocketException { throw new UnsupportedOperationException(); } }; private final int fd; private final AtomicBoolean closed = new AtomicBoolean(); private final AtomicBoolean inputClosed = new AtomicBoolean(); private final AtomicBoolean outputClosed = new AtomicBoolean(); private final InputStream in; private final OutputStream out; UnixSocket(int fd) throws SocketException { super(fakeSocketImpl); this.fd = fd; in = new UsInput(); out = new UsOutput(); } private class UsInput extends InputStream { @Override public int read() throws IOException { byte[] buf = new byte[1]; int rv = read(buf, 0, 1); if (rv == -1) { return -1; } return (int) buf[0]; } public int read(byte b[]) throws IOException { return this.read(b, 0, b.length); } @Override public int read(byte b[], int off, int len) throws IOException { if (inputClosed.get()) { throw new UnixSocketException("Read on closed stream"); } return UnixSocketNative.recv(fd, b, off, len); } @Override public void close() throws IOException { shutdownInput(); } } private class UsOutput extends OutputStream { @Override public void write(int b) throws IOException { write(new byte[]{(byte) b}, 0, 1); } public void write(byte b[], int off, int len) throws IOException { if (outputClosed.get()) { throw new UnixSocketException("Write to closed stream"); } Objects.requireNonNull(b); while (len > 0) { int sent = UnixSocketNative.send(fd, b, off, len); if (sent == 0) { throw new UnixSocketException("No data written to buffer"); } off = off + sent; len = len - sent; } } @Override public void close() throws IOException { shutdownOutput(); } } public static UnixSocket connect(String destination) throws IOException { int fd = UnixSocketNative.socket(); UnixSocketNative.connect(fd, destination); return new UnixSocket(fd); } @Override public InputStream getInputStream() { return in; } @Override public OutputStream getOutputStream() { return out; } @Override public synchronized void setReceiveBufferSize(int size) throws SocketException { UnixSocketNative.setRecvBufSize(fd, size); } @Override public synchronized void setSendBufferSize(int size) throws SocketException { UnixSocketNative.setSendBufSize(fd, size); } @Override public void setSoTimeout(int timeout) throws SocketException { UnixSocketNative.setRecvTimeout(fd, timeout); } @Override public int getSoTimeout() throws SocketException { return UnixSocketNative.getRecvTimeout(fd); } @Override public void connect(SocketAddress endpoint) throws IOException { throw new UnsupportedOperationException(); } @Override public void connect(SocketAddress endpoint, int timeout) throws IOException { throw new UnsupportedOperationException(); } @Override public void bind(SocketAddress bindpoint) throws IOException { throw new UnsupportedOperationException(); } @Override public InetAddress getInetAddress() { return null; } @Override public InetAddress getLocalAddress() { throw new UnsupportedOperationException(); } @Override public int getPort() { return 0; } @Override public int getLocalPort() { return -1; } @Override public SocketAddress getRemoteSocketAddress() { return null; } @Override public SocketAddress getLocalSocketAddress() { return null; } @Override public boolean isConnected() { return true; } @Override public boolean isBound() { return true; } @Override public boolean isClosed() { return closed.get(); } @Override public boolean isInputShutdown() { return inputClosed.get(); } @Override public boolean isOutputShutdown() { return outputClosed.get(); } @Override public void shutdownInput() throws IOException { if (inputClosed.compareAndSet(false, true)) { UnixSocketNative.shutdown(fd, true, false); } else { throw new SocketException("Input already shut down"); } } @Override public void shutdownOutput() throws IOException { if (outputClosed.compareAndSet(false, true)) { UnixSocketNative.shutdown(fd, false, true); } else { throw new SocketException("Output already shut down"); } } @Override public void close() throws IOException { if (closed.compareAndSet(false, true)) { UnixSocketNative.close(fd); } } }
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/main/java/com/fnproject/fn/runtime/ntv/UnixSocketNative.java
runtime/src/main/java/com/fnproject/fn/runtime/ntv/UnixSocketNative.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.ntv; import java.io.IOException; /** * Created on 12/09/2018. * <p> * (c) 2018 Oracle Corporation */ class UnixSocketNative { public UnixSocketNative() {} static { String lib = System.mapLibraryName("fnunixsocket"); String libLocation = System.getProperty("com.fnproject.java.native.libdir"); if (libLocation != null) { if (!libLocation.endsWith("/")) { libLocation = libLocation + "/"; } lib = libLocation + lib; System.load(lib); }else{ System.loadLibrary("fnunixsocket"); } } public static native int socket() throws IOException; public static native void bind(int socket, String path) throws UnixSocketException; public static native void connect(int socket, String path) throws IOException; public static native void listen(int socket, int backlog) throws UnixSocketException; public static native int accept(int socket, long timeoutMs) throws IOException; public static native int recv(int socket, byte[] buffer, int offset, int length) throws IOException; public static native int send(int socket, byte[] buffer, int offset, int length) throws IOException; public static native void close(int socket) throws UnixSocketException; public static native void setSendTimeout(int socket, int timeout) throws UnixSocketException; public static native int getSendTimeout(int socket) throws IOException; public static native void setRecvTimeout(int socket, int timeout) throws UnixSocketException; public static native int getRecvTimeout(int socket) throws UnixSocketException; public static native void setSendBufSize(int socket, int bufSize) throws UnixSocketException; public static native void setRecvBufSize(int socket, int bufSize) throws UnixSocketException; public static native void shutdown(int socket, boolean input, boolean output) throws UnixSocketException; }
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/main/java/com/fnproject/fn/runtime/ntv/UnixServerSocket.java
runtime/src/main/java/com/fnproject/fn/runtime/ntv/UnixServerSocket.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.ntv; import java.io.Closeable; import java.io.IOException; import java.net.SocketException; import java.util.concurrent.atomic.AtomicBoolean; /** * Created on 12/09/2018. * <p> * (c) 2018 Oracle Corporation */ public class UnixServerSocket implements Closeable { private final int fd; private final AtomicBoolean closed = new AtomicBoolean(); private UnixServerSocket(int fd) { this.fd = fd; } public static UnixServerSocket listen(String fileName, int backlog) throws IOException { int fd = UnixSocketNative.socket(); try { UnixSocketNative.bind(fd, fileName); } catch (UnixSocketException e) { UnixSocketNative.close(fd); throw e; } try { UnixSocketNative.listen(fd, backlog); } catch (UnixSocketException e) { UnixSocketNative.close(fd); throw e; } return new UnixServerSocket(fd); } @Override public void close() throws IOException { if (closed.compareAndSet(false,true)) { UnixSocketNative.close(fd); } } public UnixSocket accept(long timeoutMillis) throws IOException { if (closed.get()) { throw new SocketException("accept on closed socket"); } int newFd = UnixSocketNative.accept(fd, timeoutMillis); if (newFd == 0) { return null; } return new UnixSocket(newFd); } }
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/main/java/com/fnproject/fn/runtime/coercion/InputEventCoercion.java
runtime/src/main/java/com/fnproject/fn/runtime/coercion/InputEventCoercion.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.coercion; 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 java.util.Optional; public class InputEventCoercion implements InputCoercion<InputEvent> { @Override public Optional<InputEvent> tryCoerceParam(InvocationContext currentContext, int arg, InputEvent input, MethodWrapper method) { if (method.getParamType(arg).getParameterClass().equals(InputEvent.class)) { return Optional.of(input); } else { return Optional.empty(); } } }
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/main/java/com/fnproject/fn/runtime/coercion/VoidCoercion.java
runtime/src/main/java/com/fnproject/fn/runtime/coercion/VoidCoercion.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.coercion; 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 java.util.Optional; public class VoidCoercion implements OutputCoercion { @Override public Optional<OutputEvent> wrapFunctionResult(InvocationContext ctx, MethodWrapper method, Object value) { if (method.getReturnType().getParameterClass().equals(Void.class)) { return Optional.of(OutputEvent.emptyResult(OutputEvent.Status.Success)); } else { return Optional.empty(); } } }
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/main/java/com/fnproject/fn/runtime/coercion/StringCoercion.java
runtime/src/main/java/com/fnproject/fn/runtime/coercion/StringCoercion.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.coercion; import com.fnproject.fn.api.*; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Optional; public class StringCoercion implements InputCoercion<String>, OutputCoercion { @Override public Optional<OutputEvent> wrapFunctionResult(InvocationContext ctx, MethodWrapper method, Object value) { if (method.getReturnType().getParameterClass().equals(String.class)) { return Optional.of(OutputEvent.fromBytes(((String) value).getBytes(), OutputEvent.Status.Success, "text/plain")); } else { return Optional.empty(); } } @Override public Optional<String> tryCoerceParam(InvocationContext currentContext, int param, InputEvent input, MethodWrapper method) { if (method.getParamType(param).getParameterClass().equals(String.class)) { return Optional.of( input.consumeBody(is -> { try { return IOUtils.toString(is, StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException("Error reading input as string"); } })); } else { return Optional.empty(); } } }
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/main/java/com/fnproject/fn/runtime/coercion/ContextCoercion.java
runtime/src/main/java/com/fnproject/fn/runtime/coercion/ContextCoercion.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.coercion; import com.fnproject.fn.api.*; import com.fnproject.fn.api.httpgateway.HTTPGatewayContext; import com.fnproject.fn.api.tracing.TracingContext; import com.fnproject.fn.runtime.httpgateway.FunctionHTTPGatewayContext; import com.fnproject.fn.runtime.tracing.OCITracingContext; import java.util.Optional; /** * Handles coercion to build in context objects ({@link RuntimeContext}, {@link InvocationContext} , {@link HTTPGatewayContext}) */ public class ContextCoercion implements InputCoercion<Object> { @Override public Optional<Object> tryCoerceParam(InvocationContext currentContext, int arg, InputEvent input, MethodWrapper method) { Class<?> paramClass = method.getParamType(arg).getParameterClass(); if (paramClass.equals(RuntimeContext.class)) { return Optional.of(currentContext.getRuntimeContext()); } else if (paramClass.equals(InvocationContext.class)) { return Optional.of(currentContext); } else if (paramClass.equals(HTTPGatewayContext.class)) { return Optional.of(new FunctionHTTPGatewayContext(currentContext)); } else if (paramClass.equals(TracingContext.class)) { return Optional.of(new OCITracingContext(currentContext, currentContext.getRuntimeContext())); } else { return Optional.empty(); } } }
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/main/java/com/fnproject/fn/runtime/coercion/ByteArrayCoercion.java
runtime/src/main/java/com/fnproject/fn/runtime/coercion/ByteArrayCoercion.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.coercion; import com.fnproject.fn.api.*; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Optional; /** * Handles coercion to and from byte arrays. */ public class ByteArrayCoercion implements InputCoercion<byte[]>, OutputCoercion { public Optional<OutputEvent> wrapFunctionResult(InvocationContext ctx, MethodWrapper method, Object value) { if (method.getReturnType().getParameterClass().equals(byte[].class)) { return Optional.of(OutputEvent.fromBytes(((byte[]) value), OutputEvent.Status.Success, "application/octet-stream")); } else { return Optional.empty(); } } private byte[] toByteArray(InputStream is) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[1024]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toByteArray(); } @Override public Optional<byte[]> tryCoerceParam(InvocationContext currentContext, int arg, InputEvent input, MethodWrapper method) { if (method.getParamType(arg).getParameterClass().equals(byte[].class)) { return Optional.of( input.consumeBody(is -> { try { return toByteArray(is); } catch (IOException e) { throw new RuntimeException("Error reading input as bytes", e); } })); } else { return Optional.empty(); } } }
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/main/java/com/fnproject/fn/runtime/coercion/OutputEventCoercion.java
runtime/src/main/java/com/fnproject/fn/runtime/coercion/OutputEventCoercion.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.coercion; 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 java.util.Optional; public class OutputEventCoercion implements OutputCoercion { @Override public Optional<OutputEvent> wrapFunctionResult(InvocationContext ctx, MethodWrapper method, Object value) { if (method.getReturnType().getParameterClass().equals(OutputEvent.class)) { return Optional.of((OutputEvent) value); } else { return Optional.empty(); } } }
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/main/java/com/fnproject/fn/runtime/coercion/jackson/JacksonCoercion.java
runtime/src/main/java/com/fnproject/fn/runtime/coercion/jackson/JacksonCoercion.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.coercion.jackson; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fnproject.fn.api.*; import java.io.IOException; import java.lang.reflect.Type; import java.util.Optional; /** * Jackson JSON Serialization feature - * <p> * This supports marshalling and unmarshalling of event parameters and responses to */ public class JacksonCoercion implements InputCoercion<Object>, OutputCoercion { private static final String OM_KEY = JacksonCoercion.class.getCanonicalName() + ".om"; private static final JacksonCoercion instance = new JacksonCoercion(); /** * Return the global instance of this coercion * @return a singleton instance of the JSON coercion for the VM */ public static JacksonCoercion 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<Object> tryCoerceParam(InvocationContext currentContext, int param, InputEvent input, MethodWrapper method) { Type type = method.getTargetMethod().getGenericParameterTypes()[param]; JavaType javaType = objectMapper(currentContext).constructType(type); return Optional.ofNullable(input.consumeBody(inputStream -> { try { return objectMapper(currentContext).readValue(inputStream, javaType); } catch (IOException e) { throw coercionFailed(type, e); } })); } private static RuntimeException coercionFailed(Type paramType, Throwable cause) { return new RuntimeException("Failed to coerce event to user function parameter type " + paramType, cause); } private static RuntimeException coercionFailed(Type paramType) { return coercionFailed(paramType, null); } @Override public Optional<OutputEvent> wrapFunctionResult(InvocationContext ctx, MethodWrapper method, Object value) { try { return Optional.of(OutputEvent.fromBytes(objectMapper(ctx).writeValueAsBytes(value), OutputEvent.Status.Success, "application/json")); } catch (JsonProcessingException e) { throw new RuntimeException("Failed to render response 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/runtime/src/main/java/com/fnproject/fn/runtime/httpgateway/QueryParametersParser.java
runtime/src/main/java/com/fnproject/fn/runtime/httpgateway/QueryParametersParser.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.httpgateway; import com.fnproject.fn.api.QueryParameters; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.*; import java.util.Map.Entry; import java.util.stream.Collectors; import static java.util.stream.Collectors.mapping; import static java.util.stream.Collectors.toList; public class QueryParametersParser { public static QueryParameters getParams(String url) { int beginIndex = url.indexOf("?"); if (beginIndex < 0) { return new QueryParametersImpl(); } String queryParameters = url.substring(beginIndex + 1); return new QueryParametersImpl(parseQueryParameters(queryParameters)); } private static Map<String, List<String>> parseQueryParameters(String queryParameters) { if (queryParameters == null || "".equals(queryParameters)) { return Collections.emptyMap(); } return Arrays.stream(queryParameters.split("[&;]")) .map(QueryParametersParser::splitQueryParameter) .collect(Collectors.groupingBy(Entry::getKey, LinkedHashMap::new, mapping(Entry::getValue, toList()))); } private static Entry<String, String> splitQueryParameter(String parameter) { final int idx = parameter.indexOf("="); final String key = decode(idx > 0 ? parameter.substring(0, idx) : parameter); final String value = idx > 0 && parameter.length() > idx + 1 ? decode(parameter.substring(idx + 1)) : ""; return new SimpleImmutableEntry<>(key, value); } private static String decode(String urlEncodedString) { try { return URLDecoder.decode(urlEncodedString, "utf-8"); } catch (UnsupportedEncodingException e) { throw new Error("No utf-8 support in underlying platform", e); } } }
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/main/java/com/fnproject/fn/runtime/httpgateway/FunctionHTTPGatewayContext.java
runtime/src/main/java/com/fnproject/fn/runtime/httpgateway/FunctionHTTPGatewayContext.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.httpgateway; import com.fnproject.fn.api.Headers; import com.fnproject.fn.api.InvocationContext; import com.fnproject.fn.api.OutputEvent; import com.fnproject.fn.api.QueryParameters; import com.fnproject.fn.api.httpgateway.HTTPGatewayContext; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; /** * Created on 19/09/2018. * <p> * (c) 2018 Oracle Corporation */ public class FunctionHTTPGatewayContext implements HTTPGatewayContext { private final InvocationContext invocationContext; private final Headers httpRequestHeaders; private final String method; private final String requestUrl; private final QueryParameters queryParameters; public FunctionHTTPGatewayContext(InvocationContext invocationContext) { this.invocationContext = Objects.requireNonNull(invocationContext, "invocationContext"); Map<String, List<String>> myHeaders = new HashMap<>(); String requestUri = ""; String method = ""; for (Map.Entry<String, List<String>> e : invocationContext.getRequestHeaders().asMap().entrySet()) { String key = e.getKey(); if (key.startsWith("Fn-Http-H-")) { String httpKey = key.substring("Fn-Http-H-".length()); if (httpKey.length() > 0) { myHeaders.put(httpKey, e.getValue()); } } if (key.equals("Fn-Http-Request-Url")) { requestUri = e.getValue().get(0); } if (key.equals("Fn-Http-Method")) { method = e.getValue().get(0); } } this.queryParameters = QueryParametersParser.getParams(requestUri); this.requestUrl = requestUri; this.method = method; this.httpRequestHeaders = Headers.emptyHeaders().setHeaders(myHeaders); } @Override public InvocationContext getInvocationContext() { return invocationContext; } @Override public Headers getHeaders() { return httpRequestHeaders; } @Override public String getRequestURL() { return requestUrl; } @Override public String getMethod() { return method; } @Override public QueryParameters getQueryParameters() { return queryParameters; } @Override public void addResponseHeader(String key, String value) { invocationContext.addResponseHeader("Fn-Http-H-" + key, value); } public void addResponseHeader(String key, List<String> values) { if (values == null || values.isEmpty()) { setResponseHeader(key, null); } else { for (String value : values) { addResponseHeader(key, value); } } } @Override public void setResponseHeader(String key, String value, String... vs) { if (Headers.canonicalKey(key).equals(OutputEvent.CONTENT_TYPE_HEADER)) { invocationContext.setResponseContentType(value); invocationContext.setResponseHeader("Fn-Http-H-" + key, value); } else { invocationContext.setResponseHeader("Fn-Http-H-" + key, value, vs); } } @Override public void setStatusCode(int code) { if (code < 100 || code >= 600) { throw new IllegalArgumentException("Invalid HTTP status code: " + code); } invocationContext.setResponseHeader("Fn-Http-Status", "" + code); } }
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/main/java/com/fnproject/fn/runtime/httpgateway/QueryParametersImpl.java
runtime/src/main/java/com/fnproject/fn/runtime/httpgateway/QueryParametersImpl.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.httpgateway; import com.fnproject.fn.api.QueryParameters; import java.io.Serializable; import java.util.*; public class QueryParametersImpl implements QueryParameters, Serializable { private final Map<String, List<String>> params; public QueryParametersImpl() { this.params = new HashMap<>(); } public QueryParametersImpl(Map<String, List<String>> params) { this.params = Objects.requireNonNull(params); } public Optional<String> get(String key) { Objects.requireNonNull(key); return Optional.of(getValues(key)) .filter((values) -> values.size() > 0) .flatMap((values) -> Optional.ofNullable(values.get(0))); } public List<String> getValues(String key) { Objects.requireNonNull(key); List<String> values = this.params.get(key); if (values == null) { return Collections.emptyList(); } return values; } public int size() { return params.size(); } @Override public Map<String, List<String>> getAll() { return new HashMap<>(params); } }
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/main/java-filtered/com/fnproject/fn/runtime/Version.java
runtime/src/main/java-filtered/com/fnproject/fn/runtime/Version.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; /** * This uses maven-resource filtering rather than conventional manifest versioning as it's more robust against resource changes than using standard META-INF/MANIFEST.MF * versioning. For native image functions this negates the need for extra configuration to include manifest resources. * * Created on 18/02/2020. * <p> * * (c) 2020 Oracle Corporation */ public class Version { public static final String FDK_VERSION="${project.version}"; }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/testing-core/src/main/java/com/fnproject/fn/testing/FnHttpEventBuilder.java
testing-core/src/main/java/com/fnproject/fn/testing/FnHttpEventBuilder.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.runtime.ReadOnceInputEvent; import org.apache.commons.io.IOUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Map; import java.util.Objects; public class FnHttpEventBuilder { private byte[] bodyBytes = new byte[0]; private Headers headers = Headers.emptyHeaders(); private Instant deadline = Instant.now().plus(1, ChronoUnit.HOURS); public FnHttpEventBuilder withHeader(String key, String value) { Objects.requireNonNull(key, "key"); Objects.requireNonNull(value, "value"); headers = headers.addHeader(key, value); return this; } public FnHttpEventBuilder withBody(InputStream body) throws IOException { Objects.requireNonNull(body, "body"); this.bodyBytes = IOUtils.toByteArray(body); return this; } public FnHttpEventBuilder withBody(byte[] body) { Objects.requireNonNull(body, "body"); this.bodyBytes = body; return this; } public FnHttpEventBuilder withBody(String body) { byte stringAsBytes[] = Objects.requireNonNull(body, "body").getBytes(); return withBody(stringAsBytes); } public FnHttpEventBuilder withHeaders(Map<String, String> headers) { Headers h = this.headers; for (Map.Entry<String, String> he : headers.entrySet()) { h = h.setHeader(he.getKey(), he.getValue()); } this.headers = h; return this; } public InputEvent buildEvent() { return new ReadOnceInputEvent(new ByteArrayInputStream(bodyBytes), headers, "callId", deadline); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/testing-core/src/main/java/com/fnproject/fn/testing/PlatformError.java
testing-core/src/main/java/com/fnproject/fn/testing/PlatformError.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; /** * An Exception that can be used in invocations of stubbed external functions to signal the failure of the external * function due to a simulated infrastructure error in the Oracle Functions platform */ public class PlatformError extends Exception { public PlatformError() { } public PlatformError(String s) { super(s); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/testing-core/src/main/java/com/fnproject/fn/testing/FnTestingClassLoader.java
testing-core/src/main/java/com/fnproject/fn/testing/FnTestingClassLoader.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.runtime.EntryPoint; import com.fnproject.fn.runtime.EventCodec; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Testing classloader that loads all classes afresh when needed, otherwise delegates shared classes to the parent classloader */ public class FnTestingClassLoader extends ClassLoader { private final List<String> sharedPrefixes; private final Map<String, Class<?>> loaded = new HashMap<>(); public FnTestingClassLoader(ClassLoader parent, List<String> sharedPrefixes) { super(parent); this.sharedPrefixes = sharedPrefixes; } boolean isShared(String classOrPackageName) { for (String prefix : sharedPrefixes) { if (("=" + classOrPackageName).equals(prefix) || classOrPackageName.startsWith(prefix)) { return true; } } return false; } @Override public synchronized Class<?> loadClass(String className) throws ClassNotFoundException { Class<?> definedClass = loaded.get(className); if (definedClass != null) { return definedClass; } Class<?> cls = null; if (isShared(className)) { cls = getParent().loadClass(className); } if (cls == null) { try { InputStream in = getResourceAsStream(className.replace('.', '/') + ".class"); if (in == null) { throw new ClassNotFoundException("Class not found :" + className); } byte[] clsBytes = IOUtils.toByteArray(in); cls = defineClass(className, clsBytes, 0, clsBytes.length); resolveClass(cls); } catch (IOException e) { throw new ClassNotFoundException(className, e); } } loaded.put(className, cls); return cls; } public int run(Map<String, String> mutableEnv, EventCodec codec, PrintStream functionErr, String... s) { ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this); Class<?> entryPoint_class = loadClass(EntryPoint.class.getName()); Object entryPoint = entryPoint_class.newInstance(); return (int) getMethodInClassLoader(entryPoint, "run", Map.class, EventCodec.class, PrintStream.class, String[].class) .invoke(entryPoint, mutableEnv, codec, functionErr, s); } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException | IllegalArgumentException e) { throw new RuntimeException("Something broke in the reflective classloader", e); } finally { Thread.currentThread().setContextClassLoader(currentClassLoader); } } private Method getMethodInClassLoader(Object target, String method, Class... types) throws NoSuchMethodException { Class<?> targetClass; if (target instanceof Class) { targetClass = (Class) target; } else { targetClass = target.getClass(); } return targetClass.getMethod(method, types); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/testing-core/src/main/java/com/fnproject/fn/testing/FnResult.java
testing-core/src/main/java/com/fnproject/fn/testing/FnResult.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.OutputEvent; /** * A simple abstraction over {@link OutputEvent} that buffers the response body */ public interface FnResult extends OutputEvent { /** * Returns the body of the function result as a byte array * * @return the function response body */ byte[] getBodyAsBytes(); /** * Returns the body of the function response as a string * * @return a function response body */ String getBodyAsString(); /** * Determine if the status code corresponds to a successful invocation * * @return true if the status code indicates success */ default boolean isSuccess() { return getStatus() == Status.Success; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/testing-core/src/main/java/com/fnproject/fn/testing/FunctionError.java
testing-core/src/main/java/com/fnproject/fn/testing/FunctionError.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; /** * An Exception that can be used in invocations of stubbed external functions to signal the failure of the external * function due to a simulated error case of the function itself */ public class FunctionError extends Exception { public FunctionError() { } public FunctionError(String s) { super(s); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/testing-core/src/main/java/com/fnproject/fn/testing/FnEventBuilder.java
testing-core/src/main/java/com/fnproject/fn/testing/FnEventBuilder.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.IOException; import java.io.InputStream; /** * Builder for function input events */ public interface FnEventBuilder<T> { /** * Add a header to the input with a variable number of values; duplicate headers will be overwritten * * @param key header key * @param value header value(s) * @return an event builder */ FnEventBuilder<T> withHeader(String key, String value); /** * Set the body of the request by providing an InputStream * <p> * Note - setting the body to an input stream means that only one event can be enqueued using this builder. * * @param body the bytes of the body * @return an event builder */ FnEventBuilder<T> withBody(InputStream body) throws IOException; /** * Set the body of the request as a byte array * * @param body the bytes of the body * @return an event builder */ FnEventBuilder<T> withBody(byte[] body); /** * Set the body of the request as a String * * @param body the String of the body * @return an event builder */ FnEventBuilder<T> withBody(String body); /** * Consume the builder and enqueue this event to be passed into the function when it is run * * @return The original testing rule. The builder is consumed. * @throws IllegalStateException if this event has already been enqueued and the event input can only be read once. */ // FnTestingRule enqueue(); T enqueue(); /** * Consume the builder and enqueue multiple copies of this event. * <p> * Note that if the body of the event has been set to an input stream this will fail with an * {@link IllegalStateException}. * * @param n number of copies of the event to enqueue * @return The original testing rule. The builder is consumed. * @throws IllegalStateException if the body cannot be read multiple times. */ // FnTestingRule enqueue(int n); T enqueue(int n); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/testing-core/src/main/java/com/fnproject/fn/testing/HeaderWriter.java
testing-core/src/main/java/com/fnproject/fn/testing/HeaderWriter.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.IOException; import java.io.OutputStream; class HeaderWriter { final OutputStream os; HeaderWriter(OutputStream os) { this.os = os; } void writeHeader(String key, String value) throws IOException { os.write((key + ": " + value + "\r\n").getBytes("ISO-8859-1")); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/test/java/com/fnproject/fn/api/HeadersTest.java
api/src/test/java/com/fnproject/fn/api/HeadersTest.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.api; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Created on 10/09/2018. * <p> * (c) 2018 Oracle Corporation */ public class HeadersTest { @Test public void shouldCanonicalizeHeaders(){ for (String[] v : new String[][] { {"",""}, {"a","A"}, {"fn-ID-","Fn-Id-"}, {"myHeader-VaLue","Myheader-Value"}, {" Not a Header "," Not a Header "}, {"-","-"}, {"--","--"}, {"a-","A-"}, {"-a","-A"} }){ assertThat(Headers.canonicalKey(v[0])).isEqualTo(v[1]); } } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/InputCoercion.java
api/src/main/java/com/fnproject/fn/api/InputCoercion.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.api; import java.util.Optional; /** * Handles the coercion of an input event to a parameter */ public interface InputCoercion<T> { /** * Handle coercion for a function parameter * <p> * Coercions may choose to act on a parameter, in which case they should return a fulfilled option) or may * ignore parameters (allowing other coercions to act on the parameter) * <p> * When a coercion ignores a parameter it must not consume the input stream of the event. * <p> * If a coercion throws a RuntimeException, no further coercions will be tried and the function invocation will fail. * * @param currentContext the invocation context for this event - this links to the {@link RuntimeContext} and method and class * @param arg the parameter index for the argument being extracted * @param input the input event * @param methodWrapper the method which the parameter is for * @return the result of the coercion, if it succeeded */ Optional<T> tryCoerceParam(InvocationContext currentContext, int arg, InputEvent input, MethodWrapper methodWrapper); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/QueryParameters.java
api/src/main/java/com/fnproject/fn/api/QueryParameters.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.api; import java.util.List; import java.util.Map; import java.util.Optional; /** * Wrapper for query parameters map parsed from the URL of a function invocation. */ public interface QueryParameters { /** * Find the first entry for {@code key} if it exists otherwise returns {@code Optional.empty} * * @param key the header entry key (e.g. {@code Accept} in {@code Accept: text/html} * @return the first entry for {@code key} if it was present in the URL otherwise {@code Optional.empty}. * @throws NullPointerException if {@code key} is null. */ Optional<String> get(String key); /** * Find the list of entries for a specific key. Returns {@code Optional.empty}. Useful when multiple values are * passed. e.g. this method returns {@code ["val1", "val2", "val3]} for the key {@code param} in the URL * {@code http://example.com?param=val1&amp;param=val2&amp;param=val3} * * @param key the header entry key (e.g. {@code Accept} in {@code Accept: text/html} * @return the list of entries for the key if present otherwise the empty list * if not present. If the key was present without a value, it returns * a list with a single element, the empty string. * @throws NullPointerException if {@code key} is null. */ List<String> getValues(String key); /** * @return a copy of the underlying map storing all query parameters */ Map<String, List<String>> getAll(); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/InvocationContext.java
api/src/main/java/com/fnproject/fn/api/InvocationContext.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.api; /** * Context wrapper around a single invocation. * <p> * Any attributes attached to this interface are scoped solely to a single function invocation; * multiple invocations of a hot function will receive new instances of this interface. */ public interface InvocationContext { /** * Returns the {@link RuntimeContext} associated with this invocation context * * @return a runtime context */ RuntimeContext getRuntimeContext(); /** * Adds an {@link InvocationListener} that will be fired when an invocation of this function * completes either successfully or exceptionally. * * @param listener a listener to fire when function completes execution */ void addListener(InvocationListener listener); /** * Returns the current request headers for the invocation * * @return the headers passed into the function */ Headers getRequestHeaders(); /** * Sets the response content type, this will override the default content type of the output * * @param contentType a mime type for the response */ default void setResponseContentType(String contentType) { this.setResponseHeader(OutputEvent.CONTENT_TYPE_HEADER, contentType); } /** * Adds a response header to the outbound event * * @param key header key * @param value header value */ void addResponseHeader(String key, String value); /** * Sets a response header to the outbound event, overriding a previous value. * <p> * Headers set in this way override any headers returned by the function or any middleware on the function * * @param key header key * @param v1 first value to set * @param vs other values to set header to */ void setResponseHeader(String key, String v1, 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/api/src/main/java/com/fnproject/fn/api/InvocationListener.java
api/src/main/java/com/fnproject/fn/api/InvocationListener.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.api; import java.util.EventListener; /** * Listener that will be notified in the event that a function invocation executes successfully or fails. * error. Instances of InvocationListener should be registered with {@link InvocationContext}. */ public interface InvocationListener extends EventListener { /** * Notifies this InvocationListener that a function invocation has executed successfully. */ void onSuccess(); /** * Notifies this InvocationListener that a function invocation has failed during its execution. */ void onFailure(); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/RuntimeContext.java
api/src/main/java/com/fnproject/fn/api/RuntimeContext.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.api; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.Optional; /** * Captures the context of a function runtime's lifecycle. * <p> * The attributes represented by this interface are constant over the lifetime * of a function; they will not change between multiple invocations of a hot function. */ public interface RuntimeContext { /** * The application ID of the application associated with this function * @return an application ID */ String getAppID(); /** * THe function ID of the function * @return a function ID */ String getFunctionID(); /** * The user-friendly name of the application associated with this function, * if present; defaulted to the application ID for backwards compatibility * @return an application name */ default public String getAppName() { return getAppID(); } /** * The user-friendly name of the function, if present; defaulted to the * function ID for backwards compatibility * @return a function name */ default public String getFunctionName() { return getFunctionID(); } /** * Create an instance of the user specified class on which the target function to invoke is declared. * * @return new instance of class containing the target function */ Optional<Object> getInvokeInstance(); /** * Get the target method of the user specified function wrapped in a {@link MethodWrapper}. * * @return the target method of the function invocation */ MethodWrapper getMethod(); /** * Get a configuration variable value by key * * @param key the name of the configuration variable * @return an Optional String value of the config variable */ Optional<String> getConfigurationByKey(String key); /** * Get the configuration variables associated with this com.fnproject.fn.runtime * * @return an immutable map of configuration variables */ Map<String, String> getConfiguration(); /** * Get an attribute from the context. * * @param att the attribute ID * @param type the type of the attribute * @param <T> the type of the attribute * @return an Optional which contains the attribute if it is set. */ <T> Optional<T> getAttribute(String att, Class<T> type); /** * Set an attribute , overwriting any previous value * * @param att the attribute name * @param val nullable attribute to set */ void setAttribute(String att, Object val); /** * Add an {@link InputCoercion}. {@link InputCoercion} instances added here will be * tried in order, and before any of the built-in {@link InputCoercion} are tried. * * @param ic The {@link InputCoercion} to add */ void addInputCoercion(InputCoercion ic); /** * Gets a list of the possible {@link InputCoercion} for this parameter. * <p> * If the parameter has been annotated with a specific coercion, only that coercion is * tried, otherwise configuration-provided coercions are tried first and builtin * coercions second. * * @param targetMethod The user function method * @param param The index of the parameter * @return a list of configured input coercions to apply to the given parameter */ List<InputCoercion> getInputCoercions(MethodWrapper targetMethod, int param); /** * Add an {@link OutputCoercion}. {@link OutputCoercion} instances added here will be * tried in order, before any of the builtin {@link OutputCoercion} are tried. * * @param oc The {@link OutputCoercion} to add */ void addOutputCoercion(OutputCoercion oc); /** * Gets a list of the possible {@link OutputCoercion} for the method. * <p> * If the method has been annotated with a specific coercion, only that coercion is * tried, otherwise configuration-provided coercions are tried first and builtin * coercions second. * * @param method The user function method * @return a list of configured output coercions to apply to the given method. */ List<OutputCoercion> getOutputCoercions(Method method); /** * Set an {@link FunctionInvoker} for this function. The invoker will override * the built in function invoker, although the cloud threads invoker will still * have precedence so that cloud threads can be used from functions using custom invokers. * * @param invoker The {@link FunctionInvoker} to add. * @deprecated this is equivalent to {@link #addInvoker(FunctionInvoker, FunctionInvoker.Phase)} with a phase of {@link FunctionInvoker.Phase#Call} */ default void setInvoker(FunctionInvoker invoker) { addInvoker(invoker, FunctionInvoker.Phase.Call); } /** * Adds an FunctionInvoker handler to the runtime - new FunctionInvokers are added at the head of the specific phase they apply to so ordering may be important * * * @param invoker an invoker to use to handle a given call * @param phase the phase at which to add the invoke */ void addInvoker(FunctionInvoker invoker, FunctionInvoker.Phase phase); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/TypeWrapper.java
api/src/main/java/com/fnproject/fn/api/TypeWrapper.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.api; /** * Interface representing type information about a possibly-generic type. */ public interface TypeWrapper { /** * Unlike {@link java.lang.reflect.Method}, types (such as parameter types, or return types) are * resolved to a reified type even if they are generic, providing reification is possible. * * For example, take the following classes: * <pre>{@code * class GenericParent<T> { * public void someMethod(T t) { // do something with t } * } * * class ConcreteClass extends GenericParent<String> { } * }</pre> * * A {@link TypeWrapper} representing the first argument of {@code someMethod} would return {@code String.class} * instead of {@code Object.class} * * @return Reified type */ Class<?> getParameterClass(); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/FunctionInvoker.java
api/src/main/java/com/fnproject/fn/api/FunctionInvoker.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.api; import java.util.Optional; /** * Handles the invocation of a given function call */ public interface FunctionInvoker { /** * Phase determines a loose ordering for invocation handler processing * this should be used with {@link RuntimeContext#addInvoker(FunctionInvoker, Phase)} to add new invoke handlers to a runtime */ enum Phase { /** * The Pre-Call phase runs before the main function call, all {@link FunctionInvoker} handlers added at this phase are tried prior to calling the {@link Phase#Call} phase * This phase is typically used for handlers that /may/ intercept the request based on request attributes */ PreCall, /** * The Call Phase indicates invokers that should handle call values - typically a given runtime will only be handled by one of these */ Call } /** * Optionally handles an invocation chain for this function * <p> * If the invoker returns an empty option then no action has been taken and another invoker may attempt to tryInvoke * <p> * In particular this means that implementations must not read the input event body until they are committed to handling this event. * * A RuntimeException thrown by the implementation will cause the entire function invocation to fail. * * @param ctx the context for a single invocation * @param evt the incoming event * @return a optional output event if the invoker handled the event. */ Optional<OutputEvent> tryInvoke(InvocationContext ctx, InputEvent evt); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/InputBinding.java
api/src/main/java/com/fnproject/fn/api/InputBinding.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.api; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation to be used on a parameter of the user function. * * The annotation must have a 'coercion' argument which specifies the * {@link InputCoercion} class to use to perform the input binding. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface InputBinding { /** * Which coercion class to use for processing an InputEvent into * the type required by the function parameter. * * @return the{@link InputCoercion} class used to perform the input binding */ Class<? extends InputCoercion> coercion(); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/OutputCoercion.java
api/src/main/java/com/fnproject/fn/api/OutputCoercion.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.api; import java.util.Optional; /** * Handles the coercion of a function's return value to an {@link OutputEvent} */ public interface OutputCoercion { /** * Handle coercion for a function parameter * <p> * Coercions may choose to act on a parameter, in which case they should return a fulfilled option) or may * ignore parameters (allowing other coercions to act on the parameter) * <p> * When a coercion ignores a parameter it must not consume the input stream of the event. * <p> * If a coercion throws a RuntimeException, no further coercions will be tried and the function invocation will fail. * * @param currentContext the invocation context for this event - this links to the {@link RuntimeContext} and method and class * @param method the method which was invoked * @param value The object which the method returned * @return the result of the coercion, if it succeeded */ Optional<OutputEvent> wrapFunctionResult(InvocationContext currentContext, MethodWrapper method, Object value); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/OutputEvent.java
api/src/main/java/com/fnproject/fn/api/OutputEvent.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.api; import java.io.IOException; import java.io.OutputStream; import java.util.Objects; import java.util.Optional; /** * Wrapper for an outgoing fn event */ public interface OutputEvent { String CONTENT_TYPE_HEADER = "Content-Type"; /** * The outcome status of this function event * This determines how the platform will reflect this error to the customer and how it will treat the container after an error */ enum Status { /** * The event was successfully processed */ Success(200), /** * The Function code raised unhandled exception */ FunctionError(502), /** * The Function code did not respond within a given timeout */ FunctionTimeout(504), /** * An internal error occurred in the FDK */ InternalError(500); private final int code; Status(int code) { this.code = code; } public int getCode() { return this.code; } } /** * Report the outcome status code of this event. * * @return the status associated with this event */ Status getStatus(); /** * Report the boolean success of this event. * For default-format functions, this is used to map the HTTP status code into a straight success/failure. * * @return true if the output event results from a successful invocation. */ default boolean isSuccess() { return getStatus() == Status.Success; } /** * The content type of the response. * <p> * * @return The name of the content type. */ default Optional<String> getContentType(){ return getHeaders().get(CONTENT_TYPE_HEADER); } /** * Any additional {@link Headers} that should be supplied along with the content * <p> * These are only used when the function format is HTTP * * @return the headers to add */ Headers getHeaders(); /** * Write the body of the output to a stream * * @param out an outputstream to emit the body of the event * @throws IOException OutputStream exceptions percolate up through this method */ void writeToOutput(OutputStream out) throws IOException; /** * Creates a new output event based on this one with the headers overriding * @param headers the headers use in place of this event * @return a new output event with these set */ default OutputEvent withHeaders(Headers headers) { Objects.requireNonNull(headers, "headers"); OutputEvent a = this; return new OutputEvent() { @Override public Status getStatus() { return a.getStatus(); } @Override public Headers getHeaders() { return headers; } @Override public void writeToOutput(OutputStream out) throws IOException { a.writeToOutput(out); } }; } /** * Create an output event from a byte array * * @param bytes the byte array to write to the output * @param status the status code to report * @param contentType the content type to present on HTTP responses * @return a new output event */ static OutputEvent fromBytes(byte[] bytes, Status status, String contentType) { return fromBytes(bytes, status, contentType, Headers.emptyHeaders()); } /** * Create an output event from a byte array * * @param bytes the byte array to write to the output * @param status the status code of this event * @param contentType the content type to present on HTTP responses or null * @param headers any additional headers to supply with HTTP responses * @return a new output event */ static OutputEvent fromBytes(final byte[] bytes, final Status status, final String contentType, final Headers headers) { Objects.requireNonNull(bytes, "bytes"); Objects.requireNonNull(status, "status"); Objects.requireNonNull(headers, "headers"); final Headers newHeaders = contentType== null?Headers.emptyHeaders():headers.setHeader("Content-Type",contentType); return new OutputEvent() { @Override public Status getStatus() { return status; } @Override public Headers getHeaders() { return newHeaders; } @Override public void writeToOutput(OutputStream out) throws IOException { out.write(bytes); } }; } /** * Returns an output event with an empty body and a given status * @param status the status of the event * @return a new output event */ static OutputEvent emptyResult(final Status status) { Objects.requireNonNull(status, "status"); return new OutputEvent() { @Override public Status getStatus() { return status; } @Override public Headers getHeaders() { return Headers.emptyHeaders(); } @Override public void writeToOutput(OutputStream out) throws IOException { } }; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/FnFeature.java
api/src/main/java/com/fnproject/fn/api/FnFeature.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.api; import java.lang.annotation.*; /** * Annotation to be used in user function classes to enable runtime-wide feature. * * Runtime features are initialized at the point that the function class is loaded but prior to the call chain. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Repeatable(FnFeatures.class) public @interface FnFeature { /** * The feature class to load this must have a zero-arg public constructor * @return feature class */ Class<? extends RuntimeFeature> value(); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/FnFeatures.java
api/src/main/java/com/fnproject/fn/api/FnFeatures.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.api; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation to be used in user function classes to enable runtime-wide feature. * * Runtime features are initialized at the point that the function class is loaded but prior to the call chain. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface FnFeatures { FnFeature[] value(); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/Headers.java
api/src/main/java/com/fnproject/fn/api/Headers.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.api; import java.io.Serializable; import java.util.*; import java.util.regex.Pattern; import java.util.stream.Stream; /** * Represents a set of String-String[] header attributes, per HTTP headers. * <p> * Internally header keys are always canonicalized using HTTP header conventions * <p> * Headers objects are immutable * <p> * Keys are are stored and compared in a case-insensitive way and are canonicalised according to RFC 7230 conventions such that : * * <ul> * <li>a-header</li> * <li>A-Header</li> * <li>A-HeaDer</li> * </ul> * are all equivalent - keys are returned in the canonical form (lower cased except for leading characters) * Where keys do not comply with HTTP header naming they are left as is. */ public final class Headers implements Serializable { private static final Headers emptyHeaders = new Headers(Collections.emptyMap()); private Map<String, List<String>> headers; private Headers(Map<String, List<String>> headersIn) { this.headers = headersIn; } private static Pattern headerName = Pattern.compile("[A-Za-z0-9!#%&'*+-.^_`|~]+"); public Map getAll() { return headers; } /** * Calculates the canonical key (cf RFC 7230) for a header * <p> * If the header contains invalid characters it returns the original header * * @param key the header key to canonicalise * @return a canonical key or the original key if the input contains invalid character */ public static String canonicalKey(String key) { if (!headerName.matcher(key).matches()) { return key; } String parts[] = key.split("-", -1); for (int i = 0; i < parts.length; i++) { String p = parts[i]; if (p.length() > 0) { parts[i] = p.substring(0, 1).toUpperCase() + p.substring(1).toLowerCase(); } } return String.join("-", parts); } /** * Build a headers object from a map composed of (name, value) entries, we take a copy of the map and * disallow any further modification * * @param headers underlying collection of header entries to copy * @return {@code Headers} built from headers map */ public static Headers fromMap(Map<String, String> headers) { Objects.requireNonNull(headers, "headersIn"); Map<String, List<String>> h = new HashMap<>(); headers.forEach((k, v) -> h.put(canonicalKey(k), Collections.singletonList(v))); return new Headers(Collections.unmodifiableMap(new HashMap<>(h))); } /** * Build a headers object from a map composed of (name, value) entries, we take a copy of the map and * disallow any further modification * * @param headers underlying collection of header entries to copy * @return {@code Headers} built from headers map */ public static Headers fromMultiHeaderMap(Map<String, List<String>> headers) { Map<String, List<String>> hm = new HashMap<>(); headers.forEach((k, vs) -> hm.put(canonicalKey(k), new ArrayList<>(vs))); return new Headers(Collections.unmodifiableMap(new HashMap<>(Objects.requireNonNull(headers)))); } /** * Build an empty collection of headers * * @return empty headers */ public static Headers emptyHeaders() { return emptyHeaders; } /** * Sets a map of headers, overwriting any headers in the current headers with the respective values * * @param vals a map of headers * @return a new headers object with thos headers set */ public Headers setHeaders(Map<String, List<String>> vals) { Objects.requireNonNull(vals, "vals"); Map<String, List<String>> nm = new HashMap<>(headers); vals.forEach((k, vs) -> { vs.forEach(v -> Objects.requireNonNull(v, "header list contains null entries")); nm.put(canonicalKey(k), vs); }); return new Headers(nm); } /** * Creates a new headers object with the specified header added - if a header with the same key existed it the new value is appended * <p> * This will overwrite an existing header with an exact name match * * @param key new header key * @param v1 new header value * @param vs additional header values to set * @return a new headers object with the specified header added */ public Headers addHeader(String key, String v1, String... vs) { Objects.requireNonNull(key, "key"); Objects.requireNonNull(key, "value"); String canonKey = canonicalKey(key); Map<String, List<String>> nm = new HashMap<>(headers); List<String> current = nm.get(canonKey); if (current == null) { List<String> s = new ArrayList<>(); s.add(v1); s.addAll(Arrays.asList(vs)); nm.put(canonKey, Collections.unmodifiableList(s)); } else { List<String> s = new ArrayList<>(current); s.add(v1); s.addAll(Arrays.asList(vs)); nm.put(canonKey, Collections.unmodifiableList(s)); } return new Headers(nm); } /** * Creates a new headers object with the specified header set - this overwrites any existin values * <p> * This will overwrite an existing header with an exact name match * * @param key new header key * @param v1 new header value * @param vs more header values to set * @return a new headers object with the specified header added */ public Headers setHeader(String key, String v1, String... vs) { Objects.requireNonNull(key, "key"); Objects.requireNonNull(v1, "v1"); Stream.of(vs).forEach((v) -> Objects.requireNonNull(v, "vs")); Map<String, List<String>> nm = new HashMap<>(headers); List<String> s = new ArrayList<>(); s.add(v1); s.addAll(Arrays.asList(vs)); nm.put(canonicalKey(key), Collections.unmodifiableList(s)); return new Headers(Collections.unmodifiableMap(nm)); } /** * Creates a new headers object with the specified headers set - this overwrites any existin values * <p> * This will overwrite an existing header with an exact name match * * @param key new header key * @param vs header values to set * @return a new headers object with the specified header added */ public Headers setHeader(String key, Collection<String> vs) { Objects.requireNonNull(key, "key"); Objects.requireNonNull(vs, "vs"); if (vs.size() == 0) { throw new IllegalArgumentException("can't set keys to an empty list"); } vs.forEach((v) -> Objects.requireNonNull(v, "vs")); Map<String, List<String>> nm = new HashMap<>(headers); nm.put(canonicalKey(key), Collections.unmodifiableList(new ArrayList<>(vs))); return new Headers(Collections.unmodifiableMap(nm)); } /** * Creates a new headers object with the specified headers remove - this overwrites any existin values * <p> * This will overwrite an existing header with an exact name match * * @param key new header key * @return a new headers object with the specified header removed */ public Headers removeHeader(String key) { Objects.requireNonNull(key, "key"); String canonKey = canonicalKey(key); if (!headers.containsKey(canonKey)) { return this; } Map<String, List<String>> nm = new HashMap<>(headers); nm.remove(canonKey); return new Headers(Collections.unmodifiableMap(nm)); } /** * Returns the header matching the specified key. This matches headers in a case-insensitive way and substitutes * underscore and hyphen characters such that : "CONTENT_TYPE_HEADER" and "Content-type" are equivalent. If no matching * header is found then {@code Optional.empty} is returned. * <p> * When multiple headers are present then the first value is returned- see { #getAllValues(String key)} to get all values for a header * * @param key match key * @return a header matching key or empty if no header matches. * @throws NullPointerException if {@code key} is null. */ public Optional<String> get(String key) { Objects.requireNonNull(key, "Key cannot be null"); String canonKey = canonicalKey(key); List<String> val = headers.get(canonKey); if (val == null){ return Optional.empty(); } return Optional.of(val.get(0)); } /** * Returns a collection of current header keys * * @return a collection of keys */ public Collection<String> keys() { return headers.keySet(); } /** * Returns the headers as a map * * @return a map of key-values */ public Map<String, List<String>> asMap() { return headers; } /** * GetAllValues returns all values for a header or an empty list if the header has no values * @param key the Header key * @return a possibly empty list of values */ public List<String> getAllValues(String key) { return headers.getOrDefault(canonicalKey(key), Collections.emptyList()); } public int hashCode() { return headers.hashCode(); } public boolean equals(Object other) { if (!(other instanceof Headers)) { return false; } if (other == this) { return true; } return headers.equals(((Headers) other).headers); } @Override public String toString() { return Objects.toString(headers); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/OutputBinding.java
api/src/main/java/com/fnproject/fn/api/OutputBinding.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.api; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation to be used on the method of the user function. * <p> * The annotation must have a 'coercion' argument which specifies the * {@link OutputCoercion} class to use to perform the output binding. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OutputBinding { /** * @return Which coercion class to use for processing the return type of the user function into an OutputEvent. */ Class<? extends OutputCoercion> coercion(); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/RuntimeFeature.java
api/src/main/java/com/fnproject/fn/api/RuntimeFeature.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.api; /** * RuntimeFeatures are classes that configure the Fn Runtime prior to startup and can be loaded by annotating the function class with a {@link FnFeature} annotation * Created on 10/09/2018. * <p> * (c) 2018 Oracle Corporation */ public interface RuntimeFeature { /** * Initialize the runtime context for this function * * @param context a runtime context to initalize */ void initialize(RuntimeContext context); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/FnConfiguration.java
api/src/main/java/com/fnproject/fn/api/FnConfiguration.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.api; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation to be used in user function classes on one or more configuration * methods. * <p> * If the user function method is static, then any annotated configuration * method must also be static. This restriction does not apply if the * user function method is non-static. * <p> * The configuration method will be called immediately after the class is * loaded and (in the case where the function method is an instance method) * after an object of the function class is instantiated. This is still before * any function invocations occur. * <p> * Configuration methods must have a void return type; methods may * have zero arguments or take a single argument of type {@link RuntimeContext} which it * may then modify to configure the runtime behaviour of the function. * * <table summary="Configuration Options"> * <tr> * <td></td> * <th>No configuration</th> * <th>Static configuration method</th> * <th>Instance configuration method</th> * </tr> * <tr> * <th>Static function method</th> * <td>OK</td> * <td>OK</td> * <td>ERROR</td> * </tr> * <tr> * <th>Instance function method</th> * <td>OK</td> * <td>OK (can only configure runtime)</td> * <td>OK (can configure runtime and function instance)</td> * </tr> * </table> * <p> * Function classes may have multiple configuration methods and may inherit from classes with configuration methods. * <p> * When multiple methods are declared in a class hierarchy, all static configuration methods will be called before * instance configuration methods and methods declared in super-classes will be called before those in sub-classes. * <p> * Multiple configuration methods in the same class are supported but no guarantees are made about the ordering of * calls. * <p> * When configuration methods are overridden, the `@FnConfiguration` annotation must be added to the overridden * method in order for it to be called. * <p> * `@FnConfiguration` annotations on interface methods (including default methods and static methods) will be * ignored. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface FnConfiguration { }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/MethodWrapper.java
api/src/main/java/com/fnproject/fn/api/MethodWrapper.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.api; import java.lang.reflect.Method; /** * Represents a method, similar to {@link Method} but with methods for resolving * parameter and return types that are reified generics. */ public interface MethodWrapper { /** * Get the target class for the function invocation * * The class from which the wrapper was created, may not necessarily be the declaring class of the method, but a * subclass. * * @return the class the user has configured as the function entrypoint */ Class<?> getTargetClass(); /** * Gets the underlying wrapped {@link Method} * * @return {@link Method} which this class wraps */ Method getTargetMethod(); /** * Get the {@link TypeWrapper} for a parameter specified by {@code index} * @param index index of the parameter whose type to retrieve * @return the type of the parameter at {@code index}, reified generics will resolve to the reified type * and not {@link Object} */ TypeWrapper getParamType(int index); /** * Get the {@link TypeWrapper} for the return type of the method. * @return the return type, reified generics will resolve to the reified type and not {@link Object} */ TypeWrapper getReturnType(); /** * Get the name of the method including the package path built from {@link Class#getCanonicalName()} and * {@link Method#getName()}. e.g. {@code com.fnproject.fn.api.MethodWrapper::getLongName} for this method. * * @return long method name */ default String getLongName() { return getTargetClass().getCanonicalName() + "::" + getTargetMethod().getName(); } /** * Get the number of parameters the method has. * * @return Parameter count */ default int getParameterCount() { return getTargetMethod().getParameterTypes().length; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/InputEvent.java
api/src/main/java/com/fnproject/fn/api/InputEvent.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.api; import java.io.Closeable; import java.io.InputStream; import java.time.Instant; import java.util.function.Function; public interface InputEvent extends Closeable { /** * Consume the body associated with this event * <p> * This may only be done once per request. * * @param dest a function to send the body to - this does not need to close the incoming stream * @param <T> An optional return type * @return the new */ <T> T consumeBody(Function<InputStream, T> dest); /** * return the current call ID for this event * @return a call ID */ String getCallID(); /** * The deadline by which this event should be processed - this is information and is intended to help you determine how long you should spend processing your event - if you exceed this deadline Fn will terminate your container. * * @return a deadline relative to the current system clock that the event must be processed by */ Instant getDeadline(); /** * The HTTP headers on the request * * @return an immutable map of headers */ Headers getHeaders(); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/tracing/TracingContext.java
api/src/main/java/com/fnproject/fn/api/tracing/TracingContext.java
package com.fnproject.fn.api.tracing; import com.fnproject.fn.api.InvocationContext; import com.fnproject.fn.api.RuntimeContext; public interface TracingContext { /** * Returns the underlying invocation context behind this Tracing context * * @return an invocation context related to this function */ InvocationContext getInvocationContext(); /** * Returns the {@link RuntimeContext} associated with this invocation context * * @return a runtime context */ RuntimeContext getRuntimeContext(); /** * Returns true if tracing is enabled for this function invocation * * @return whether tracing is enabled */ Boolean isTracingEnabled(); /** * Returns the user-friendly name of the application associated with the * function; shorthand for getRuntimeContext().getAppName() * * @return the user-friendly name of the application associated with the * function */ String getAppName(); /** * Returns the user-friendly name of the function; shorthand for * getRuntimeContext().getFunctionName() * * @return the user-friendly name of the function */ String getFunctionName(); /** * Returns a standard constructed "service name" to be used in tracing * libraries to identify the function * * @return a standard constructed "service name" */ String getServiceName(); /** * Returns the URL to be used in tracing libraries as the destination for * the tracing data * * @return a string containing the trace collector URL */ String getTraceCollectorURL(); /** * Returns the current trace ID as extracted from Zipkin B3 headers if they * are present on the request * * @return the trace ID as a string */ String getTraceId(); /** * Returns the current span ID as extracted from Zipkin B3 headers if they * are present on the request * * @return the span ID as a string */ String getSpanId(); /** * Returns the parent span ID as extracted from Zipkin B3 headers if they * are present on the request * * @return the parent span ID as a string */ String getParentSpanId(); /** * Returns the value of the Sampled header of the Zipkin B3 headers if they * are present on the request * * @return true if sampling is enabled for the request */ Boolean isSampled(); /** * Returns the value of the Flags header of the Zipkin B3 headers if they * are present on the request * * @return the verbatim value of the X-B3-Flags header */ String getFlags(); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/exception/FunctionConfigurationException.java
api/src/main/java/com/fnproject/fn/api/exception/FunctionConfigurationException.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.api.exception; /** * The function class's configuration methods could not be invoked. */ public class FunctionConfigurationException extends FunctionLoadException { public FunctionConfigurationException(String message, Throwable cause) { super(message, cause); } public FunctionConfigurationException(String message) { super(message); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/exception/FunctionOutputHandlingException.java
api/src/main/java/com/fnproject/fn/api/exception/FunctionOutputHandlingException.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.api.exception; /** * This used to wrap any exception thrown by an {@link com.fnproject.fn.api.OutputCoercion}. It is * also thrown if no {@link com.fnproject.fn.api.OutputCoercion} is applicable to the object returned by the function. */ public class FunctionOutputHandlingException extends RuntimeException { public FunctionOutputHandlingException(String s, Exception e) { super(s,e); } public FunctionOutputHandlingException(String s) { super(s); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/exception/FunctionInputHandlingException.java
api/src/main/java/com/fnproject/fn/api/exception/FunctionInputHandlingException.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.api.exception; /** * This used to wrap any exception thrown by an {@link com.fnproject.fn.api.InputCoercion}. It is * also thrown if no {@link com.fnproject.fn.api.InputCoercion} is applicable to a parameter of the user function. * * This indicates that the input was not appropriate to this function. */ public class FunctionInputHandlingException extends RuntimeException { public FunctionInputHandlingException(String s, Throwable t) { super(s,t); } public FunctionInputHandlingException(String s) { super(s); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/api/src/main/java/com/fnproject/fn/api/exception/FunctionLoadException.java
api/src/main/java/com/fnproject/fn/api/exception/FunctionLoadException.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.api.exception; /** * an exception relating to loading the users code into runtime * see children for specific cases */ public abstract class FunctionLoadException extends RuntimeException { public FunctionLoadException(String message, Throwable cause) { super(message, cause); } public FunctionLoadException(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/api/src/main/java/com/fnproject/fn/api/httpgateway/HTTPGatewayContext.java
api/src/main/java/com/fnproject/fn/api/httpgateway/HTTPGatewayContext.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.api.httpgateway; import com.fnproject.fn.api.Headers; import com.fnproject.fn.api.InvocationContext; import com.fnproject.fn.api.QueryParameters; /** * A context for accessing and setting HTTP Gateway atributes such aas headers and query parameters from a function call * <p> * Created on 19/09/2018. * <p> * (c) 2018 Oracle Corporation */ public interface HTTPGatewayContext { /** * Returns the underlying invocation context behind this HTTP context * * @return an invocation context related to this function */ InvocationContext getInvocationContext(); /** * Returns the HTTP headers for the request associated with this function call * If no headers were set this will return an empty headers object * * @return the incoming HTTP headers sent in the gateway request */ Headers getHeaders(); /** * Returns the fully qualified request URI that the function was called with, including query parameters * * @return the request URI of the function */ String getRequestURL(); /** * Returns the incoming request method for the HTTP * * @return the HTTP method set on this call */ String getMethod(); /** * Returns the query parameters of the request * * @return a query parameters object */ QueryParameters getQueryParameters(); /** * Adds a response header to the outbound event * * @param key header key * @param value header value */ void addResponseHeader(String key, String value); /** * Sets a response header to the outbound event, overriding a previous value. * <p> * Headers set in this way override any headers returned by the function or any middleware on the function * <p> * Setting the "Content-Type" response header also sets this on the underlying Invocation context * * @param key header key * @param v1 first value to set * @param vs other values to set header to */ void setResponseHeader(String key, String v1, String... vs); /** * Sets the HTTP status code of the response * * @param code an HTTP status code * @throws IllegalArgumentException if the code is &lt; 100 or &gt;l=600 */ void setStatusCode(int code); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/experimental-native-image-support/src/test/java/com/fnproject/fn/nativeimagesupport/JacksonFeatureTest.java
experimental-native-image-support/src/test/java/com/fnproject/fn/nativeimagesupport/JacksonFeatureTest.java
package com.fnproject.fn.nativeimagesupport; import java.math.BigInteger; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Created on 16/02/2021. * <p> * (c) 2021 Oracle Corporation */ public class JacksonFeatureTest { @Test public void shouldWalkAnnotations() { assertThat(JacksonFeature.expandClassesToMarkForReflection(AbstractBase.class)).containsExactly(AbstractBase.class,ConcreteSubType.class); assertThat(JacksonFeature.expandClassesToMarkForReflection(InterfaceBase.class)).containsExactly(InterfaceImpl.class); assertThat(JacksonFeature.expandClassesToMarkForReflection(UsesJacksonFeatures.class)).containsExactly(UsesJacksonFeatures.class,UsesJacksonFeatures.Builder.class); assertThat(JacksonFeature.expandClassesToMarkForReflection(AnnotationsOnFields.class)).containsExactly(AnnotationsOnFields.class,BigInteger.class); assertThat(JacksonFeature.expandClassesToMarkForReflection(AnnotationsOnMethods.class)).containsExactly(AnnotationsOnMethods.class,BigInteger.class); } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY) @JsonSubTypes({ @JsonSubTypes.Type(value = ConcreteSubType.class, name = "c1") }) public abstract static class AbstractBase { } public static class ConcreteSubType extends AbstractBase { int id; } public static class InterfaceImpl implements InterfaceBase { } /** * Created on 15/02/2021. * <p> * (c) 2021 Oracle Corporation */ @JsonDeserialize(as = InterfaceImpl.class) public interface InterfaceBase { } @JsonDeserialize(builder = UsesJacksonFeatures.Builder.class) public static class UsesJacksonFeatures { @JsonPOJOBuilder public static class Builder { } } public static class AnnotationsOnFields { @JsonSerialize(as = BigInteger.class) private int number; } public static class AnnotationsOnMethods { @JsonSerialize(as = BigInteger.class) public int getNumber() { return 1; } } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/experimental-native-image-support/src/main/java/com/fnproject/fn/nativeimagesupport/JacksonFeature.java
experimental-native-image-support/src/main/java/com/fnproject/fn/nativeimagesupport/JacksonFeature.java
/* * Copyright (c) 2019, 2020, 2021 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.nativeimagesupport; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import com.fasterxml.jackson.annotation.JacksonAnnotation; import com.oracle.svm.reflect.hosted.ReflectionFeature; import org.graalvm.nativeimage.ImageSingletons; import org.graalvm.nativeimage.hosted.Feature; import org.graalvm.nativeimage.impl.RuntimeReflectionSupport; /** * This is a graal native-image feature that automatically includes any classes referenced as literals in Jackson Annotations * from included classes. * <p> * The process assumes that the following classes require full reflective acceess (all fields/methods/constructors) : * <ul> * <li>Classes with Jackson annotations (any jackson annotation on the class or in a member)</li> * <li>Any Class literals referenced from jackson annotations or their descendents (e.g. Serializers, dispatch types)</li> * </ul> * <p> * This is not likely to be complete and may skip annotations in some cases, notably there are cases where super classes may not be correctly accounted for. */ public class JacksonFeature implements Feature { public JacksonFeature() { System.out.println("JacksonFeature: FnProject experimental Jackson feature loaded"); System.out.println("JacksonFeature: Graal native image support is *experimental* it may not be stable and there may be cases where it does not work as expected"); } private static final String JACKSON_PACKAGE_PREFIX = "com.fasterxml.jackson"; private static boolean shouldIncludeClass(Class<?> clz) { return !clz.isInterface() && clz != Void.class && !clz.getPackage().getName().startsWith(JACKSON_PACKAGE_PREFIX); } private static boolean isJacksonAnnotation(Annotation a) { return a.annotationType().getAnnotation(JacksonAnnotation.class) != null; } protected static Stream<Class<?>> extractLiteralAnnotationRefs(Annotation a) { Class<? extends Annotation> aClass = a.annotationType(); return Arrays.stream(aClass.getDeclaredMethods()) .flatMap(m -> { Object val; // get annotation attribute value try { val = m.invoke(a); } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) { throw new IllegalStateException("Failed to retrieve annotation value from annotation" + a + " method " + m, e); } // technically annotations can't be null but just in case if (val == null) { return Stream.empty(); } if (val.getClass().isAnnotation()) { // annotation param on an annotation - descend return extractLiteralAnnotationRefs((Annotation) val); } else if (val.getClass().isArray()) { Class<?> innerType = val.getClass().getComponentType(); if (innerType.isAnnotation()) { // list of annotations - descend return Arrays.stream((Annotation[]) val) .flatMap(JacksonFeature::extractLiteralAnnotationRefs); } return Arrays.stream((Object[]) val) // add class literals in array ref .filter(arrayVal -> arrayVal instanceof Class).map(arrayVal -> (Class<?>) arrayVal); } else if (val instanceof Class) { return Stream.of((Class<?>) val); } return Stream.empty(); }); } // VisibleForTesting protected static Stream<Class<?>> expandClassesToMarkForReflection(Class<?> clazz) { List<Annotation> jacksonAnnotations; try { jacksonAnnotations = Stream.concat(Stream.concat( Arrays.stream(clazz.getAnnotations()), Arrays.stream(clazz.getDeclaredFields()).flatMap(f -> Arrays.stream(f.getAnnotations()))), Arrays.stream(clazz.getDeclaredMethods()).flatMap(m -> Arrays.stream(m.getAnnotations())) ).filter(JacksonFeature::isJacksonAnnotation).collect(Collectors.toList()); } catch (NoClassDefFoundError ignored) { // we skip the whole class if any of its members are unresolvable - this is assumed safe as jackson won't be able to load the class here anyway return Stream.empty(); } // if no jackson classes present, skip the whole class if (jacksonAnnotations.isEmpty()) { return Stream.empty(); } // otherwise include the class and any descendent classes referenced within those annotations return Stream.concat(Stream.of(clazz), jacksonAnnotations.stream() .flatMap(JacksonFeature::extractLiteralAnnotationRefs)) .filter(JacksonFeature::shouldIncludeClass); } @Override public List<Class<? extends Feature>> getRequiredFeatures() { List<Class<? extends Feature>> fs = new ArrayList<>(); fs.add(ReflectionFeature.class); return fs; } @Override public void beforeAnalysis(BeforeAnalysisAccess access) { ClassLoader cl = access.getApplicationClassLoader(); RuntimeReflectionSupport rrs = ImageSingletons.lookup(RuntimeReflectionSupport.class); access.registerSubtypeReachabilityHandler((acc, sourceClazz) -> { expandClassesToMarkForReflection(sourceClazz) .forEach((referencedClazz) -> { System.out.println("JacksonFeature: adding extra Jackson annotated " + referencedClazz); acc.registerAsUsed(referencedClazz); acc.registerAsInHeap(referencedClazz); rrs.register(referencedClazz); rrs.register(referencedClazz.getDeclaredConstructors()); rrs.register(referencedClazz.getDeclaredMethods()); Arrays.stream(referencedClazz.getDeclaredFields()).forEach(f -> rrs.register(false, f)); }); }, Object.class); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/regex-query/src/test/java/com/fnproject/fn/examples/RegexQueryTests.java
examples/regex-query/src/test/java/com/fnproject/fn/examples/RegexQueryTests.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.examples; import com.fnproject.fn.testing.FnTestingRule; import org.json.JSONException; import org.junit.Rule; import org.junit.Test; import org.skyscreamer.jsonassert.JSONAssert; public class RegexQueryTests { @Rule public FnTestingRule fn = FnTestingRule.createDefault(); @Test public void matchingSingleCharacter() throws JSONException { String text = "a"; String regex = "."; fn.givenEvent() .withBody(String.format("{\"text\": \"%s\", \"regex\": \"%s\"}", text, regex)) .enqueue(); fn.thenRun(RegexQuery.class, "query"); JSONAssert.assertEquals(String.format("{\"text\":\"%s\"," + "\"regex\":\"%s\"," + "\"matches\":[" + "{\"start\": 0, \"end\": 1, \"match\": \"a\"}" + "]}", text, regex), fn.getOnlyResult().getBodyAsString(), false); } @Test public void matchingSingleCharacterMultipleTimes() throws JSONException { String text = "abc"; String regex = "."; fn.givenEvent() .withBody(String.format("{\"text\": \"%s\", \"regex\": \"%s\"}", text, regex)) .enqueue(); fn.thenRun(RegexQuery.class, "query"); JSONAssert.assertEquals(String.format("{\"text\":\"%s\"," + "\"regex\":\"%s\"," + "\"matches\":[" + "{\"start\": 0, \"end\": 1, \"match\": \"a\"}," + "{\"start\": 1, \"end\": 2, \"match\": \"b\"}," + "{\"start\": 2, \"end\": 3, \"match\": \"c\"}" + "]}", text, regex), fn.getOnlyResult().getBodyAsString(), false); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/regex-query/src/main/java/com/fnproject/fn/examples/Match.java
examples/regex-query/src/main/java/com/fnproject/fn/examples/Match.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.examples; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class Match { public final int start; public final int end; public final String match; @JsonCreator public Match(@JsonProperty("start") int start, @JsonProperty("end") int end, @JsonProperty("match") String match) { this.start = start; this.end = end; this.match = match; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/regex-query/src/main/java/com/fnproject/fn/examples/Query.java
examples/regex-query/src/main/java/com/fnproject/fn/examples/Query.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.examples; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class Query { public final String regex; public final String text; @JsonCreator public Query(@JsonProperty("regex") String regex, @JsonProperty("text") String text) { this.regex = regex; this.text = text; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/regex-query/src/main/java/com/fnproject/fn/examples/Response.java
examples/regex-query/src/main/java/com/fnproject/fn/examples/Response.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.examples; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; public class Response { public final String regex; public final String text; public final List<Match> matches; @JsonCreator public Response(@JsonProperty("regex") String regex, @JsonProperty("text") String text, @JsonProperty("matches") List<Match> matches) { this.regex = regex; this.text = text; this.matches = matches; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/regex-query/src/main/java/com/fnproject/fn/examples/RegexQuery.java
examples/regex-query/src/main/java/com/fnproject/fn/examples/RegexQuery.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.examples; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexQuery { public Response query(Query query) { return new Response(query.regex, query.text, getMatches(query)); } private List<Match> getMatches(Query query) { Pattern pattern = Pattern.compile(query.regex); Matcher matcher = pattern.matcher(query.text); List<Match> matches = new ArrayList<>(); while (matcher.find()) { matches.add(new Match(matcher.start(), matcher.end(), query.text.substring(matcher.start(), matcher.end()))); } return matches; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/connectorhub-logging/src/test/java/com/fnproject/fn/examples/FunctionTest.java
examples/connectorhub-logging/src/test/java/com/fnproject/fn/examples/FunctionTest.java
package com.fnproject.fn.examples; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; 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.testing.ConnectorHubTestFeature; import com.fnproject.fn.testing.FnResult; import com.fnproject.fn.testing.FnTestingRule; import org.junit.Rule; import org.junit.Test; public class FunctionTest { @Rule public FnTestingRule fn = FnTestingRule.createDefault(); private final ConnectorHubTestFeature connectorHubTestFeature = ConnectorHubTestFeature.createDefault(fn); @Test public void testInvokeFunctionWithLoggingData() throws Exception { ConnectorHubBatch<LoggingData> event = createMinimalRequest(); connectorHubTestFeature.givenEvent(event).enqueue(); fn.thenRun(Function.class, "handler"); FnResult result = fn.getOnlyResult(); assertEquals(200, result.getStatus().getCode()); } private static ConnectorHubBatch<LoggingData> createMinimalRequest() { 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"); LoggingData source = new LoggingData( "ecb37864-4396-4302-9575-981644949730", "log-name", "1.0", "schedule", "com.oraclecloud.functions.application.functioninvoke", data, oracle, new Date(1764860467553L) ); ConnectorHubBatch<LoggingData> event = mock(ConnectorHubBatch.class); when(event.getBatch()).thenReturn(Collections.singletonList(source)); return event; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/connectorhub-logging/src/main/java/com/fnproject/fn/examples/Function.java
examples/connectorhub-logging/src/main/java/com/fnproject/fn/examples/Function.java
package com.fnproject.fn.examples; import com.fnproject.events.ConnectorHubFunction; import com.fnproject.events.input.ConnectorHubBatch; import com.fnproject.events.input.sch.LoggingData; public class Function extends ConnectorHubFunction<LoggingData> { public LogService logService; public Function() { this.logService = new LogService(); } @Override public void handler(ConnectorHubBatch<LoggingData> batch) { for (LoggingData log : batch.getBatch()) { logService.readLog(log); } } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/connectorhub-logging/src/main/java/com/fnproject/fn/examples/LogService.java
examples/connectorhub-logging/src/main/java/com/fnproject/fn/examples/LogService.java
package com.fnproject.fn.examples; import com.fnproject.events.input.sch.LoggingData; public class LogService { public void readLog(LoggingData loggingData) { System.out.println(loggingData); assert loggingData != null; assert loggingData.getData() != null && !loggingData.getData().isEmpty(); assert loggingData.getId() != null; assert loggingData.getOracle() != null && !loggingData.getOracle().isEmpty();; assert loggingData.getSource() != null; assert loggingData.getSpecversion() != null; assert loggingData.getTime() != null; assert loggingData.getType() != null; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/connectorhub-queue/src/test/java/com/fnproject/fn/examples/FunctionTest.java
examples/connectorhub-queue/src/test/java/com/fnproject/fn/examples/FunctionTest.java
package com.fnproject.fn.examples; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Collections; import com.fnproject.events.input.ConnectorHubBatch; import com.fnproject.events.testing.ConnectorHubTestFeature; import com.fnproject.fn.testing.FnResult; import com.fnproject.fn.testing.FnTestingRule; import org.junit.Rule; import org.junit.Test; public class FunctionTest { @Rule public FnTestingRule fn = FnTestingRule.createDefault(); private final ConnectorHubTestFeature connectorHubTestFeature = ConnectorHubTestFeature.createDefault(fn); @Test public void testInvokeFunctionWithQueueData() throws Exception { ConnectorHubBatch<Employee> event = createMinimalRequest(); connectorHubTestFeature.givenEvent(event).enqueue(); fn.thenRun(Function.class, "handler"); FnResult result = fn.getOnlyResult(); assertEquals(200, result.getStatus().getCode()); } private static ConnectorHubBatch<Employee> createMinimalRequest() { Employee employee = new Employee(); employee.setName("foo"); ConnectorHubBatch<Employee> event = mock(ConnectorHubBatch.class); when(event.getBatch()).thenReturn(Collections.singletonList(employee)); return event; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/connectorhub-queue/src/main/java/com/fnproject/fn/examples/Function.java
examples/connectorhub-queue/src/main/java/com/fnproject/fn/examples/Function.java
package com.fnproject.fn.examples; import com.fnproject.events.ConnectorHubFunction; import com.fnproject.events.input.ConnectorHubBatch; public class Function extends ConnectorHubFunction<Employee> { public QueueService queueService; public Function() { this.queueService = new QueueService(); } @Override public void handler(ConnectorHubBatch<Employee> batch) { for (Employee employee : batch.getBatch()) { queueService.readContent(employee); } } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/connectorhub-queue/src/main/java/com/fnproject/fn/examples/Employee.java
examples/connectorhub-queue/src/main/java/com/fnproject/fn/examples/Employee.java
package com.fnproject.fn.examples; import java.util.Objects; public class Employee { private String name; public Employee() {} public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Employee employee = (Employee) o; return Objects.equals(name, employee.name); } @Override public int hashCode() { return Objects.hashCode(name); } @Override public String toString() { return "Employee{" + "name='" + name + '\'' + '}'; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/connectorhub-queue/src/main/java/com/fnproject/fn/examples/QueueService.java
examples/connectorhub-queue/src/main/java/com/fnproject/fn/examples/QueueService.java
package com.fnproject.fn.examples; public class QueueService { public void readContent(Employee employee) { System.out.println(employee); assert employee != null; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/notifications/src/test/java/com/fnproject/fn/examples/FunctionTest.java
examples/notifications/src/test/java/com/fnproject/fn/examples/FunctionTest.java
package com.fnproject.fn.examples; import static org.junit.Assert.assertEquals; import com.fnproject.events.input.NotificationMessage; import com.fnproject.events.testing.NotificationTestFeature; import com.fnproject.fn.api.Headers; import com.fnproject.fn.testing.FnResult; import com.fnproject.fn.testing.FnTestingRule; import org.junit.Rule; import org.junit.Test; public class FunctionTest { @Rule public FnTestingRule fn = FnTestingRule.createDefault(); private final NotificationTestFeature connectorHubTestFeature = NotificationTestFeature.createDefault(fn); @Test public void testInvokeFunctionWithLoggingData() throws Exception { NotificationMessage<Employee> event = createMinimalRequest(); connectorHubTestFeature.givenEvent(event).enqueue(); fn.thenRun(Function.class, "handler"); FnResult result = fn.getOnlyResult(); assertEquals(200, result.getStatus().getCode()); } private static NotificationMessage createMinimalRequest() { Employee employee = new Employee(); employee.setName("foo"); return new NotificationMessage<>(employee, Headers.emptyHeaders()); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/notifications/src/main/java/com/fnproject/fn/examples/NotificationService.java
examples/notifications/src/main/java/com/fnproject/fn/examples/NotificationService.java
package com.fnproject.fn.examples; import com.fnproject.events.input.NotificationMessage; public class NotificationService { public void readNotification(NotificationMessage<Employee> notification) { System.out.println(notification); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/notifications/src/main/java/com/fnproject/fn/examples/Function.java
examples/notifications/src/main/java/com/fnproject/fn/examples/Function.java
package com.fnproject.fn.examples; import com.fnproject.events.NotificationFunction; import com.fnproject.events.input.NotificationMessage; public class Function extends NotificationFunction<Employee> { public NotificationService notificationService; public Function() { this.notificationService = new NotificationService(); } @Override public void handler(NotificationMessage<Employee> content) { notificationService.readNotification(content); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/notifications/src/main/java/com/fnproject/fn/examples/Employee.java
examples/notifications/src/main/java/com/fnproject/fn/examples/Employee.java
package com.fnproject.fn.examples; import java.util.Objects; public class Employee { private String name; public Employee() {} public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Employee employee = (Employee) o; return Objects.equals(name, employee.name); } @Override public int hashCode() { return Objects.hashCode(name); } @Override public String toString() { return "Employee{" + "name='" + name + '\'' + '}'; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/async-thumbnails/src/test/java/com/fnproject/fn/examples/ThumbnailsFunctionTest.java
examples/async-thumbnails/src/test/java/com/fnproject/fn/examples/ThumbnailsFunctionTest.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.examples; import com.fnproject.fn.testing.FnTestingRule; import com.fnproject.fn.testing.flow.FlowTesting; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.junit.WireMockRule; import org.junit.Rule; import org.junit.Test; import static com.github.tomakehurst.wiremock.client.WireMock.*; public class ThumbnailsFunctionTest { @Rule public final FnTestingRule fn = FnTestingRule.createDefault(); private final FlowTesting flow = FlowTesting.create(fn); @Rule public final WireMockRule mockServer = new WireMockRule(0); @Test public void testThumbnail() { fn .setConfig("OBJECT_STORAGE_URL", "http://localhost:" + mockServer.port()) .setConfig("OBJECT_STORAGE_ACCESS", "alpha") .setConfig("OBJECT_STORAGE_SECRET", "betabetabetabeta") .setConfig("RESIZE_128_FN_ID","myapp/resize128") .setConfig("RESIZE_256_FN_ID","myapp/resize256") .setConfig("RESIZE_512_FN_ID","myapp/resize512"); flow .givenFn("myapp/resize128") .withAction((data) -> "128".getBytes()) .givenFn("myapp/resize256") .withAction((data) -> "256".getBytes()) .givenFn("myapp/resize512") .withAction((data) -> "512".getBytes()); fn .givenEvent() .withBody("fn".getBytes()) .enqueue(); // Mock the http endpoint mockMinio(); fn.thenRun(ThumbnailsFunction.class, "handleRequest"); // Check the final image uploads were performed mockServer.verify(putRequestedFor(urlMatching("/alpha/.*\\.png")).withRequestBody(containing("fn"))); mockServer.verify(putRequestedFor(urlMatching("/alpha/.*\\.png")).withRequestBody(containing("128"))); mockServer.verify(putRequestedFor(urlMatching("/alpha/.*\\.png")).withRequestBody(containing("256"))); mockServer.verify(putRequestedFor(urlMatching("/alpha/.*\\.png")).withRequestBody(containing("512"))); mockServer.verify(4, putRequestedFor(urlMatching(".*"))); } @Test public void anExternalFunctionFailure() { fn .setConfig("OBJECT_STORAGE_URL", "http://localhost:" + mockServer.port()) .setConfig("OBJECT_STORAGE_ACCESS", "alpha") .setConfig("OBJECT_STORAGE_SECRET", "betabetabetabeta") .setConfig("RESIZE_128_FN_ID","myapp/resize128") .setConfig("RESIZE_256_FN_ID","myapp/resize256") .setConfig("RESIZE_512_FN_ID","myapp/resize512");; flow .givenFn("myapp/resize128") .withResult("128".getBytes()) .givenFn("myapp/resize256") .withResult("256".getBytes()) .givenFn("myapp/resize512") .withFunctionError(); fn .givenEvent() .withBody("fn".getBytes()) .enqueue(); // Mock the http endpoint mockMinio(); fn.thenRun(ThumbnailsFunction.class, "handleRequest"); // Confirm that one image upload didn't happen mockServer.verify(0, putRequestedFor(urlMatching("/alpha/.*\\.png")).withRequestBody(equalTo("512"))); mockServer.verify(3, putRequestedFor(urlMatching(".*"))); } private void mockMinio() { mockServer.stubFor(get(urlMatching("/alpha.*")) .willReturn(aResponse().withBody( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ListBucketResult>\n" + " <Name>alpha</Name>\n" + " <Prefix/>\n" + " <KeyCount>0</KeyCount>\n" + " <MaxKeys>100</MaxKeys>\n" + " <IsTruncated>false</IsTruncated>\n" + "</ListBucketResult>"))); mockServer.stubFor(WireMock.head(urlMatching("/alpha.*")).willReturn(aResponse().withStatus(200))); mockServer.stubFor(WireMock.put(urlMatching(".*")).willReturn(aResponse().withStatus(200))); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/async-thumbnails/src/main/java/com/fnproject/fn/examples/ThumbnailsFunction.java
examples/async-thumbnails/src/main/java/com/fnproject/fn/examples/ThumbnailsFunction.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.examples; import com.fnproject.fn.api.FnFeature; import com.fnproject.fn.api.Headers; import com.fnproject.fn.api.RuntimeContext; import com.fnproject.fn.api.flow.Flow; import com.fnproject.fn.runtime.flow.FlowFeature; import com.fnproject.fn.api.flow.Flows; import com.fnproject.fn.api.flow.HttpMethod; import io.minio.BucketExistsArgs; import io.minio.MakeBucketArgs; import io.minio.MinioClient; import io.minio.PutObjectArgs; import java.io.ByteArrayInputStream; import java.io.Serializable; @FnFeature(FlowFeature.class) public class ThumbnailsFunction implements Serializable { private final String storageUrl; private final String storageAccessKey; private final String storageSecretKey; private final String resize128ID; private final String resize256ID; private final String resize512ID; public ThumbnailsFunction(RuntimeContext ctx) { storageUrl = ctx.getConfigurationByKey("OBJECT_STORAGE_URL") .orElseThrow(() -> new RuntimeException("Missing configuration: OBJECT_STORAGE_URL")); storageAccessKey = ctx.getConfigurationByKey("OBJECT_STORAGE_ACCESS") .orElseThrow(() -> new RuntimeException("Missing configuration: OBJECT_STORAGE_ACCESS")); storageSecretKey = ctx.getConfigurationByKey("OBJECT_STORAGE_SECRET") .orElseThrow(() -> new RuntimeException("Missing configuration: OBJECT_STORAGE_SECRET")); resize128ID = ctx.getConfigurationByKey("RESIZE_128_FN_ID") .orElseThrow(() -> new RuntimeException("Missing configuration: RESIZE_128_FN_ID")); resize256ID = ctx.getConfigurationByKey("RESIZE_256_FN_ID") .orElseThrow(() -> new RuntimeException("Missing configuration: RESIZE_256_FN_ID")); resize512ID = ctx.getConfigurationByKey("RESIZE_512_FN_ID") .orElseThrow(() -> new RuntimeException("Missing configuration: RESIZE_512_FN_ID")); } public class Response { Response(String imageId) { this.imageId = imageId; } public String imageId; } public Response handleRequest(byte[] imageBuffer) { String id = java.util.UUID.randomUUID().toString(); Flow runtime = Flows.currentFlow(); runtime.allOf( runtime.invokeFunction(resize128ID, HttpMethod.POST, Headers.emptyHeaders(), imageBuffer) .thenAccept((img) -> objectUpload(img.getBodyAsBytes(), id + "-128.png")), runtime.invokeFunction(resize256ID, HttpMethod.POST, Headers.emptyHeaders(), imageBuffer) .thenAccept((img) -> objectUpload(img.getBodyAsBytes(), id + "-256.png")), runtime.invokeFunction(resize512ID, HttpMethod.POST, Headers.emptyHeaders(), imageBuffer) .thenAccept((img) -> objectUpload(img.getBodyAsBytes(), id + "-512.png")), runtime.supply(() -> objectUpload(imageBuffer, id + ".png")) ); return new Response(id); } /** * Uploads the provided data to the storage server, as an object named as specified. * * @param imageBuffer the image data to upload * @param objectName the name of the remote object to create */ private void objectUpload(byte[] imageBuffer, String objectName) { try { MinioClient minioClient = MinioClient.builder() .endpoint(storageUrl).credentials(storageAccessKey, storageSecretKey).build(); // Ensure the bucket exists. BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket("alpha").build(); MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket("alpha").build(); if(!minioClient.bucketExists(bucketExistsArgs)) { minioClient.makeBucket(makeBucketArgs); } PutObjectArgs putObjectArgs = PutObjectArgs.builder() .bucket("alpha") .object(objectName) .stream(new ByteArrayInputStream(imageBuffer), imageBuffer.length, -1).build(); // Upload the image to the bucket with putObject minioClient.putObject(putObjectArgs); } catch(Exception e) { System.err.println("Error occurred: " + e); e.printStackTrace(); } } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/gradle-build/src/test/java/com/example/fn/HelloFunctionTest.java
examples/gradle-build/src/test/java/com/example/fn/HelloFunctionTest.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.example.fn; import static org.junit.Assert.*; public class HelloFunctionTest { @Rule public final FnTestingRule testing = FnTestingRule.createDefault(); @Test public void shouldReturnGreeting() { testing.givenEvent().enqueue(); testing.thenRun(HelloFunction.class, "handleRequest"); FnResult result = testing.getOnlyResult(); assertEquals("Hello, world!", result.getBodyAsString()); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/gradle-build/src/main/java/com/example/fn/HelloFunction.java
examples/gradle-build/src/main/java/com/example/fn/HelloFunction.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.example.fn; public class HelloFunction { public String handleRequest(String input) { String name = (input == null || input.isEmpty()) ? "world" : input; return "Hello, " + name + "!"; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/qr-code/src/test/java/com/fnproject/fn/examples/QRGenTest.java
examples/qr-code/src/test/java/com/fnproject/fn/examples/QRGenTest.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.examples; import com.fnproject.fn.testing.FnTestingRule; import com.google.zxing.BinaryBitmap; import com.google.zxing.ChecksumException; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.QRCodeReader; import org.junit.Rule; import org.junit.Test; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; import static org.junit.Assert.assertEquals; public class QRGenTest { @Rule public FnTestingRule fn = FnTestingRule.createDefault(); @Test public void textHelloWorld() throws Exception { String content = "hello world"; fn.givenEvent() .withHeader("Fn-Http-Request-Url", "http://www.example.com/qr?contents=hello+world&format=png") .withHeader("Fn-Http-Method","GET") .enqueue(); fn.thenRun(QRGen.class, "create"); assertEquals(content, decode(fn.getOnlyResult().getBodyAsBytes())); } @Test public void phoneNumber() throws Exception { String telephoneNumber = "tel:0-12345-67890"; fn.givenEvent() .withHeader("Fn-Http-Request-Url", "http://www.example.com/qr?contents=tel:0-12345-67890") .withHeader("Fn-Http-Method","GET") .enqueue(); fn.thenRun(QRGen.class, "create"); assertEquals(telephoneNumber, decode(fn.getOnlyResult().getBodyAsBytes())); } @Test public void formatConfigurationIsUsedIfNoFormatIsProvided() throws Exception { String contents = "hello world"; fn.setConfig("FORMAT", "jpg"); fn.givenEvent() .withHeader("Fn-Http-Request-Url", "http://www.example.com/qr?contents=hello+world") .withHeader("Fn-Http-Method","GET") .enqueue(); fn.thenRun(QRGen.class, "create"); assertEquals(contents, decode(fn.getOnlyResult().getBodyAsBytes())); } private String decode(byte[] imageBytes) throws IOException, NotFoundException, ChecksumException, FormatException { BinaryBitmap bitmap = readToBitmap(imageBytes); return new QRCodeReader().decode(bitmap).getText(); } private BinaryBitmap readToBitmap(byte[] imageBytes) throws IOException { BufferedImage inputImage = ImageIO.read(new ByteArrayInputStream(imageBytes)); BufferedImageLuminanceSource luminanceSource = new BufferedImageLuminanceSource(inputImage); HybridBinarizer binarizer = new HybridBinarizer(luminanceSource); return new BinaryBitmap(binarizer); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false