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

The following examples show how to use org.eclipse.lsp4j.jsonrpc.messages.ResponseError. 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: PatchedRemoteEndpoint.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @param out
 *            a consumer that transmits messages to the remote service
 * @param localEndpoint
 *            the local service implementation
 * @param exceptionHandler
 *            an exception handler that should never return null.
 */
@SuppressWarnings("unchecked")
public PatchedRemoteEndpoint(MessageConsumer out, Endpoint localEndpoint,
		Function<Throwable, ResponseError> exceptionHandler) {
	super(out, localEndpoint, exceptionHandler);
	this.localEndpoint = localEndpoint;
	this.exceptionHandler = exceptionHandler;
	this.out = out;
	Field field;
	try {
		field = RemoteEndpoint.class.getDeclaredField("receivedRequestMap");
		field.setAccessible(true);
		receivedRequestMap = (Map<String, CompletableFuture<?>>) field.get(this);
	} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
		throw new RuntimeException(e);
	}
}
 
Example #2
Source File: RemoteEndpointTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCancellation() {
	TestEndpoint endp = new TestEndpoint();
	TestMessageConsumer consumer = new TestMessageConsumer();
	RemoteEndpoint endpoint = new RemoteEndpoint(consumer, endp);
	
	endpoint.consume(init(new RequestMessage(), it -> {
		it.setId("1");
		it.setMethod("foo");
		it.setParams("myparam");
	}));
	
	Entry<RequestMessage, CompletableFuture<Object>> entry = endp.requests.entrySet().iterator().next();
	entry.getValue().cancel(true);
	ResponseMessage message = (ResponseMessage) consumer.messages.get(0);
	assertNotNull(message);
	ResponseError error = message.getError();
	assertNotNull(error);
	assertEquals(error.getCode(), ResponseErrorCode.RequestCancelled.getValue());
	assertEquals(error.getMessage(), "The request (id: 1, method: 'foo') has been cancelled");
}
 
Example #3
Source File: MessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testResponseErrorData() {
	MessageJsonHandler handler = new MessageJsonHandler(Collections.emptyMap());
	ResponseMessage message = (ResponseMessage) handler.parseMessage("{\"jsonrpc\":\"2.0\","
			+ "\"id\":\"2\",\n"
			+ "\"error\": { \"code\": -32001, \"message\": \"foo\",\n"
			+ "    \"data\": { \"uri\": \"file:/foo\", \"version\": 5, \"list\": [\"a\", \"b\", \"c\"] }\n"
			+ "  }\n"
			+ "}");
	ResponseError error = message.getError();
	Assert.assertTrue("Expected a JsonObject in error.data", error.getData() instanceof JsonObject);
	JsonObject data = (JsonObject) error.getData();
	Assert.assertEquals("file:/foo", data.get("uri").getAsString());
	Assert.assertEquals(5, data.get("version").getAsInt());
	JsonArray list = data.get("list").getAsJsonArray();
	Assert.assertEquals("a", list.get(0).getAsString());
	Assert.assertEquals("b", list.get(1).getAsString());
	Assert.assertEquals("c", list.get(2).getAsString());
}
 
Example #4
Source File: RemoteEndpoint.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
protected void handleRequestIssues(RequestMessage requestMessage, List<MessageIssue> issues) {
	ResponseError errorObject = new ResponseError();
	if (issues.size() == 1) {
		MessageIssue issue = issues.get(0);
		errorObject.setMessage(issue.getText());
		errorObject.setCode(issue.getIssueCode());
		errorObject.setData(issue.getCause());
	} else {
		if (requestMessage.getMethod() != null)
			errorObject.setMessage("Multiple issues were found in '" + requestMessage.getMethod() + "' request.");
		else
			errorObject.setMessage("Multiple issues were found in request.");
		errorObject.setCode(ResponseErrorCode.InvalidRequest);
		errorObject.setData(issues);
	}
	out.consume(createErrorResponseMessage(requestMessage, errorObject));
}
 
Example #5
Source File: DebugRemoteEndpointTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testCancellation() {
	TestEndpoint endp = new TestEndpoint();
	TestMessageConsumer consumer = new TestMessageConsumer();
	RemoteEndpoint endpoint = new DebugRemoteEndpoint(consumer, endp);

	endpoint.consume(new RequestMessage() {{
		setId("1");
		setMethod("foo");
		setParams("myparam");
	}});

	Entry<RequestMessage, CompletableFuture<Object>> entry = endp.requests.entrySet().iterator().next();
	entry.getValue().cancel(true);
	ResponseMessage message = (ResponseMessage) consumer.messages.get(0);
	assertNotNull(message);
	ResponseError error = message.getError();
	assertNotNull(error);
	assertEquals(error.getCode(), ResponseErrorCode.RequestCancelled.getValue());
	assertEquals(error.getMessage(), "The request (id: 1, method: 'foo') has been cancelled");

}
 
Example #6
Source File: XWorkspaceManager.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return the workspace configuration
 * @throws ResponseErrorException
 *             if the workspace is not yet initialized
 */
public IWorkspaceConfig getWorkspaceConfig() throws ResponseErrorException {
	if (workspaceConfig == null) {
		ResponseError error = new ResponseError(ResponseErrorCode.serverNotInitialized,
				"Workspace has not been initialized yet.", null);
		throw new ResponseErrorException(error);
	}
	return workspaceConfig;
}
 
Example #7
Source File: RemoteEndpoint.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param out - a consumer that transmits messages to the remote service
 * @param localEndpoint - the local service implementation
 * @param exceptionHandler - an exception handler that should never return null.
 */
public RemoteEndpoint(MessageConsumer out, Endpoint localEndpoint, Function<Throwable, ResponseError> exceptionHandler) {
	if (out == null)
		throw new NullPointerException("out");
	if (localEndpoint == null)
		throw new NullPointerException("localEndpoint");
	if (exceptionHandler == null)
		throw new NullPointerException("exceptionHandler");
	this.out = out;
	this.localEndpoint = localEndpoint;
	this.exceptionHandler = exceptionHandler;
}
 
Example #8
Source File: RemoteEndpoint.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
private static ResponseError fallbackResponseError(String header, Throwable throwable) {
	LOG.log(Level.SEVERE, header + ": " + throwable.getMessage(), throwable);
	ResponseError error = new ResponseError();
	error.setMessage(header + ".");
	error.setCode(ResponseErrorCode.InternalError);
	ByteArrayOutputStream stackTrace = new ByteArrayOutputStream();
	PrintWriter stackTraceWriter = new PrintWriter(stackTrace);
	throwable.printStackTrace(stackTraceWriter);
	stackTraceWriter.flush();
	error.setData(stackTrace.toString());
	return error;
}
 
Example #9
Source File: GenericEndpoint.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<?> request(String method, Object parameter) {
	// Check the registered method handlers
	Function<Object, CompletableFuture<Object>> handler = methodHandlers.get(method);
	if (handler != null) {
		return handler.apply(parameter);
	}
	
	// Ask the delegate objects whether they can handle the request generically
	List<CompletableFuture<?>> futures = new ArrayList<>(delegates.size());
	for (Object delegate : delegates) {
		if (delegate instanceof Endpoint) {
			futures.add(((Endpoint) delegate).request(method, parameter));
		}
	}
	if (!futures.isEmpty()) {
		return CompletableFuture.anyOf(futures.toArray(new CompletableFuture[futures.size()]));
	}
	
	// Create a log message about the unsupported method
	String message = "Unsupported request method: " + method;
	if (isOptionalMethod(method)) {
		LOG.log(Level.INFO, message);
		return CompletableFuture.completedFuture(null);
	}
	LOG.log(Level.WARNING, message);
	CompletableFuture<?> exceptionalResult = new CompletableFuture<Object>();
	ResponseError error = new ResponseError(ResponseErrorCode.MethodNotFound, message, null);
	exceptionalResult.completeExceptionally(new ResponseErrorException(error));
	return exceptionalResult;
}
 
Example #10
Source File: WorkspaceManager.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @return the workspace configuration
 * @throws ResponseErrorException
 *             if the workspace is not yet initialized
 */
protected IWorkspaceConfig getWorkspaceConfig() throws ResponseErrorException {
	if (workspaceConfig == null) {
		ResponseError error = new ResponseError(ResponseErrorCode.serverNotInitialized,
				"Workspace has not been initialized yet.", null);
		throw new ResponseErrorException(error);
	}
	return workspaceConfig;
}
 
Example #11
Source File: ServerRefactoringIssueAcceptor.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public ResponseError toResponseError() {
	Severity maxSeverity = getMaximumSeverity();
	ResponseError responseError = new ResponseError();
	responseError.setMessage(getMessageBySeverity(maxSeverity));
	responseError.setCode(getCodeBySeverity(maxSeverity));
	List<Issue> bySeverity = IterableExtensions.sortBy(issues, (i) -> i.severity);
	List<String> messages = ListExtensions.map(ListExtensions.reverse(bySeverity), (i) -> i.message);
	responseError.setData(IterableExtensions.join(messages, "\n"));
	return responseError;
}
 
Example #12
Source File: RenamePositionTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void renameAndFail(final String model, final Position position, final String messageFragment) {
  final String modelFile = this.writeFile("MyType.testlang", model);
  this.initialize();
  try {
    final TextDocumentIdentifier identifier = new TextDocumentIdentifier(modelFile);
    PrepareRenameParams _prepareRenameParams = new PrepareRenameParams(identifier, position);
    final Either<Range, PrepareRenameResult> prepareRenameResult = this.languageServer.prepareRename(_prepareRenameParams).get();
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("expected null result got ");
    _builder.append(prepareRenameResult);
    _builder.append(" instead");
    Assert.assertNull(_builder.toString(), prepareRenameResult);
    TextDocumentIdentifier _textDocumentIdentifier = new TextDocumentIdentifier(modelFile);
    final RenameParams renameParams = new RenameParams(_textDocumentIdentifier, position, "Tescht");
    this.languageServer.rename(renameParams).get();
    Assert.fail("Rename should have failed");
  } catch (final Throwable _t) {
    if (_t instanceof Exception) {
      final Exception exc = (Exception)_t;
      final Throwable rootCause = Throwables.getRootCause(exc);
      Assert.assertTrue((rootCause instanceof ResponseErrorException));
      final ResponseError error = ((ResponseErrorException) rootCause).getResponseError();
      Assert.assertTrue(error.getData().toString().contains(messageFragment));
    } else {
      throw Exceptions.sneakyThrow(_t);
    }
  }
}
 
Example #13
Source File: PrepareRenameHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public Either<Range, PrepareRenameResult> prepareRename(TextDocumentPositionParams params, IProgressMonitor monitor) {

		final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri());
		if (unit != null) {
			try {
				OccurrencesFinder finder = new OccurrencesFinder();
				CompilationUnit ast = CoreASTProvider.getInstance().getAST(unit, CoreASTProvider.WAIT_YES, monitor);

				if (ast != null) {
					int offset = JsonRpcHelpers.toOffset(unit.getBuffer(), params.getPosition().getLine(), params.getPosition().getCharacter());
					String error = finder.initialize(ast, offset, 0);
					if (error == null) {
						OccurrenceLocation[] occurrences = finder.getOccurrences();
						if (occurrences != null) {
							for (OccurrenceLocation loc : occurrences) {
								if (monitor.isCanceled()) {
									return Either.forLeft(new Range());
								}
								if (loc.getOffset() <= offset && loc.getOffset() + loc.getLength() >= offset) {
									InnovationContext context = new InnovationContext(unit, loc.getOffset(), loc.getLength());
									context.setASTRoot(ast);
									ASTNode node = context.getCoveredNode();
									// Rename package is not fully supported yet.
									if (!isBinaryOrPackage(node)) {
										return Either.forLeft(JDTUtils.toRange(unit, loc.getOffset(), loc.getLength()));
									}
								}
							}
						}
					}
				}

			} catch (CoreException e) {
				JavaLanguageServerPlugin.logException("Problem computing occurrences for" + unit.getElementName() + " in prepareRename", e);
			}
		}
		throw new ResponseErrorException(new ResponseError(ResponseErrorCode.InvalidRequest, "Renaming this element is not supported.", null));
	}
 
Example #14
Source File: Launcher.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
public Builder<T> setExceptionHandler(Function<Throwable, ResponseError> exceptionHandler) {
	this.exceptionHandler = exceptionHandler;
	return this;
}
 
Example #15
Source File: MessageTypeAdapter.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Message read(JsonReader in) throws IOException, JsonIOException, JsonSyntaxException {
	if (in.peek() == JsonToken.NULL) {
		in.nextNull();
		return null;
	}
	
	in.beginObject();
	String jsonrpc = null, method = null;
	Either<String, Number> id = null;
	Object rawParams = null;
	Object rawResult = null;
	ResponseError responseError = null;
	try {
		
		while (in.hasNext()) {
			String name = in.nextName();
			switch (name) {
			case "jsonrpc": {
				jsonrpc = in.nextString();
				break;
			}
			case "id": {
				if (in.peek() == JsonToken.NUMBER)
					id = Either.forRight(in.nextInt());
				else
					id = Either.forLeft(in.nextString());
				break;
			}
			case "method": {
				method = in.nextString();
				break;
			}
			case "params": {
				rawParams = parseParams(in, method);
				break;
			}
			case "result": {
				rawResult = parseResult(in, id != null ? id.get().toString() : null);
				break;
			}
			case "error": {
				responseError = gson.fromJson(in, ResponseError.class);
				break;
			}
			default:
				in.skipValue();
			}
		}
		Object params = parseParams(rawParams, method);
		Object result = parseResult(rawResult, id != null ? id.get().toString() : null);
		
		in.endObject();
		return createMessage(jsonrpc, id, method, params, result, responseError);
		
	} catch (JsonSyntaxException | MalformedJsonException | EOFException exception) {
		if (id != null || method != null) {
			// Create a message and bundle it to an exception with an issue that wraps the original exception
			Message message = createMessage(jsonrpc, id, method, rawParams, rawResult, responseError);
			MessageIssue issue = new MessageIssue("Message could not be parsed.", ResponseErrorCode.ParseError.getValue(), exception);
			throw new MessageIssueException(message, issue);
		} else {
			throw exception;
		}
	}
}
 
Example #16
Source File: DebugRemoteEndpoint.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
public DebugRemoteEndpoint(MessageConsumer out, Endpoint localEndpoint,
		Function<Throwable, ResponseError> exceptionHandler) {
	super(out, localEndpoint, exceptionHandler);
}
 
Example #17
Source File: ResponseErrorException.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
public ResponseErrorException(ResponseError responseError) {
	this.responseError = responseError;
}
 
Example #18
Source File: ResponseErrorException.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
public ResponseError getResponseError() {
	return responseError;
}
 
Example #19
Source File: RemoteEndpoint.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
protected ResponseMessage createErrorResponseMessage(RequestMessage requestMessage, ResponseError errorObject) {
	ResponseMessage responseMessage = createResponseMessage(requestMessage);
	responseMessage.setError(errorObject);
	return responseMessage;
}
 
Example #20
Source File: PrepareRenameTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testRenameFqn_invalid_error() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("package foo.bar {");
  _builder.newLine();
  _builder.append("  ");
  _builder.append("type A {");
  _builder.newLine();
  _builder.append("    ");
  _builder.append("foo.bar.MyType bar");
  _builder.newLine();
  _builder.append("  ");
  _builder.append("}");
  _builder.newLine();
  _builder.append("  ");
  _builder.append("type MyType { }");
  _builder.newLine();
  _builder.append("}");
  _builder.newLine();
  final String uri = this.writeFile("my-type-invalid.testlang", _builder);
  this.initialize();
  TextDocumentIdentifier _textDocumentIdentifier = new TextDocumentIdentifier(uri);
  Position _position = new Position(2, 5);
  final RenameParams params = new RenameParams(_textDocumentIdentifier, _position, "Does not matter");
  try {
    final WorkspaceEdit workspaceEdit = this.languageServer.rename(params).get();
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("Expected an expcetion when trying to rename document but got a valid workspace edit instead: ");
    _builder_1.append(workspaceEdit);
    Assert.fail(_builder_1.toString());
  } catch (final Throwable _t) {
    if (_t instanceof Exception) {
      final Exception e = (Exception)_t;
      final Throwable rootCause = Throwables.getRootCause(e);
      Assert.assertTrue((rootCause instanceof ResponseErrorException));
      final ResponseError error = ((ResponseErrorException) rootCause).getResponseError();
      Assert.assertTrue(error.getData().toString().contains("No element found at position"));
    } else {
      throw Exceptions.sneakyThrow(_t);
    }
  }
}