org.eclipse.lsp4j.jsonrpc.CompletableFutures Java Examples

The following examples show how to use org.eclipse.lsp4j.jsonrpc.CompletableFutures. 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: ProtocolTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testDocumentResolve() throws Exception, ExecutionException {
	LanguageServer languageServer = wrap(LanguageServer.class, new MockLanguageServer() {
		@Override
		public CompletableFuture<DocumentLink> documentLinkResolve(DocumentLink params) {
			return CompletableFutures.computeAsync(canceler -> {
				params.setTarget("resolved");
				return params;
			});
		}
	});
	
	CompletableFuture<DocumentLink> future = languageServer.getTextDocumentService().documentLinkResolve(
			new DocumentLink(new Range(new Position(0, 0), new Position(0, 0)), "unresolved")
	);
	DocumentLink resolved = future.get(TIMEOUT, TimeUnit.MILLISECONDS);
	
	Assert.assertEquals("resolved", resolved.getTarget());
}
 
Example #2
Source File: ActionScriptServices.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
/**
 * Finds where the definition referenced at the current position in a text
 * document is defined.
 */
@Override
public CompletableFuture<Either<List<? extends Location>, List<? extends LocationLink>>> definition(DefinitionParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        //make sure that the latest changes have been passed to
        //workspace.fileChanged() before proceeding
        if(realTimeProblemsChecker != null)
        {
            realTimeProblemsChecker.updateNow();
        }

        compilerWorkspace.startBuilding();
        try
        {
            DefinitionProvider provider = new DefinitionProvider(workspaceFolderManager, fileTracker);
            return provider.definition(params, cancelToken);
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #3
Source File: ProtocolTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testDocumentLink_01() throws Exception, ExecutionException {
	LanguageServer languageServer = wrap(LanguageServer.class, new MockLanguageServer() {
		@Override
		public CompletableFuture<List<DocumentLink>> documentLink(DocumentLinkParams params) {
			return CompletableFutures.computeAsync(canceler -> {
				return new ArrayList<>();
			});
		}
	});
	
	CompletableFuture<List<DocumentLink>> future = languageServer.getTextDocumentService().documentLink(new DocumentLinkParams(new TextDocumentIdentifier("test")));
	List<DocumentLink> list = future.get(TIMEOUT, TimeUnit.MILLISECONDS);
	
	Assert.assertTrue(list.isEmpty());
}
 
Example #4
Source File: ActionScriptServices.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
/**
 * Renames a symbol at the specified document position.
 */
@Override
public CompletableFuture<WorkspaceEdit> rename(RenameParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        //make sure that the latest changes have been passed to
        //workspace.fileChanged() before proceeding
        if(realTimeProblemsChecker != null)
        {
            realTimeProblemsChecker.updateNow();
        }

        compilerWorkspace.startBuilding();
        try
        {
            RenameProvider provider = new RenameProvider(workspaceFolderManager, fileTracker);
            WorkspaceEdit result = provider.rename(params, cancelToken);
            if(result == null)
            {
                if (languageClient != null)
                {
                    MessageParams message = new MessageParams();
                    message.setType(MessageType.Info);
                    message.setMessage("You cannot rename this element.");
                    languageClient.showMessage(message);
                }
                return new WorkspaceEdit(new HashMap<>());
            }
            return result;
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #5
Source File: ActionScriptServices.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
/**
 * Can be used to "quick fix" an error or warning.
 */
@Override
public CompletableFuture<List<Either<Command, CodeAction>>> codeAction(CodeActionParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        //make sure that the latest changes have been passed to
        //workspace.fileChanged() before proceeding
        if(realTimeProblemsChecker != null)
        {
            realTimeProblemsChecker.updateNow();
        }

        compilerWorkspace.startBuilding();
        try
        {
            CodeActionProvider provider = new CodeActionProvider(workspaceFolderManager, fileTracker);
            return provider.codeAction(params, cancelToken);
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #6
Source File: ActionScriptServices.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
/**
 * Searches by name for a symbol in a specific document (not the whole
 * workspace)
 */
@Override
public CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> documentSymbol(DocumentSymbolParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        //make sure that the latest changes have been passed to
        //workspace.fileChanged() before proceeding
        if(realTimeProblemsChecker != null)
        {
            realTimeProblemsChecker.updateNow();
        }
        
        compilerWorkspace.startBuilding();
        try
        {
            boolean hierarchicalDocumentSymbolSupport = false;
            try
            {
                hierarchicalDocumentSymbolSupport = clientCapabilities.getTextDocument().getDocumentSymbol().getHierarchicalDocumentSymbolSupport();
            }
            catch(NullPointerException e)
            {
                //ignore
            }
            DocumentSymbolProvider provider = new DocumentSymbolProvider(workspaceFolderManager, hierarchicalDocumentSymbolSupport);
            return provider.documentSymbol(params, cancelToken);
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #7
Source File: ActionScriptServices.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
/**
 * Searches by name for a symbol in the workspace.
 */
@Override
public CompletableFuture<List<? extends SymbolInformation>> symbol(WorkspaceSymbolParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        //make sure that the latest changes have been passed to
        //workspace.fileChanged() before proceeding
        if(realTimeProblemsChecker != null)
        {
            realTimeProblemsChecker.updateNow();
        }

        compilerWorkspace.startBuilding();
        try
        {
            WorkspaceSymbolProvider provider = new WorkspaceSymbolProvider(workspaceFolderManager);
            return provider.workspaceSymbol(params, cancelToken);
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #8
Source File: ActionScriptServices.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
/**
 * Finds all references of the definition referenced at the current position
 * in a text document. Does not necessarily get called where a definition is
 * defined, but may be at one of the references.
 */
@Override
public CompletableFuture<List<? extends Location>> references(ReferenceParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        //make sure that the latest changes have been passed to
        //workspace.fileChanged() before proceeding
        if(realTimeProblemsChecker != null)
        {
            realTimeProblemsChecker.updateNow();
        }

        compilerWorkspace.startBuilding();
        try
        {
            ReferencesProvider provider = new ReferencesProvider(workspaceFolderManager, fileTracker);
            return provider.references(params, cancelToken);
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #9
Source File: ActionScriptServices.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
/**
 * Finds all implemenations of an interface.
 */
@Override
public CompletableFuture<Either<List<? extends Location>, List<? extends LocationLink>>> implementation(ImplementationParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        //make sure that the latest changes have been passed to
        //workspace.fileChanged() before proceeding
        if(realTimeProblemsChecker != null)
        {
            realTimeProblemsChecker.updateNow();
        }

        compilerWorkspace.startBuilding();
        try
        {
            ImplementationProvider provider = new ImplementationProvider(workspaceFolderManager, fileTracker);
            return provider.implementation(params, cancelToken);
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #10
Source File: ActionScriptServices.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
/**
 * Finds where the type of the definition referenced at the current position
 * in a text document is defined.
 */
@Override
public CompletableFuture<Either<List<? extends Location>, List<? extends LocationLink>>> typeDefinition(TypeDefinitionParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        //make sure that the latest changes have been passed to
        //workspace.fileChanged() before proceeding
        if(realTimeProblemsChecker != null)
        {
            realTimeProblemsChecker.updateNow();
        }

        compilerWorkspace.startBuilding();
        try
        {
            TypeDefinitionProvider provider = new TypeDefinitionProvider(workspaceFolderManager, fileTracker);
            return provider.typeDefinition(params, cancelToken);
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #11
Source File: ActionScriptServices.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
/**
 * Displays a function's parameters, including which one is currently
 * active. Called automatically by VSCode any time that the user types "(",
 * so be sure to check that a function call is actually happening at the
 * current position.
 */
@Override
public CompletableFuture<SignatureHelp> signatureHelp(SignatureHelpParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        //make sure that the latest changes have been passed to
        //workspace.fileChanged() before proceeding
        if(realTimeProblemsChecker != null)
        {
            realTimeProblemsChecker.updateNow();
        }

        compilerWorkspace.startBuilding();
        try
        {
            SignatureHelpProvider provider = new SignatureHelpProvider(workspaceFolderManager, fileTracker);
            return provider.signatureHelp(params, cancelToken);
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #12
Source File: ActionScriptServices.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
/**
 * Returns information to display in a tooltip when the mouse hovers over
 * something in a text document.
 */
@Override
public CompletableFuture<Hover> hover(HoverParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        //make sure that the latest changes have been passed to
        //workspace.fileChanged() before proceeding
        if(realTimeProblemsChecker != null)
        {
            realTimeProblemsChecker.updateNow();
        }

        compilerWorkspace.startBuilding();
        try
        {
            HoverProvider provider = new HoverProvider(workspaceFolderManager, fileTracker);
            return provider.hover(params, cancelToken);
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #13
Source File: ActionScriptServices.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of all items to display in the completion list at a
 * specific position in a document. Called automatically by VSCode as the
 * user types, and may not necessarily be triggered only on "." or ":".
 */
@Override
public CompletableFuture<Either<List<CompletionItem>, CompletionList>> completion(CompletionParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        //make sure that the latest changes have been passed to
        //workspace.fileChanged() before proceeding
        if(realTimeProblemsChecker != null)
        {
            realTimeProblemsChecker.updateNow();
        }

        compilerWorkspace.startBuilding();
        try
        {
            CompletionProvider provider = new CompletionProvider(workspaceFolderManager,
                    fileTracker, completionSupportsSnippets, frameworkSDKIsRoyale);
            return provider.completion(params, cancelToken);
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #14
Source File: ProtocolTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testDocumentLink_02() throws Exception, ExecutionException {
	LanguageServer languageServer = wrap(LanguageServer.class, new MockLanguageServer() {
		@Override
		public CompletableFuture<List<DocumentLink>> documentLink(DocumentLinkParams params) {
			return CompletableFutures.computeAsync(canceler -> {
				return null;
			});
		}
	});
	
	CompletableFuture<List<DocumentLink>> future = languageServer.getTextDocumentService().documentLink(new DocumentLinkParams(new TextDocumentIdentifier("test")));
	List<DocumentLink> list = future.get(TIMEOUT, TimeUnit.MILLISECONDS);
	
	Assert.assertNull(list);
}
 
Example #15
Source File: ModelTextDocument.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the completable future which loads the model. The process of parse od
 * the model is stopped as soon as possible when text content changed.
 * 
 * @return the completable future which loads the model.
 */
public CompletableFuture<T> getModel() {
	if (model == null) {
		int version = super.getVersion();
		model = CompletableFutures.computeAsync((requestCancelChecker) -> {
			long start = System.currentTimeMillis();
			try {
				LOGGER.fine("Start parsing of model with version '" + version);
				// Stop of parse process can be done when completable future is canceled or when
				// version of document changes
				MultiCancelChecker cancelChecker = new MultiCancelChecker(requestCancelChecker,
						new TextDocumentVersionChecker(this, version));
				// parse the model
				return parse.apply(this, cancelChecker);
			} catch (CancellationException e) {
				LOGGER.fine("Stop parsing parsing of model with version '" + version + "' in "
						+ (System.currentTimeMillis() - start) + "ms");
				throw e;
			} finally {
				LOGGER.fine("End parse of model with version '" + version + "' in "
						+ (System.currentTimeMillis() - start) + "ms");
			}
		});
	}
	return model;
}
 
Example #16
Source File: IntegrationTest.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testCancellationResponse() throws Exception {
	// create client messages
	String requestMessage = "{\"jsonrpc\": \"2.0\",\n"
			+ "\"id\": \"1\",\n" 
			+ "\"method\": \"askServer\",\n" 
			+ "\"params\": { \"value\": \"bar\" }\n"
			+ "}";
	String cancellationMessage = "{\"jsonrpc\": \"2.0\",\n"
			+ "\"method\": \"$/cancelRequest\",\n" 
			+ "\"params\": { \"id\": 1 }\n"
			+ "}";
	String clientMessages = getHeader(requestMessage.getBytes().length) + requestMessage
			+ getHeader(cancellationMessage.getBytes().length) + cancellationMessage;
	
	// create server side
	ByteArrayInputStream in = new ByteArrayInputStream(clientMessages.getBytes());
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	MyServer server = new MyServer() {
		@Override
		public CompletableFuture<MyParam> askServer(MyParam param) {
			return CompletableFutures.computeAsync(cancelToken -> {
				try {
					long startTime = System.currentTimeMillis();
					do {
						cancelToken.checkCanceled();
						Thread.sleep(50);
					} while (System.currentTimeMillis() - startTime < TIMEOUT);
				} catch (InterruptedException e) {
					Assert.fail("Thread was interrupted unexpectedly.");
				}
				return param;
			});
		}
	};
	Launcher<MyClient> serverSideLauncher = Launcher.createLauncher(server, MyClient.class, in, out);
	serverSideLauncher.startListening().get(TIMEOUT, TimeUnit.MILLISECONDS);
	
	Assert.assertEquals("Content-Length: 132" + CRLF + CRLF
			+ "{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"error\":{\"code\":-32800,\"message\":\"The request (id: 1, method: \\u0027askServer\\u0027) has been cancelled\"}}",
			out.toString());
}
 
Example #17
Source File: DebugIntegrationTest.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testCancellationResponse() throws Exception {
	// create client messages
	String requestMessage = "{\"type\":\"request\","
			+ "\"seq\":1,\n"
			+ "\"command\":\"askServer\",\n"
			+ "\"arguments\": { value: \"bar\" }\n"
			+ "}";
	String cancellationMessage = "{\"type\":\"event\","
			+ "\"event\":\"$/cancelRequest\",\n"
			+ "\"body\": { id: 1 }\n"
			+ "}";
	String clientMessages = getHeader(requestMessage.getBytes().length) + requestMessage
			+ getHeader(cancellationMessage.getBytes().length) + cancellationMessage;

	// create server side
	ByteArrayInputStream in = new ByteArrayInputStream(clientMessages.getBytes());
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	MyServer server = new MyServer() {
		@Override
		public CompletableFuture<MyParam> askServer(MyParam param) {
			return CompletableFutures.computeAsync(cancelToken -> {
				try {
					long startTime = System.currentTimeMillis();
					do {
						cancelToken.checkCanceled();
						Thread.sleep(50);
					} while (System.currentTimeMillis() - startTime < TIMEOUT);
				} catch (InterruptedException e) {
					Assert.fail("Thread was interrupted unexpectedly.");
				}
				return param;
			});
		}
	};
	Launcher<MyClient> serverSideLauncher = DebugLauncher.createLauncher(server, MyClient.class, in, out);
	serverSideLauncher.startListening().get(TIMEOUT, TimeUnit.MILLISECONDS);

	Assert.assertEquals("Content-Length: 163\r\n\r\n" +
			"{\"type\":\"response\",\"seq\":1,\"request_seq\":1,\"command\":\"askServer\",\"success\":false,\"message\":\"The request (id: 1, method: \\u0027askServer\\u0027) has been cancelled\"}",
			out.toString());
}
 
Example #18
Source File: ExecuteCommandProvider.java    From vscode-as3mxml with Apache License 2.0 4 votes vote down vote up
private CompletableFuture<Object> executeAddMXMLNamespaceCommand(ExecuteCommandParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        compilerWorkspace.startBuilding();
        try
        {
            cancelToken.checkCanceled();
            List<Object> args = params.getArguments();
            String nsPrefix = ((JsonPrimitive) args.get(0)).getAsString();
            String nsUri = ((JsonPrimitive) args.get(1)).getAsString();
            String uri = ((JsonPrimitive) args.get(2)).getAsString();
            int startIndex = ((JsonPrimitive) args.get(3)).getAsInt();
            int endIndex = ((JsonPrimitive) args.get(4)).getAsInt();
            if(nsPrefix == null || nsUri == null)
            {
                return new Object();
            }
            Path pathForImport = LanguageServerCompilerUtils.getPathFromLanguageServerURI(uri);
            if(pathForImport == null)
            {
                return new Object();
            }
            String text = fileTracker.getText(pathForImport);
            if(text == null)
            {
                return new Object();
            }
            WorkspaceEdit workspaceEdit = CodeActionsUtils.createWorkspaceEditForAddMXMLNamespace(nsPrefix, nsUri, text, uri, startIndex, endIndex);
            if(workspaceEdit == null)
            {
                //no edit required
                return new Object();
            }

            ApplyWorkspaceEditParams editParams = new ApplyWorkspaceEditParams();
            editParams.setEdit(workspaceEdit);

            languageClient.applyEdit(editParams);
            return new Object();
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #19
Source File: ExecuteCommandProvider.java    From vscode-as3mxml with Apache License 2.0 4 votes vote down vote up
private CompletableFuture<Object> executeAddImportCommand(ExecuteCommandParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        compilerWorkspace.startBuilding();
        try
        {
            cancelToken.checkCanceled();
            List<Object> args = params.getArguments();
            String qualifiedName = ((JsonPrimitive) args.get(0)).getAsString();
            String uri = ((JsonPrimitive) args.get(1)).getAsString();
            int line = ((JsonPrimitive) args.get(2)).getAsInt();
            int character = ((JsonPrimitive) args.get(3)).getAsInt();
            if(qualifiedName == null)
            {
                return new Object();
            }
            Path pathForImport = LanguageServerCompilerUtils.getPathFromLanguageServerURI(uri);
            if(pathForImport == null)
            {
                return new Object();
            }
            WorkspaceFolderData folderData = workspaceFolderManager.getWorkspaceFolderDataForSourceFile(pathForImport);
            if(folderData == null || folderData.project == null)
            {
                return new Object();
            }
            String text = fileTracker.getText(pathForImport);
            if(text == null)
            {
                return new Object();
            }
            int currentOffset = LanguageServerCompilerUtils.getOffsetFromPosition(new StringReader(text), new Position(line, character));
            ImportRange importRange = null;
            if(uri.endsWith(FILE_EXTENSION_MXML))
            {
                MXMLData mxmlData = workspaceFolderManager.getMXMLDataForPath(pathForImport, folderData);
                IMXMLTagData offsetTag = MXMLDataUtils.getOffsetMXMLTag(mxmlData, currentOffset);
                importRange = ImportRange.fromOffsetTag(offsetTag, currentOffset);
            }
            else
            {
                IASNode offsetNode = workspaceFolderManager.getOffsetNode(pathForImport, currentOffset, folderData);
                importRange = ImportRange.fromOffsetNode(offsetNode);
            }
            WorkspaceEdit workspaceEdit = CodeActionsUtils.createWorkspaceEditForAddImport(
                qualifiedName, text, uri, importRange);
            if(workspaceEdit == null)
            {
                //no edit required
                return new Object();
            }

            ApplyWorkspaceEditParams editParams = new ApplyWorkspaceEditParams();
            editParams.setEdit(workspaceEdit);

            languageClient.applyEdit(editParams);
            return new Object();
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #20
Source File: BaseJDTLanguageServer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
protected <R> CompletableFuture<R> computeAsync(Function<IProgressMonitor, R> code) {
	return CompletableFutures.computeAsync(cc -> code.apply(toMonitor(cc)));
}
 
Example #21
Source File: JDTLanguageServer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private <R> CompletableFuture<R> computeAsyncWithClientProgress(Function<IProgressMonitor, R> code) {
	return CompletableFutures.computeAsync((cc) -> {
		IProgressMonitor monitor = progressReporterManager.getProgressReporter(cc);
		return code.apply(monitor);
	});
}