001package org.consensusj.jsonrpc.introspection.sample; 002 003import org.consensusj.jsonrpc.JsonRpcError; 004import org.consensusj.jsonrpc.JsonRpcRequest; 005import org.consensusj.jsonrpc.JsonRpcResponse; 006import org.consensusj.jsonrpc.JsonRpcService; 007import org.consensusj.jsonrpc.introspection.AbstractJsonRpcService; 008import org.consensusj.jsonrpc.introspection.JsonRpcServiceWrapper; 009import org.slf4j.Logger; 010import org.slf4j.LoggerFactory; 011 012import java.lang.invoke.MethodHandles; 013import java.lang.reflect.Method; 014import java.util.Arrays; 015import java.util.Map; 016import java.util.concurrent.CompletableFuture; 017import java.util.concurrent.ExecutionException; 018 019/** 020 * Simple service and command-line tool that contains a "math" JsonRpcService 021 * Allows testing method dispatch independent of any server code or framework 022 * (including compiling with Graal `native-image` and running as a native tool with SubstrateVM) 023 */ 024public class MathService extends AbstractJsonRpcService { 025 private static final Logger log = LoggerFactory.getLogger(MathService.class); 026 private static final Map<String, Method> methods = JsonRpcServiceWrapper.reflect(MethodHandles.lookup().lookupClass()); 027 028 /** 029 * Constructor that calls {@link AbstractJsonRpcService#AbstractJsonRpcService(Map)} with a private, statically-initialized 030 * {@link Map} of methods generated with {@link JsonRpcServiceWrapper#reflect(Class)} }. 031 */ 032 public MathService() { 033 super(methods); 034 } 035 036 public static void main(String[] args) { 037 JsonRpcService service = new MathService(); 038 JsonRpcRequest req = new JsonRpcRequest("add", Arrays.asList(1, 2)); 039 JsonRpcResponse<Object> response = null; 040 try { 041 response = service.call(req).get(); 042 } catch (InterruptedException | ExecutionException e) { 043 e.printStackTrace(); 044 System.exit(-1); 045 } 046 Integer sum = (Integer) response.getResult(); 047 JsonRpcError error = response.getError(); 048 if (sum == null) { 049 System.err.println("Error = " + response.getError().getMessage()); 050 System.exit(-1); 051 } 052 System.out.println("Sum is: " + sum); 053 } 054 055 public CompletableFuture<Integer> add(Integer a, Integer b) { 056 log.info("MathService: add {} + {}",a,b); 057 return result(a + b); 058 } 059 060 public CompletableFuture<Integer> subtract(Integer a, Integer b) { 061 log.info("MathService: subtract {} - {}",a,b); 062 return result(a - b); 063 } 064}