org.eclipse.lsp4j.jsonrpc.ResponseErrorException Java Examples

The following examples show how to use org.eclipse.lsp4j.jsonrpc.ResponseErrorException. 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: PrepareRenameHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test(expected = ResponseErrorException.class)
public void testRenameImportDeclaration() throws JavaModelException, BadLocationException {
	when(clientPreferences.isResourceOperationSupported()).thenReturn(true);

	IPackageFragment pack1 = sourceFolder.createPackageFragment("ex.amples", false, null);

	{
	//@formatter:off
	String[] content = {
		"package ex.amples;\n",
		"import java.ne|*t.URI;\n",
		"public class A {}\n"
	};
	//@formatter:on
		StringBuilder builder = new StringBuilder();
		Position pos = mergeCode(builder, content);
		ICompilationUnit cu = pack1.createCompilationUnit("A.java", builder.toString(), false, null);

		prepareRename(cu, pos, "");
	}
}
 
Example #2
Source File: RenameHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test(expected = ResponseErrorException.class)
public void testRenameSystemLibrary() throws JavaModelException {
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);

	String[] codes = {
			"package test1;\n",
			"public class E {\n",
			"   public int bar() {\n",
			"		String str = new String();\n",
			"   	str.len|*gth();\n",
			"   }\n",
			"}\n"
	};
	StringBuilder builder = new StringBuilder();
	Position pos = mergeCode(builder, codes);
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", builder.toString(), false, null);

	getRenameEdit(cu, pos, "newname");
}
 
Example #3
Source File: PrepareRenameHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test(expected = ResponseErrorException.class)
public void testRenameMiddleOfPackage() throws JavaModelException, BadLocationException {
	when(clientPreferences.isResourceOperationSupported()).thenReturn(true);

	IPackageFragment pack1 = sourceFolder.createPackageFragment("ex.amples", false, null);

	//@formatter:off
	String[] content = {
		"package |*ex.amples;\n",
		"public class A {}\n"
	};
	//@formatter:on
	StringBuilder builder = new StringBuilder();
	Position pos = mergeCode(builder, content);
	ICompilationUnit cu = pack1.createCompilationUnit("A.java", builder.toString(), false, null);

	prepareRename(cu, pos, "ex.am.ple");

	//@formatter:off
	String[] content2 = {
		"package ex.|*amples;\n",
		"public class A {}\n"
	};
	//@formatter:on
	builder = new StringBuilder();
	pos = mergeCode(builder, content2);
	cu = pack1.createCompilationUnit("A.java", builder.toString(), false, null);

	prepareRename(cu, pos, "ex.am.ple");
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
Source File: PrepareRenameHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test(expected = ResponseErrorException.class)
public void testRenamePackage() throws JavaModelException, BadLocationException {
	when(clientPreferences.isResourceOperationSupported()).thenReturn(true);

	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
	IPackageFragment pack2 = sourceFolder.createPackageFragment("parent.test2", false, null);

	String[] codes1= {
			"package test1;\n",
			"import parent.test2.B;\n",
			"public class A {\n",
			"   public void foo(){\n",
			"		B b = new B();\n",
			"		b.foo();\n",
			"	}\n",
			"}\n"
	};

	String[] codes2 = {
			"package parent.test2|*;\n",
			"public class B {\n",
			"	public B() {}\n",
			"   public void foo() {}\n",
			"}\n"
	};
	StringBuilder builderA = new StringBuilder();
	mergeCode(builderA, codes1);
	pack1.createCompilationUnit("A.java", builderA.toString(), false, null);

	StringBuilder builderB = new StringBuilder();
	Position pos = mergeCode(builderB, codes2);
	ICompilationUnit cuB = pack2.createCompilationUnit("B.java", builderB.toString(), false, null);

	prepareRename(cuB, pos, "parent.newpackage");
}
 
Example #9
Source File: RenameHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test(expected = ResponseErrorException.class)
public void testRenameTypeWithErrors() throws JavaModelException, BadLocationException {
	when(clientPreferences.isResourceOperationSupported()).thenReturn(true);

	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);

	String[] codes = { "package test1;\n",
			           "public class Newname {\n",
			           "   }\n",
			           "}\n" };
	StringBuilder builder = new StringBuilder();
	mergeCode(builder, codes);
	ICompilationUnit cu = pack1.createCompilationUnit("Newname.java", builder.toString(), false, null);


	String[] codes1 = { "package test1;\n",
			           "public class E|* {\n",
			           "   public E() {\n",
			           "   }\n",
			           "   public int bar() {\n", "   }\n",
			           "   public int foo() {\n",
			           "		this.bar();\n",
			           "   }\n",
			           "}\n" };
	builder = new StringBuilder();
	Position pos = mergeCode(builder, codes1);
	cu = pack1.createCompilationUnit("E.java", builder.toString(), false, null);

	WorkspaceEdit edit = getRenameEdit(cu, pos, "Newname");
	assertNotNull(edit);
	List<Either<TextDocumentEdit, ResourceOperation>> resourceChanges = edit.getDocumentChanges();

	assertEquals(resourceChanges.size(), 3);
}
 
Example #10
Source File: WorkspaceExecuteCommandHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testExecuteCommandInvalidParameters() {
	expectedEx.expect(ResponseErrorException.class);
	expectedEx.expectMessage("The workspace/executeCommand has empty params or command");

	WorkspaceExecuteCommandHandler handler = WorkspaceExecuteCommandHandler.getInstance();
	ExecuteCommandParams params = null;
	handler.executeCommand(params, monitor);
}
 
Example #11
Source File: WorkspaceExecuteCommandHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testExecuteCommandThrowsExceptionCommand() {
	expectedEx.expect(ResponseErrorException.class);
	expectedEx.expectMessage("Unsupported");

	WorkspaceExecuteCommandHandler handler = WorkspaceExecuteCommandHandler.getInstance();
	ExecuteCommandParams params = new ExecuteCommandParams();
	params.setCommand("testcommand.throwexception");
	handler.executeCommand(params, monitor);
}
 
Example #12
Source File: WorkspaceExecuteCommandHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testExecuteCommandNonexistingCommand() {
	expectedEx.expect(ResponseErrorException.class);
	expectedEx.expectMessage("No delegateCommandHandler for testcommand.not.existing");

	WorkspaceExecuteCommandHandler handler = WorkspaceExecuteCommandHandler.getInstance();
	ExecuteCommandParams params = new ExecuteCommandParams();
	params.setCommand("testcommand.not.existing");
	params.setArguments(Arrays.asList("hello", "world"));
	Object result = handler.executeCommand(params, monitor);
}
 
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 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 #16
Source File: PrepareRenameHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test(expected = ResponseErrorException.class)
public void testRenameClassFile() throws JavaModelException, BadLocationException {
	testRenameClassFile("Ex|*ception");
}
 
Example #17
Source File: PrepareRenameHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test(expected = ResponseErrorException.class)
public void testRenameFQCNClassFile() throws JavaModelException, BadLocationException {
	testRenameClassFile("java.lang.Ex|*ception");
}
 
Example #18
Source File: PrepareRenameHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test(expected = ResponseErrorException.class)
public void testRenameBinaryPackage() throws JavaModelException, BadLocationException {
	testRenameClassFile("java.net|*.URI");
}
 
Example #19
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);
    }
  }
}
 
Example #20
Source File: ServerRefactoringIssueAcceptor.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
public void checkSeverity() {
	if (getMaximumSeverity().compareTo(Severity.WARNING) < 0) {
		throw new ResponseErrorException(toResponseError());
	}
}