下面列出了怎么用org.eclipse.lsp4j.jsonrpc.messages.Message的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void handleMessage(Message message, LanguageServer languageServer, URI rootUri) {
IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
String schemaStr = preferenceStore.getString(YAMLPreferenceInitializer.YAML_SCHEMA_PREFERENCE);
if (cachedSchema == null || !schemaStr.equals(cachedSchema)) {
cachedSchema = schemaStr;
Map<String, Object> schemas = new Gson().fromJson(schemaStr, new TypeToken<HashMap<String, Object>>() {}.getType());
Map<String, Object> yaml = new HashMap<>();
yaml.put("schemas", schemas);
yaml.put("validate", true);
yaml.put("completion", true);
yaml.put("hover", true);
Map<String, Object> settings = new HashMap<>();
settings.put("yaml", yaml);
DidChangeConfigurationParams params = new DidChangeConfigurationParams(settings);
languageServer.getWorkspaceService().didChangeConfiguration(params);
}
}
@Override
public void handleMessage(Message message, LanguageServer languageServer, URI rootUri) {
if (message instanceof ResponseMessage) {
ResponseMessage responseMessage = (ResponseMessage) message;
if (responseMessage.getResult() instanceof InitializeResult) {
Map<String, Object> htmlOptions = new HashMap<>();
Map<String, Object> validateOptions = new HashMap<>();
validateOptions.put("scripts", true);
validateOptions.put("styles", true);
htmlOptions.put("validate", validateOptions);
htmlOptions.put("format", Collections.singletonMap("enable", Boolean.TRUE));
Map<String, Object> html = new HashMap<>();
html.put("html", htmlOptions);
DidChangeConfigurationParams params = new DidChangeConfigurationParams(html);
languageServer.getWorkspaceService().didChangeConfiguration(params);
}
}
}
@SuppressWarnings({ "unchecked" })
@Test
public void testParseList() {
Map<String, JsonRpcMethod> supportedMethods = new LinkedHashMap<>();
supportedMethods.put("foo", JsonRpcMethod.request("foo",
new TypeToken<List<? extends Entry>>() {}.getType(),
new TypeToken<List<? extends Entry>>() {}.getType()));
DebugMessageJsonHandler handler = new DebugMessageJsonHandler(supportedMethods);
handler.setMethodProvider((id)->"foo");
Message message = handler.parseMessage("{"
+ "\"seq\":2,\n"
+ "\"type\":\"response\",\n"
+ "\"success\":true,\n"
+ " \"body\": [\n"
+ " {\"name\":\"$schema\",\"kind\":15,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":1,\"character\":3},\"end\":{\"line\":1,\"character\":55}}}},\n"
+ " {\"name\":\"type\",\"kind\":15,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":2,\"character\":3},\"end\":{\"line\":2,\"character\":19}}}},\n"
+ " {\"name\":\"title\",\"kind\":15,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":3,\"character\":3},\"end\":{\"line\":3,\"character\":50}}}},\n"
+ " {\"name\":\"additionalProperties\",\"kind\":17,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":4,\"character\":4},\"end\":{\"line\":4,\"character\":32}}}},\n"
+ " {\"name\":\"properties\",\"kind\":15,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":5,\"character\":3},\"end\":{\"line\":5,\"character\":20}}}}\n"
+ "]}");
List<? extends Entry> result = (List<? extends Entry>) ((ResponseMessage)message).getResult();
Assert.assertEquals(5, result.size());
for (Entry e : result) {
Assert.assertTrue(e.location.uri, e.location.uri.startsWith("file:/home/mistria"));
}
}
@SuppressWarnings({ "unchecked" })
@Test
public void testParseList_02() {
Map<String, JsonRpcMethod> supportedMethods = new LinkedHashMap<>();
supportedMethods.put("foo", JsonRpcMethod.request("foo",
new TypeToken<Set<Entry>>() {}.getType(),
new TypeToken<Set<Entry>>() {}.getType()));
DebugMessageJsonHandler handler = new DebugMessageJsonHandler(supportedMethods);
handler.setMethodProvider((id)->"foo");
Message message = handler.parseMessage("{"
+ "\"seq\":2,\n"
+ "\"type\":\"response\",\n"
+ "\"success\":true,\n"
+ " \"body\": [\n"
+ " {\"name\":\"$schema\",\"kind\":15,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":1,\"character\":3},\"end\":{\"line\":1,\"character\":55}}}},\n"
+ " {\"name\":\"type\",\"kind\":15,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":2,\"character\":3},\"end\":{\"line\":2,\"character\":19}}}},\n"
+ " {\"name\":\"title\",\"kind\":15,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":3,\"character\":3},\"end\":{\"line\":3,\"character\":50}}}},\n"
+ " {\"name\":\"additionalProperties\",\"kind\":17,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":4,\"character\":4},\"end\":{\"line\":4,\"character\":32}}}},\n"
+ " {\"name\":\"properties\",\"kind\":15,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":5,\"character\":3},\"end\":{\"line\":5,\"character\":20}}}}\n"
+ "]}");
Set<Entry> result = (Set<Entry>) ((ResponseMessage)message).getResult();
Assert.assertEquals(5, result.size());
for (Entry e : result) {
Assert.assertTrue(e.location.uri, e.location.uri.startsWith("file:/home/mistria"));
}
}
@SuppressWarnings({ "unchecked" })
@Test
public void testEither_02() {
Map<String, JsonRpcMethod> supportedMethods = new LinkedHashMap<>();
supportedMethods.put("foo", JsonRpcMethod.request("foo",
new TypeToken<Either<Integer, Map<String,String>>>() {}.getType(),
new TypeToken<Object>() {}.getType()));
DebugMessageJsonHandler handler = new DebugMessageJsonHandler(supportedMethods);
handler.setMethodProvider((id) -> "foo");
Message message = handler.parseMessage("{"
+ "\"seq\":2,\n"
+ "\"type\":\"response\",\n"
+ "\"success\":true,\n"
+ "\"body\": 2\n"
+ "}");
Either<Integer, List<Map<String, String>>> result = (Either<Integer, List<Map<String,String>>>) ((ResponseMessage)message).getResult();
Assert.assertTrue(result.isLeft());
Assert.assertEquals(Integer.valueOf(2), result.getLeft());
}
/**
* Constructs a log string for a given {@link Message}. The type of the {@link MessageConsumer}
* determines if we're sending or receiving a message. The type of the @{link Message} determines
* if it is a request, response, or notification.
*/
@Override
public void consume(Message message) throws MessageIssueException, JsonRpcException {
final Instant now = clock.instant();
final String date = dateTimeFormatter.format(now);
final String logString;
if (messageConsumer instanceof StreamMessageConsumer) {
logString = consumeMessageSending(message, now, date);
} else if (messageConsumer instanceof RemoteEndpoint) {
logString = consumeMessageReceiving(message, now, date);
} else {
LOG.log(WARNING, String.format("Unknown MessageConsumer type: %s", messageConsumer));
logString = null;
}
if (logString != null) {
printWriter.print(logString);
printWriter.flush();
}
messageConsumer.consume(message);
}
@Override
public void consume(Message message) {
try {
String content = jsonHandler.serialize(message);
byte[] contentBytes = content.getBytes(encoding);
int contentLength = contentBytes.length;
String header = getHeader(contentLength);
byte[] headerBytes = header.getBytes(StandardCharsets.US_ASCII);
synchronized (outputLock) {
output.write(headerBytes);
output.write(contentBytes);
output.flush();
}
} catch (IOException exception) {
throw new JsonRpcException(exception);
}
}
@Override
public void handle(Message message, List<MessageIssue> issues) {
if (issues.isEmpty()) {
throw new IllegalArgumentException("The list of issues must not be empty.");
}
if (message instanceof RequestMessage) {
RequestMessage requestMessage = (RequestMessage) message;
handleRequestIssues(requestMessage, issues);
} else if (message instanceof ResponseMessage) {
ResponseMessage responseMessage = (ResponseMessage) message;
handleResponseIssues(responseMessage, issues);
} else {
logIssues(message, issues);
}
}
@SuppressWarnings({ "unchecked" })
@Test
public void testParseList_01() {
Map<String, JsonRpcMethod> supportedMethods = new LinkedHashMap<>();
supportedMethods.put("foo", JsonRpcMethod.request("foo",
new TypeToken<List<? extends Entry>>() {}.getType(),
new TypeToken<List<? extends Entry>>() {}.getType()));
MessageJsonHandler handler = new MessageJsonHandler(supportedMethods);
handler.setMethodProvider((id)->"foo");
Message message = handler.parseMessage("{\"jsonrpc\":\"2.0\","
+ "\"id\":\"2\",\n"
+ " \"result\": [\n"
+ " {\"name\":\"$schema\",\"kind\":15,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":1,\"character\":3},\"end\":{\"line\":1,\"character\":55}}}},\n"
+ " {\"name\":\"type\",\"kind\":15,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":2,\"character\":3},\"end\":{\"line\":2,\"character\":19}}}},\n"
+ " {\"name\":\"title\",\"kind\":15,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":3,\"character\":3},\"end\":{\"line\":3,\"character\":50}}}},\n"
+ " {\"name\":\"additionalProperties\",\"kind\":17,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":4,\"character\":4},\"end\":{\"line\":4,\"character\":32}}}},\n"
+ " {\"name\":\"properties\",\"kind\":15,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":5,\"character\":3},\"end\":{\"line\":5,\"character\":20}}}}\n"
+ "]}");
List<? extends Entry> result = (List<? extends Entry>) ((ResponseMessage) message).getResult();
Assert.assertEquals(5, result.size());
for (Entry e : result) {
Assert.assertTrue(e.location.uri, e.location.uri.startsWith("file:/home/mistria"));
}
}
@SuppressWarnings({ "unchecked" })
@Test
public void testParseList_02() {
Map<String, JsonRpcMethod> supportedMethods = new LinkedHashMap<>();
supportedMethods.put("foo", JsonRpcMethod.request("foo",
new TypeToken<Set<Entry>>() {}.getType(),
new TypeToken<Set<Entry>>() {}.getType()));
MessageJsonHandler handler = new MessageJsonHandler(supportedMethods);
handler.setMethodProvider((id)->"foo");
Message message = handler.parseMessage("{\"jsonrpc\":\"2.0\","
+ "\"id\":\"2\",\n"
+ " \"result\": [\n"
+ " {\"name\":\"$schema\",\"kind\":15,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":1,\"character\":3},\"end\":{\"line\":1,\"character\":55}}}},\n"
+ " {\"name\":\"type\",\"kind\":15,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":2,\"character\":3},\"end\":{\"line\":2,\"character\":19}}}},\n"
+ " {\"name\":\"title\",\"kind\":15,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":3,\"character\":3},\"end\":{\"line\":3,\"character\":50}}}},\n"
+ " {\"name\":\"additionalProperties\",\"kind\":17,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":4,\"character\":4},\"end\":{\"line\":4,\"character\":32}}}},\n"
+ " {\"name\":\"properties\",\"kind\":15,\"location\":{\"uri\":\"file:/home/mistria/runtime-EclipseApplication-with-patch/EclipseConEurope/something.json\",\"range\":{\"start\":{\"line\":5,\"character\":3},\"end\":{\"line\":5,\"character\":20}}}}\n"
+ "]}");
Set<Entry> result = (Set<Entry>) ((ResponseMessage)message).getResult();
Assert.assertEquals(5, result.size());
for (Entry e : result) {
Assert.assertTrue(e.location.uri, e.location.uri.startsWith("file:/home/mistria"));
}
}
@SuppressWarnings({ "unchecked" })
@Test
public void testEither_02() {
Map<String, JsonRpcMethod> supportedMethods = new LinkedHashMap<>();
supportedMethods.put("foo", JsonRpcMethod.request("foo",
new TypeToken<Either<MyEnum, Map<String,String>>>() {}.getType(),
new TypeToken<Object>() {}.getType()));
MessageJsonHandler handler = new MessageJsonHandler(supportedMethods);
handler.setMethodProvider((id) -> "foo");
Message message = handler.parseMessage("{\"jsonrpc\":\"2.0\","
+ "\"id\":\"2\",\n"
+ "\"result\": 2\n"
+ "}");
Either<MyEnum, List<Map<String, String>>> result = (Either<MyEnum, List<Map<String,String>>>) ((ResponseMessage)message).getResult();
Assert.assertTrue(result.isLeft());
Assert.assertEquals(MyEnum.B, result.getLeft());
}
@Test
public void testExceptionInOutputStream() throws Exception {
LogMessageAccumulator logMessages = new LogMessageAccumulator();
try {
logMessages.registerTo(RemoteEndpoint.class);
TestEndpoint endp = new TestEndpoint();
MessageConsumer consumer = new MessageConsumer() {
@Override
public void consume(Message message) throws JsonRpcException {
throw new JsonRpcException(new SocketException("Permission denied: connect"));
}
};
RemoteEndpoint endpoint = new RemoteEndpoint(consumer, endp);
endpoint.notify("foo", null);
logMessages.await(Level.WARNING, "Failed to send notification message.");
} finally {
logMessages.unregister();
}
}
@Test
public void testOutputStreamClosed() throws Exception {
LogMessageAccumulator logMessages = new LogMessageAccumulator();
try {
logMessages.registerTo(RemoteEndpoint.class);
TestEndpoint endp = new TestEndpoint();
MessageConsumer consumer = new MessageConsumer() {
@Override
public void consume(Message message) throws JsonRpcException {
throw new JsonRpcException(new SocketException("Socket closed"));
}
};
RemoteEndpoint endpoint = new RemoteEndpoint(consumer, endp);
endpoint.notify("foo", null);
logMessages.await(Level.INFO, "Failed to send notification message.");
} finally {
logMessages.unregister();
}
}
private void handleMessage(Message message) {
if (message instanceof ResponseMessage) {
ResponseMessage responseMessage = (ResponseMessage) message;
if (responseMessage.getResult() instanceof InitializeResult) {
listener.initialize(languageServer, (InitializeResult) responseMessage.getResult());
}
}
}
public void logMessage(Message message) {
if (message instanceof ResponseMessage) {
ResponseMessage responseMessage = (ResponseMessage) message;
if (responseMessage.getError() != null && (responseMessage.getId()
.equals(Integer.toString(ResponseErrorCode.RequestCancelled.getValue())))) {
LOG.error(new ResponseErrorException(responseMessage.getError()));
}
}
}
private void logMessage(Message message) {
if (message instanceof ResponseMessage && ((ResponseMessage) message).getError() != null
&& ((ResponseMessage) message).getId()
.equals(Integer.toString(ResponseErrorCode.RequestCancelled.getValue()))) {
ResponseMessage responseMessage = (ResponseMessage) message;
LOGGER.warn("", new ResponseErrorException(responseMessage.getError()));
} else if (LOGGER.isDebugEnabled()) {
LOGGER.info(message.getClass().getSimpleName() + '\n' + message.toString());
}
}
@Override
public void handleMessage(Message message, LanguageServer languageServer, URI rootUri) {
if (message instanceof ResponseMessage) {
ResponseMessage responseMessage = (ResponseMessage)message;
if (responseMessage.getResult() instanceof InitializeResult) {
// enable validation: so far, no better way found than changing conf after init.
DidChangeConfigurationParams params = new DidChangeConfigurationParams(getInitializationOptions(rootUri));
languageServer.getWorkspaceService().didChangeConfiguration(params);
}
}
}
@Override
public void handleMessage(Message message, LanguageServer languageServer, URI rootUri) {
if (message instanceof ResponseMessage) {
ResponseMessage responseMessage = (ResponseMessage) message;
if (responseMessage.getResult() instanceof InitializeResult) {
// Send json/schemaAssociations notification to register JSON Schema on JSON
// Language server side.
JSonLanguageServerInterface server = (JSonLanguageServerInterface) languageServer;
Map<String, List<String>> schemaAssociations = getSchemaAssociations();
server.sendJSonchemaAssociations(schemaAssociations);
}
}
}
@Override
public void consume(Message message) {
if (message.getJsonrpc() == null) {
message.setJsonrpc(JSONRPC_VERSION);
}
try {
String content = jsonHandler.serialize(message);
byte[] contentBytes = content.getBytes(encoding);
int contentLength = contentBytes.length;
if (output instanceof WebSocketServerOutputStream) {
contentLength = content.length();
}
String header = getHeader(contentLength);
byte[] headerBytes = header.getBytes(StandardCharsets.US_ASCII);
synchronized (outputLock) {
if (output instanceof WebSocketServerOutputStream) {
((WebSocketServerOutputStream) output).writeString(header + content);
} else {
output.write(headerBytes);
output.write(contentBytes);
}
output.flush();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Returns the deserialized params attribute of a JSON message payload
*/
@SuppressWarnings("unchecked")
public static <T> T getParams(CharSequence jsonPayload) {
Message message = handler.parseMessage(jsonPayload);
Method getParam = null;
try {
getParam = message.getClass().getMethod("getParams");
Object params = getParam.invoke(message);
return (T)params;
} catch (Exception e) {
throw new UnsupportedOperationException("Can't deserialize into class");
}
}
public void onMessage(String content) {
try {
Message message = jsonHandler.parseMessage(content);
callback.consume(message);
} catch (MessageIssueException exception) {
// An issue was found while parsing or validating the message
issueHandler.handle(exception.getRpcMessage(), exception.getIssues());
}
}
@Override
public void consume(Message message) {
String content = jsonHandler.serialize(message);
try {
sendMessage(content);
} catch (IOException exception) {
throw new JsonRpcException(exception);
}
}
private void assertIssues(Message message, CharSequence expectedIssues) {
try {
validator.consume(message);
Assert.fail("Expected InvalidMessageException: " + expectedIssues + ".");
} catch (MessageIssueException e) {
String expected = expectedIssues.toString();
String actual = LineEndings.toSystemLineEndings(e.getMessage());
// The expectation may be a prefix of the actual exception message
if (!actual.startsWith(expected))
Assert.assertEquals(expected, actual);
}
}
@Test
public void testNullResponse() throws InterruptedException, ExecutionException {
LogMessageAccumulator logMessages = new LogMessageAccumulator();
try {
logMessages.registerTo(GenericEndpoint.class);
Endpoint endpoint = ServiceEndpoints.toEndpoint(this);
Map<String, JsonRpcMethod> methods = ServiceEndpoints.getSupportedMethods(LanguageServer.class);
MessageJsonHandler handler = new MessageJsonHandler(methods);
List<Message> msgs = new ArrayList<>();
MessageConsumer consumer = (message) -> {
msgs.add(message);
};
RemoteEndpoint re = new RemoteEndpoint(consumer, endpoint);
RequestMessage request = new RequestMessage();
request.setId("1");
request.setMethod("shutdown");
re.consume(request);
Assert.assertEquals("{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"result\":null}", handler.serialize(msgs.get(0)));
msgs.clear();
shutdownReturn = new Object();
re.consume(request);
Assert.assertEquals("{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"result\":{}}", handler.serialize(msgs.get(0)));
} finally {
logMessages.unregister();
}
}
@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
if (!Message.class.isAssignableFrom(typeToken.getRawType()))
return null;
return (TypeAdapter<T>) new DebugMessageTypeAdapter(handler, gson);
}
@SuppressWarnings({ "unchecked" })
@Test
public void testEither_01() {
Map<String, JsonRpcMethod> supportedMethods = new LinkedHashMap<>();
supportedMethods.put("foo", JsonRpcMethod.request("foo",
new TypeToken<Either<String, List<Map<String,String>>>>() {}.getType(),
new TypeToken<Either<String, Integer>>() {}.getType()));
DebugMessageJsonHandler handler = new DebugMessageJsonHandler(supportedMethods);
handler.setMethodProvider((id) -> "foo");
Message message = handler.parseMessage("{"
+ "\"seq\":2,\n"
+ "\"type\":\"response\",\n"
+ "\"success\":true,\n"
+ " \"body\": [\n"
+ " {\"name\":\"foo\"},\n"
+ " {\"name\":\"bar\"}\n"
+ "]}");
Either<String, List<Map<String, String>>> result = (Either<String, List<Map<String,String>>>) ((ResponseMessage)message).getResult();
Assert.assertTrue(result.isRight());
for (Map<String, String> e : result.getRight()) {
Assert.assertNotNull(e.get("name"));
}
message = handler.parseMessage("{"
+ "\"seq\":2,\n"
+ "\"type\":\"response\",\n"
+ "\"success\":true,\n"
+ "\"body\": \"name\"\n"
+ "}");
result = (Either<String, List<Map<String,String>>>) ((ResponseMessage)message).getResult();
Assert.assertFalse(result.isRight());
Assert.assertEquals("name",result.getLeft());
}
@SuppressWarnings({ "unchecked" })
@Test
public void testEither_04() {
Map<String, JsonRpcMethod> supportedMethods = new LinkedHashMap<>();
supportedMethods.put("foo", JsonRpcMethod.request("foo",
new TypeToken<Either<MyClass, List<? extends MyClass>>>() {}.getType(),
new TypeToken<Object>() {}.getType()));
DebugMessageJsonHandler handler = new DebugMessageJsonHandler(supportedMethods);
handler.setMethodProvider((id) -> "foo");
Message message = handler.parseMessage("{"
+ "\"seq\":2,\n"
+ "\"type\":\"response\",\n"
+ "\"success\":true,\n"
+ "\"body\": {\n"
+ " value:\"foo\"\n"
+ "}}");
Either<MyClass, List<? extends MyClass>> result = (Either<MyClass, List<? extends MyClass>>) ((ResponseMessage)message).getResult();
Assert.assertTrue(result.isLeft());
Assert.assertEquals("foo", result.getLeft().getValue());
message = handler.parseMessage("{"
+ "\"seq\":2,\n"
+ "\"type\":\"response\",\n"
+ "\"success\":true,\n"
+ "\"body\": [{\n"
+ " value:\"bar\"\n"
+ "}]}");
result = (Either<MyClass, List<? extends MyClass>>) ((ResponseMessage)message).getResult();
Assert.assertTrue(result.isRight());
Assert.assertEquals("bar", result.getRight().get(0).getValue());
}
@SuppressWarnings({ "unchecked" })
@Test
public void testEither_05() {
Map<String, JsonRpcMethod> supportedMethods = new LinkedHashMap<>();
supportedMethods.put("foo", JsonRpcMethod.request("foo",
new TypeToken<Either<List<MyClass>, MyClassList>>() {}.getType(),
new TypeToken<Object>() {}.getType()));
DebugMessageJsonHandler handler = new DebugMessageJsonHandler(supportedMethods);
handler.setMethodProvider((id) -> "foo");
Message message = handler.parseMessage("{"
+ "\"seq\":2,\n"
+ "\"type\":\"response\",\n"
+ "\"success\":true,\n"
+ "\"body\": [{\n"
+ " value:\"foo\"\n"
+ "}]}");
Either<List<MyClass>, MyClassList> result = (Either<List<MyClass>, MyClassList>) ((ResponseMessage)message).getResult();
Assert.assertTrue(result.isLeft());
Assert.assertEquals("foo", result.getLeft().get(0).getValue());
message = handler.parseMessage("{"
+ "\"seq\":2,\n"
+ "\"type\":\"response\",\n"
+ "\"success\":true,\n"
+ "\"body\": {\n"
+ " items: [{\n"
+ " value:\"bar\"\n"
+ "}]}}");
result = (Either<List<MyClass>, MyClassList>) ((ResponseMessage)message).getResult();
Assert.assertTrue(result.isRight());
Assert.assertEquals("bar", result.getRight().getItems().get(0).getValue());
}
@Override
public void consume(Message message) throws MessageIssueException, JsonRpcException {
List<MessageIssue> issues = validate(message);
if (!issues.isEmpty()) {
// Sort the messages in order to get a stable order (otherwise it depends on the JVM's reflection implementation)
Collections.sort(issues, (issue1, issue2) -> issue1.getText().compareTo(issue2.getText()));
throw new MessageIssueException(message, issues);
} else if (delegate != null) {
delegate.consume(message);
}
}
@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
if (!Message.class.isAssignableFrom(typeToken.getRawType()))
return null;
return (TypeAdapter<T>) new MessageTypeAdapter(handler, gson);
}