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

The following examples show how to use org.eclipse.lsp4j.jsonrpc.messages.ResponseErrorCode. 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: ServerRefactoringIssueAcceptor.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.22
 */
protected int getCodeBySeverity(Severity maxSeverity) {
	if (maxSeverity != null) {
		switch (maxSeverity) {
		case OK:
			return 0;
		case INFO:
			return 0;
		case WARNING:
			return 0;
		case ERROR:
			return ResponseErrorCode.UnknownErrorCode.getValue();
		case FATAL:
			return ResponseErrorCode.UnknownErrorCode.getValue();
		default:
			return 0;
		}
	}
	return 0;
}
 
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: 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 #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: 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 #6
Source File: RemoteEndpointTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testExceptionHandlerMisbehaving2() throws Exception {
	LogMessageAccumulator logMessages = new LogMessageAccumulator();
	try {
		// Don't show the exception in the test execution log
		logMessages.registerTo(RemoteEndpoint.class);

		TestEndpoint endp = new TestEndpoint() {
			@Override
			public CompletableFuture<Object> request(String method, Object parameter) {
				return CompletableFuture.supplyAsync(() -> "baz");
			}
		};
		TestMessageConsumer2 consumer = new TestMessageConsumer2();
		// Misbehaving exception handler that returns null
		RemoteEndpoint endpoint = new RemoteEndpoint(consumer, endp, (e) -> null);

		endpoint.consume(init(new RequestMessage(), it -> {
			it.setId("1");
			it.setMethod("foo");
			it.setParams("myparam");
		}));

		while (consumer.messages.isEmpty()) {
			Thread.sleep(20);
		}
		assertEquals("Check some response received", 1, consumer.messages.size());
		ResponseMessage response = (ResponseMessage) consumer.messages.get(0);
		assertNotNull("Check response has error", response.getError());
		assertEquals(ResponseErrorCode.InternalError.getValue(), response.getError().getCode());
	} finally {
		logMessages.unregister();
	}
}
 
Example #7
Source File: RemoteEndpointTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testExceptionHandlerMisbehaving1() {
	LogMessageAccumulator logMessages = new LogMessageAccumulator();
	try {
		// Don't show the exception in the test execution log
		logMessages.registerTo(RemoteEndpoint.class);

		TestEndpoint endp = new TestEndpoint() {
			@Override
			public CompletableFuture<Object> request(String method, Object parameter) {
				throw new RuntimeException("BAAZ");
			}
		};
		TestMessageConsumer consumer = new TestMessageConsumer();
		// Misbehaving exception handler that returns null
		RemoteEndpoint endpoint = new RemoteEndpoint(consumer, endp, (e) -> null);

		endpoint.consume(init(new RequestMessage(), it -> {
			it.setId("1");
			it.setMethod("foo");
			it.setParams("myparam");
		}));

		assertEquals("Check some response received", 1, consumer.messages.size());
		ResponseMessage response = (ResponseMessage) consumer.messages.get(0);
		assertEquals(ResponseErrorCode.InternalError.getValue(), response.getError().getCode());
	} finally {
		logMessages.unregister();
	}
}
 
Example #8
Source File: RemoteEndpointTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testExceptionInEndpoint() {
	LogMessageAccumulator logMessages = new LogMessageAccumulator();
	try {
		// Don't show the exception in the test execution log
		logMessages.registerTo(RemoteEndpoint.class);
		
		TestEndpoint endp = new TestEndpoint() {
			@Override
			public CompletableFuture<Object> request(String method, Object parameter) {
				throw new RuntimeException("BAAZ");
			}
		};
		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");
		}));
		
		ResponseMessage response = (ResponseMessage) consumer.messages.get(0);
		assertEquals("Internal error.", response.getError().getMessage());
		assertEquals(ResponseErrorCode.InternalError.getValue(), response.getError().getCode());
		String exception = (String) response.getError().getData();
		String expected = "java.lang.RuntimeException: BAAZ\n\tat org.eclipse.lsp4j.jsonrpc.test.RemoteEndpointTest";
		assertEquals(expected, exception.replaceAll("\\r", "").substring(0, expected.length()));
	} finally {
		logMessages.unregister();
	}
}
 
Example #9
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 #10
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 #11
Source File: ReflectiveMessageValidator.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
protected List<MessageIssue> validate(Object object) {
	List<MessageIssue> result = new ArrayList<>();
	try {
		validate(object, result, new LinkedList<>(), new LinkedList<>());
	} catch (Exception e) {
		LOG.log(Level.SEVERE, "Error during message validation: " + e.getMessage(), e);
		result.add(new MessageIssue("Message validation failed, please check the logs of the remote endpoint.",
				ResponseErrorCode.InvalidParams.getValue()));
	}
	return result;
}
 
Example #12
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 #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: 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 #15
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 #16
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 #17
Source File: ReflectiveMessageValidator.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Validate all fields of the given object.
 */
protected void validate(Object object, List<MessageIssue> issues, Deque<Object> objectStack, Deque<Object> accessorStack) throws Exception {
	if (object == null 
			|| object instanceof Enum<?> 
			|| object instanceof String 
			|| object instanceof Number
			|| object instanceof Boolean
			|| object instanceof JsonElement
			|| object instanceof Throwable) {
		return;
	}
	if (objectStack.contains(object)) {
		issues.add(new MessageIssue("An element of the message has a direct or indirect reference to itself."
				+ " Path: " + createPathString(accessorStack),
				ResponseErrorCode.InvalidParams.getValue()));
		return;
	}
	objectStack.push(object);
	if (object instanceof List<?>) {
		ListIterator<?> iter = ((List<?>) object).listIterator();
		while (iter.hasNext()) {
			accessorStack.push(iter.nextIndex());
			Object element = iter.next();
			if (element == null) {
				issues.add(new MessageIssue("Lists must not contain null references."
						+ " Path: " + createPathString(accessorStack),
						ResponseErrorCode.InvalidParams.getValue()));
			}
			validate(element, issues, objectStack, accessorStack);
			accessorStack.pop();
		}
	} else if (object instanceof Either<?, ?>) {
		Either<?, ?> either = (Either<?, ?>) object;
		if (either.isLeft()) {
			validate(either.getLeft(), issues, objectStack, accessorStack);
		} else if (either.isRight()) {
			validate(either.getRight(), issues, objectStack, accessorStack);
		} else {
			issues.add(new MessageIssue("An Either instance must not be empty."
					 + " Path: " + createPathString(accessorStack),
					ResponseErrorCode.InvalidParams.getValue()));
		}
	} else {
		for (Method method : object.getClass().getMethods()) {
			if (isGetter(method)) {
				accessorStack.push(method);
				Object value = method.invoke(object);
				if (value == null && method.getAnnotation(NonNull.class) != null) {
					issues.add(new MessageIssue("The accessor '" + method.getDeclaringClass().getSimpleName()
							 + "." + method.getName() + "()' must return a non-null value."
							 + " Path: " + createPathString(accessorStack),
							ResponseErrorCode.InvalidParams.getValue()));
				}
				validate(value, issues, objectStack, accessorStack);
				accessorStack.pop();
			}
		}
	}
	objectStack.pop();
}