org.eclipse.lsp4j.jsonrpc.messages.Message Java Examples

The following examples show how to use org.eclipse.lsp4j.jsonrpc.messages.Message. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RemoteEndpoint.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@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);
	}
}
 
Example #2
Source File: DebugMessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@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());
}
 
Example #3
Source File: DebugMessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@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"));
	}
}
 
Example #4
Source File: DebugMessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@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"));
	}
}
 
Example #5
Source File: RemoteEndpointTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@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();
	}
}
 
Example #6
Source File: TracingMessageConsumer.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #7
Source File: StreamMessageConsumer.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@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);
	}
}
 
Example #8
Source File: MessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@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());
}
 
Example #9
Source File: RemoteEndpointTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@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();
	}
}
 
Example #10
Source File: HTMLLanguageServer.java    From wildwebdeveloper with Eclipse Public License 2.0 6 votes vote down vote up
@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);
		}
	}
}
 
Example #11
Source File: YAMLLanguageServer.java    From wildwebdeveloper with Eclipse Public License 2.0 6 votes vote down vote up
@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);
	}
}
 
Example #12
Source File: MessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@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"));
	}
}
 
Example #13
Source File: MessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@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"));
	}
}
 
Example #14
Source File: MessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@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()));
	MessageJsonHandler handler = new MessageJsonHandler(supportedMethods);
	handler.setMethodProvider((id) -> "foo");
	Message message = handler.parseMessage("{\"jsonrpc\":\"2.0\","
			+ "\"id\":\"2\",\n"
			+ " \"result\": [\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("{\"jsonrpc\":\"2.0\","
			+ "\"id\":\"2\",\n" 
			+ "\"result\": \"name\"\n"
			+ "}");
	result = (Either<String, List<Map<String,String>>>) ((ResponseMessage)message).getResult();
	Assert.assertFalse(result.isRight());
	Assert.assertEquals("name", result.getLeft());
}
 
Example #15
Source File: MessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked" })
@Test
public void testParseEmptyList() {
	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\": []}");
	List<Entry> result = (List<Entry>) ((ResponseMessage)message).getResult();
	Assert.assertEquals(0, result.size());
}
 
Example #16
Source File: MessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@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()));
	MessageJsonHandler handler = new MessageJsonHandler(supportedMethods);
	handler.setMethodProvider((id) -> "foo");

	Message message = handler.parseMessage("{\"jsonrpc\":\"2.0\","
			+ "\"id\":\"2\",\n"
			+ "\"result\": {\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("{\"jsonrpc\":\"2.0\","
			+ "\"id\":\"2\",\n"
			+ "\"result\": [{\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());
}
 
Example #17
Source File: MessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testParseNullList() {
	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\": null}");
	Assert.assertNull(((ResponseMessage)message).getResult());
}
 
Example #18
Source File: MessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@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()));
	MessageJsonHandler handler = new MessageJsonHandler(supportedMethods);
	handler.setMethodProvider((id) -> "foo");

	Message message = handler.parseMessage("{\"jsonrpc\":\"2.0\","
			+ "\"id\":\"2\",\n"
			+ "\"result\": [{\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("{\"jsonrpc\":\"2.0\","
			+ "\"id\":\"2\",\n"
			+ "\"result\": {\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());
}
 
Example #19
Source File: MessageTypeAdapter.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@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);
}
 
Example #20
Source File: RemoteEndpoint.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void consume(Message message) {
	if (message instanceof NotificationMessage) {
		NotificationMessage notificationMessage = (NotificationMessage) message;
		handleNotification(notificationMessage);
	} else if (message instanceof RequestMessage) {
		RequestMessage requestMessage = (RequestMessage) message;
		handleRequest(requestMessage);
	} else if (message instanceof ResponseMessage) {
		ResponseMessage responseMessage = (ResponseMessage) message;
		handleResponse(responseMessage);
	} else {
		LOG.log(Level.WARNING, "Unkown message type.", message);
	}
}
 
Example #21
Source File: ReflectiveMessageValidator.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@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);
	}
}
 
Example #22
Source File: DebugMessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@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());
}
 
Example #23
Source File: DebugMessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@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());
}
 
Example #24
Source File: JsonMessageHelper.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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");
	}
}
 
Example #25
Source File: LanguageServerWrapper.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
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()));
        }
    }
}
 
Example #26
Source File: LanguageServerWrapper.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
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());
    }
}
 
Example #27
Source File: MessageHandler.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
private void handleMessage(Message message) {
    if (message instanceof ResponseMessage) {
        ResponseMessage responseMessage = (ResponseMessage) message;
        if (responseMessage.getResult() instanceof InitializeResult) {
            listener.initialize(languageServer, (InitializeResult) responseMessage.getResult());
        }
    }
}
 
Example #28
Source File: RemoteEndpointTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void consume(Message message) {
	if (sentException) {
		messages.add(message);
	} else {
		// throw an exception only for the first message
		sentException = true;
		throw new RuntimeException("Exception in consumer");
	}
}
 
Example #29
Source File: CSSLanguageServer.java    From wildwebdeveloper with Eclipse Public License 2.0 5 votes vote down vote up
@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);
		}
	}
}
 
Example #30
Source File: JSonLanguageServer.java    From wildwebdeveloper with Eclipse Public License 2.0 5 votes vote down vote up
@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);
		}
	}
}