001 package com.thetransactioncompany.jsonrpc2.examples;
002
003
004 import java.util.*;
005
006 import com.thetransactioncompany.jsonrpc2.*;
007
008
009 /**
010 * This example shows how to discern between received JSON-RPC 2.0 requests
011 * and notifications on the server side.
012 *
013 * @author Vladimir Dzhuvinov
014 */
015 public class Example2 {
016
017
018 /**
019 * Parses a JSON-RPC 2.0 message and determines its type
020 *
021 * @param jsonString The JSON-RPC 2.0 message encoded as JSON string.
022 */
023 public static void parseMessage(String jsonString) {
024
025 JSONRPC2Message msg = null;
026
027 try {
028 msg = JSONRPC2Message.parse(jsonString);
029
030 } catch (JSONRPC2ParseException e) {
031 System.out.println(e);
032 return;
033 }
034
035 if (msg instanceof JSONRPC2Request) {
036 System.out.println("The message is a Request");
037 }
038 else if (msg instanceof JSONRPC2Notification) {
039 System.out.println("The message is a Notification");
040 }
041 else if (msg instanceof JSONRPC2Response) {
042 System.out.println("The message is a Response");
043 }
044 }
045
046
047 public static void main(String[] args) {
048
049 // Create request
050 String method = "getAccountBalance";
051 Map<String,Object> params = new HashMap<String,Object>();
052 params.put("accountHolder", "Penny Adams");
053 String id = "req-002";
054 JSONRPC2Request request = new JSONRPC2Request(method, params, id);
055
056 // Create notification
057 method = "notifyRecipient";
058 params = new HashMap<String,Object>();
059 params.put("recipient", "John Shilling");
060 JSONRPC2Notification notification = new JSONRPC2Notification(method, params);
061
062 // Create response
063 String result = "EUR 1500.35";
064 JSONRPC2Response response = new JSONRPC2Response(result, id);
065
066 parseMessage(request.toString());
067 parseMessage(notification.toString());
068 parseMessage(response.toString());
069 }
070 }