Server-Side Tasks

What You Will Learn

How to upload a JavaScript task to the Infinispan Server using the REST API and then execute it remotely through the Hot Rod client with parameters.

Prerequisites

  • Java 17+

  • An Infinispan Server running on localhost:11222 (or Docker/Podman available for Testcontainers)

Start an Infinispan Server with Docker or Podman:

docker run -it --rm -p 11222:11222 -e USER=admin -e PASS=password quay.io/infinispan/server:latest
Tip
You can replace docker with podman in the command above if you use Podman.
Tip
If no server is running, the tutorial code automatically starts an Infinispan Server using Testcontainers.

Step 1: Create a Server Task Script

Define a JavaScript task in src/main/resources/hello.js:

// mode=local,language=javascript,parameters=[greetee]
"Hello " + greetee

The comment header declares the execution mode, language, and expected parameters.

Step 2: Upload the Task via REST

Use the Infinispan REST client to upload the script to the server:

   private static void uploadTask() throws Exception {
      // Grab the script content from the resources folder
      String script = getResourceAsString("hello.js", InfinispanServerTasks.class.getClassLoader());
      // Connect to the locally running Infinispan Server through the REST API
      RestURI uri = RestURI
            .create(String.format("http://localhost:%d", ConfigurationProperties.DEFAULT_HOTROD_PORT));
      RestClientConfigurationBuilder builder = uri.toConfigurationBuilder();
      builder.security().authentication().username(TutorialsConnectorHelper.USER).password(TutorialsConnectorHelper.PASSWORD);
      RestClient client = RestClient.forConfiguration(builder.build());
      RestEntity scriptEntity = RestEntity.create(APPLICATION_JAVASCRIPT, script);
      CompletionStage<RestResponse> uploadScript = client.tasks()
            .uploadScript("hello", scriptEntity);
      uploadScript.toCompletableFuture().get(5, TimeUnit.SECONDS);
   }

Step 3: Execute the Task via Hot Rod

Execute the uploaded task on a cache with parameters:

      // Get a cache to execute the task
      RemoteCache<String, String> execCache = remoteCacheManager.getCache(TutorialsConnectorHelper.TUTORIAL_CACHE_NAME);

      // Create task parameters
      Map<String, String> parameters = new HashMap<>();
      parameters.put("greetee", "developer");

      // Execute hello task
      String greet = execCache.execute("hello", parameters);
      System.out.printf("Greeting = %s\n", greet);

Step 4: Run the Tutorial

mvn package exec:java

You should see output like:

Greeting = Hello developer

What’s Next