@@ -198,6 +198,8 @@ private static class FunctionClassLoader extends URLClassLoader {
198198 private final String functionSignatureType ;
199199 private final ClassLoader functionClassLoader ;
200200
201+ private Server server ;
202+
201203 public Invoker (
202204 Integer port ,
203205 String functionTarget ,
@@ -225,8 +227,58 @@ ClassLoader getFunctionClassLoader() {
225227 return functionClassLoader ;
226228 }
227229
230+ /**
231+ * This will start the server and wait (join) for function calls.
232+ * To start the server inside a unit or integration test, use {@link #startTestServer()} instead.
233+ *
234+ * @see #stopServer()
235+ * @throws Exception
236+ */
228237 public void startServer () throws Exception {
229- Server server = new Server (port );
238+ startServer (true );
239+ }
240+
241+
242+ /**
243+ * This will start the server and return.
244+ *
245+ * This method is designed to be used for unit or integration testing only.
246+ * For other use cases use {@link #startServer()}.
247+ *
248+ * Inside a test a typical usage will be:
249+ * <pre>
250+ * {@code
251+ * // Create an invoker
252+ * Invoker invoker = new Invoker(
253+ * 8081,
254+ * "org.example.MyHttpFunction",
255+ * "http",
256+ * Thread.currentThread().getContextClassLoader()
257+ * );
258+ *
259+ * // Start the test server
260+ * invoker.startTestServer();
261+ *
262+ * // Test the function
263+ *
264+ * // Stop the test server
265+ * invoker.stopServer();
266+ * }
267+ * </pre>
268+ *
269+ * @see #stopServer()
270+ * @throws Exception
271+ */
272+ public void startTestServer () throws Exception {
273+ startServer (false );
274+ }
275+
276+ private void startServer (boolean join ) throws Exception {
277+ if (server != null ) {
278+ throw new IllegalStateException ("Server already started" );
279+ }
280+
281+ server = new Server (port );
230282
231283 ServletContextHandler servletContextHandler = new ServletContextHandler ();
232284 servletContextHandler .setContextPath ("/" );
@@ -261,7 +313,27 @@ public void startServer() throws Exception {
261313
262314 server .start ();
263315 logServerInfo ();
264- server .join ();
316+ if (join ) {
317+ server .join ();
318+ }
319+ }
320+
321+ /**
322+ * Stop the server.
323+ *
324+ * @see #startServer()
325+ * @see #startTestServer()
326+ *
327+ * @throws Exception
328+ */
329+ public void stopServer () throws Exception {
330+ if (server == null ) {
331+ throw new IllegalStateException ("Server not yet started" );
332+ }
333+
334+ server .stop ();
335+ // setting the server to null, so it can be started again
336+ server = null ;
265337 }
266338
267339 private Class <?> loadFunctionClass () throws ClassNotFoundException {
0 commit comments