org.eclipse.lsp4j.services.LanguageServer Java Examples

The following examples show how to use org.eclipse.lsp4j.services.LanguageServer. 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: 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 #3
Source File: SendNotificationTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
	this.client = mock(ExecuteCommandProposedClient.class);

	PipedOutputStream clientWritesTo = new PipedOutputStream();
	PipedInputStream clientReadsFrom = new PipedInputStream();
	PipedInputStream serverReadsFrom = new PipedInputStream();
	PipedOutputStream serverWritesTo = new PipedOutputStream();

	serverWritesTo.connect(clientReadsFrom);
	clientWritesTo.connect(serverReadsFrom);

	this.closeables = new Closeable[] { clientWritesTo, clientReadsFrom, serverReadsFrom, serverWritesTo };

	Launcher<JavaLanguageClient> serverLauncher = Launcher.createLauncher(new Object(), JavaLanguageClient.class, serverReadsFrom, serverWritesTo);
	serverLauncher.startListening();
	Launcher<LanguageServer> clientLauncher = Launcher.createLauncher(client, LanguageServer.class, clientReadsFrom, clientWritesTo);
	clientLauncher.startListening();

	this.clientConnection = serverLauncher.getRemoteProxy();
}
 
Example #4
Source File: LauncherTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@Before public void setup() throws IOException {
	PipedInputStream inClient = new PipedInputStream();
	PipedOutputStream outClient = new PipedOutputStream();
	PipedInputStream inServer = new PipedInputStream();
	PipedOutputStream outServer = new PipedOutputStream();
	
	inClient.connect(outServer);
	outClient.connect(inServer);
	server = new AssertingEndpoint();
	serverLauncher = LSPLauncher.createServerLauncher(ServiceEndpoints.toServiceObject(server, LanguageServer.class), inServer, outServer);
	serverListening = serverLauncher.startListening();
	
	client = new AssertingEndpoint();
	clientLauncher = LSPLauncher.createClientLauncher(ServiceEndpoints.toServiceObject(client, LanguageClient.class), inClient, outClient);
	clientListening = clientLauncher.startListening();
	
	Logger logger = Logger.getLogger(StreamMessageProducer.class.getName());
	logLevel = logger.getLevel();
	logger.setLevel(Level.SEVERE);
}
 
Example #5
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 #6
Source File: LanguageServiceAccessor.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Gets list of LS initialized for given project
 *
 * @param onlyActiveLS true if this method should return only the already running
 *                     language servers, otherwise previously started language servers
 *                     will be re-activated
 * @return list of Language Servers
 */
@Nonnull
public List<LanguageServer> getLanguageServers(@Nullable Module project,
                                                      Predicate<ServerCapabilities> request, boolean onlyActiveLS) {
    List<LanguageServer> serverInfos = new ArrayList<>();
    for (LanguageServerWrapper wrapper : startedServers) {
        if ((!onlyActiveLS || wrapper.isActive()) && (project == null || wrapper.canOperate(project))) {
            @Nullable
            LanguageServer server = wrapper.getServer();
            if (server == null) {
                continue;
            }
            if (request == null
                    || wrapper.getServerCapabilities() == null /* null check is workaround for https://github.com/TypeFox/ls-api/issues/47 */
                    || request.test(wrapper.getServerCapabilities())) {
                serverInfos.add(server);
            }
        }
    }
    return serverInfos;
}
 
Example #7
Source File: DefaultLanguageServerWrapper.java    From MSPaintIDE with MIT License 6 votes vote down vote up
@Override
public CompletableFuture<Void> start(File rootPath) {
    setStatus(STARTING);
    this.client = new LSPClient(this.startupLogic);

    this.rootPath = rootPath;

    try {
        var processedArgs = this.argumentPreprocessor.apply(this, new ArrayList<>(this.lspArgs));

        var streamConnectionProvider = new LSPProvider(
                () -> requestManager,
                processedArgs,
                serverPath.get());
        streamConnectionProvider.start();

        Launcher<LanguageServer> launcher =
                Launcher.createLauncher(client, LanguageServer.class, streamConnectionProvider.getInputStream(), streamConnectionProvider.getOutputStream());

        languageServer = launcher.getRemoteProxy();
        client.connect(languageServer);
        launcherFuture = launcher.startListening();

        return (startingFuture = languageServer.initialize(getInitParams()).thenApply(res -> {
            LOGGER.info("Started LSP");

            requestManager = new DefaultRequestManager(this, languageServer, client, res.getCapabilities());
            setStatus(STARTED);
            requestManager.initialized(new InitializedParams());
            setStatus(INITIALIZED);
            return res;
        }).thenRun(() -> LOGGER.info("Done starting LSP!")));

    } catch (Exception e) {
        LOGGER.error("Can't launch language server for project", e);
    }

    return CompletableFuture.runAsync(() -> {});
}
 
Example #8
Source File: ServerModule.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void configure() {
	binder().bind(ExecutorService.class).toProvider(ExecutorServiceProvider.class);

	bind(LanguageServer.class).to(LanguageServerImpl.class);
	bind(IResourceServiceProvider.Registry.class).toProvider(ResourceServiceProviderServiceLoader.class);
	bind(IMultiRootWorkspaceConfigFactory.class).to(MultiRootWorkspaceConfigFactory.class);
	bind(IProjectDescriptionFactory.class).to(DefaultProjectDescriptionFactory.class);
	bind(IContainer.Manager.class).to(ProjectDescriptionBasedContainerManager.class);
}
 
Example #9
Source File: RuntimeServerModule.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    binder().bind(ExecutorService.class).toProvider(ExecutorServiceProvider.class);

    bind(UriExtensions.class).toInstance(new MappingUriExtensions(ConfigConstants.getConfigFolder()));
    bind(LanguageServer.class).to(LanguageServerImpl.class);
    bind(IResourceServiceProvider.Registry.class).toProvider(new RegistryProvider(scriptServiceUtil, scriptEngine));
    bind(IWorkspaceConfigFactory.class).to(ProjectWorkspaceConfigFactory.class);
    bind(IProjectDescriptionFactory.class).to(DefaultProjectDescriptionFactory.class);
    bind(IContainer.Manager.class).to(ProjectDescriptionBasedContainerManager.class);
    bind(ILanguageServerShutdownAndExitHandler.class).to(ILanguageServerShutdownAndExitHandler.NullImpl.class);
}
 
Example #10
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 #11
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 #12
Source File: NullResponseTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testNullResponse() throws InterruptedException, ExecutionException {
	LogMessageAccumulator logMessages = new LogMessageAccumulator();
	try {
		logMessages.registerTo(GenericEndpoint.class);
		
		Endpoint endpoint = ServiceEndpoints.toEndpoint(this);
		Map<String, JsonRpcMethod> methods = ServiceEndpoints.getSupportedMethods(LanguageServer.class);
		MessageJsonHandler handler = new MessageJsonHandler(methods);
		List<Message> msgs = new ArrayList<>();
		MessageConsumer consumer = (message) -> {
			msgs.add(message);
		};
		RemoteEndpoint re = new RemoteEndpoint(consumer, endpoint);
		
		RequestMessage request = new RequestMessage();
		request.setId("1");
		request.setMethod("shutdown");
		re.consume(request);
		Assert.assertEquals("{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"result\":null}", handler.serialize(msgs.get(0)));
		msgs.clear();
		shutdownReturn = new Object();
		re.consume(request);
		Assert.assertEquals("{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"result\":{}}", handler.serialize(msgs.get(0)));
	} finally {
		logMessages.unregister();
	}
}
 
Example #13
Source File: LSPLauncher.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a new Launcher for a language client and an input and output stream. Threads are started with the given
 * executor service. The wrapper function is applied to the incoming and outgoing message streams so additional
 * message handling such as validation and tracing can be included.
 * 
 * @param client - the client that receives method calls from the remote server
 * @param in - input stream to listen for incoming messages
 * @param out - output stream to send outgoing messages
 * @param executorService - the executor service used to start threads
 * @param wrapper - a function for plugging in additional message consumers
 */
public static Launcher<LanguageServer> createClientLauncher(LanguageClient client, InputStream in, OutputStream out,
		ExecutorService executorService, Function<MessageConsumer, MessageConsumer> wrapper) {
	return new Builder<LanguageServer>()
			.setLocalService(client)
			.setRemoteInterface(LanguageServer.class)
			.setInput(in)
			.setOutput(out)
			.setExecutorService(executorService)
			.wrapMessages(wrapper)
			.create();
}
 
Example #14
Source File: LSPLauncher.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a new Launcher for a language server and an input and output stream, and set up message validation and tracing.
 * 
 * @param server - the server that receives method calls from the remote client
 * @param in - input stream to listen for incoming messages
 * @param out - output stream to send outgoing messages
 * @param validate - whether messages should be validated with the {@link ReflectiveMessageValidator}
 * @param trace - a writer to which incoming and outgoing messages are traced, or {@code null} to disable tracing
 */
public static Launcher<LanguageClient> createServerLauncher(LanguageServer server, InputStream in, OutputStream out,
		boolean validate, PrintWriter trace) {
	return new Builder<LanguageClient>()
			.setLocalService(server)
			.setRemoteInterface(LanguageClient.class)
			.setInput(in)
			.setOutput(out)
			.validateMessages(validate)
			.traceMessages(trace)
			.create();
}
 
Example #15
Source File: Snippet.java    From corrosion with Eclipse Public License 2.0 5 votes vote down vote up
private static LanguageServer getLanguageClient(LSPDocumentInfo info) {
	try {
		return info.getInitializedLanguageClient().get();
	} catch (InterruptedException | ExecutionException e) {
		CorrosionPlugin.logError(e);
		return null;
	}
}
 
Example #16
Source File: LSPLauncher.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a new Launcher for a language server and an input and output stream.
 * 
 * @param server - the server that receives method calls from the remote client
 * @param in - input stream to listen for incoming messages
 * @param out - output stream to send outgoing messages
 */
public static Launcher<LanguageClient> createServerLauncher(LanguageServer server, InputStream in, OutputStream out) {
	return new Builder<LanguageClient>()
			.setLocalService(server)
			.setRemoteInterface(LanguageClient.class)
			.setInput(in)
			.setOutput(out)
			.create();
}
 
Example #17
Source File: DefaultRequestManager.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
public DefaultRequestManager(LanguageServerWrapper wrapper, LanguageServer server, LanguageClient client,
                             ServerCapabilities serverCapabilities) {

    this.wrapper = wrapper;
    this.server = server;
    this.client = client;
    this.serverCapabilities = serverCapabilities;

    textDocumentOptions = serverCapabilities.getTextDocumentSync().isRight() ?
            serverCapabilities.getTextDocumentSync().getRight() : null;
    workspaceService = server.getWorkspaceService();
    textDocumentService = server.getTextDocumentService();
}
 
Example #18
Source File: LSPLauncher.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a new Launcher for a language server and an input and output stream. Threads are started with the given
 * executor service. The wrapper function is applied to the incoming and outgoing message streams so additional
 * message handling such as validation and tracing can be included.
 * 
 * @param server - the server that receives method calls from the remote client
 * @param in - input stream to listen for incoming messages
 * @param out - output stream to send outgoing messages
 * @param executorService - the executor service used to start threads
 * @param wrapper - a function for plugging in additional message consumers
 */
public static Launcher<LanguageClient> createServerLauncher(LanguageServer server, InputStream in, OutputStream out,
		ExecutorService executorService, Function<MessageConsumer, MessageConsumer> wrapper) {
	return new Builder<LanguageClient>()
			.setLocalService(server)
			.setRemoteInterface(LanguageClient.class)
			.setInput(in)
			.setOutput(out)
			.setExecutorService(executorService)
			.wrapMessages(wrapper)
			.create();
}
 
Example #19
Source File: LSPLauncher.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a new Launcher for a language client and an input and output stream.
 * 
 * @param client - the client that receives method calls from the remote server
 * @param in - input stream to listen for incoming messages
 * @param out - output stream to send outgoing messages
 */
public static Launcher<LanguageServer> createClientLauncher(LanguageClient client, InputStream in, OutputStream out) {
	return new Builder<LanguageServer>()
			.setLocalService(client)
			.setRemoteInterface(LanguageServer.class)
			.setInput(in)
			.setOutput(out)
			.create();
}
 
Example #20
Source File: RuntimeServerModule.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    binder().bind(ExecutorService.class).toProvider(ExecutorServiceProvider.class);

    bind(UriExtensions.class).toInstance(new MappingUriExtensions(ConfigConstants.getConfigFolder()));
    bind(LanguageServer.class).to(LanguageServerImpl.class);
    bind(IResourceServiceProvider.Registry.class).toProvider(new RegistryProvider(scriptServiceUtil, scriptEngine));
    bind(IWorkspaceConfigFactory.class).to(ProjectWorkspaceConfigFactory.class);
    bind(IProjectDescriptionFactory.class).to(DefaultProjectDescriptionFactory.class);
    bind(IContainer.Manager.class).to(ProjectDescriptionBasedContainerManager.class);
}
 
Example #21
Source File: LSPLauncher.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a new Launcher for a language client and an input and output stream, and set up message validation and tracing.
 * 
 * @param client - the client that receives method calls from the remote server
 * @param in - input stream to listen for incoming messages
 * @param out - output stream to send outgoing messages
 * @param validate - whether messages should be validated with the {@link ReflectiveMessageValidator}
 * @param trace - a writer to which incoming and outgoing messages are traced, or {@code null} to disable tracing
 */
public static Launcher<LanguageServer> createClientLauncher(LanguageClient client, InputStream in, OutputStream out,
		boolean validate, PrintWriter trace) {
	return new Builder<LanguageServer>()
			.setLocalService(client)
			.setRemoteInterface(LanguageServer.class)
			.setInput(in)
			.setOutput(out)
			.validateMessages(validate)
			.traceMessages(trace)
			.create();
}
 
Example #22
Source File: SocketServerLauncher.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	Injector injector = Guice.createInjector(new ServerModule());
	LanguageServer languageServer = injector.getInstance(LanguageServer.class);
	ServerSocketChannel serverSocket = ServerSocketChannel.open();
	serverSocket.bind(new InetSocketAddress("localhost", 5007));
	SocketChannel socketChannel = serverSocket.accept();
	Launcher<LanguageClient> launcher = LSPLauncher.createServerLauncher(languageServer, Channels.newInputStream(socketChannel), Channels.newOutputStream(socketChannel), true, new PrintWriter(System.out));
	launcher.startListening().get();
}
 
Example #23
Source File: TestLSPIntegration.java    From corrosion with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testLSFound()
		throws IOException, CoreException, InterruptedException, ExecutionException, TimeoutException {
	IProject project = getProject(BASIC_PROJECT_NAME);
	IFile rustFile = project.getFolder("src").getFile("main.rs");
	CompletableFuture<LanguageServer> languageServer = LanguageServiceAccessor
			.getInitializedLanguageServers(rustFile, capabilities -> capabilities.getHoverProvider() != null)
			.iterator().next();
	String uri = rustFile.getLocationURI().toString();
	Either<List<CompletionItem>, CompletionList> completionItems = languageServer.get(1, TimeUnit.MINUTES)
			.getTextDocumentService()
			.completion(new CompletionParams(new TextDocumentIdentifier(uri), new Position(1, 4)))
			.get(1, TimeUnit.MINUTES);
	Assert.assertNotNull(completionItems);
}
 
Example #24
Source File: DefaultRequestManager.java    From MSPaintIDE with MIT License 5 votes vote down vote up
public DefaultRequestManager(LanguageServerWrapper wrapper, LanguageServer server, LanguageClient client,
                             ServerCapabilities serverCapabilities) {

    this.wrapper = wrapper;
    this.server = server;
    this.client = client;
    this.serverCapabilities = serverCapabilities;

    textDocumentOptions = serverCapabilities.getTextDocumentSync().isRight() ?
            serverCapabilities.getTextDocumentSync().getRight() :
            null;
    workspaceService = server.getWorkspaceService();
    textDocumentService = server.getTextDocumentService();
}
 
Example #25
Source File: LSPBindings.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static InitializeResult initServer(Process p, LanguageServer server, FileObject root) throws InterruptedException, ExecutionException {
   InitializeParams initParams = new InitializeParams();
   initParams.setRootUri(Utils.toURI(root));
   initParams.setRootPath(FileUtil.toFile(root).getAbsolutePath()); //some servers still expect root path
   initParams.setProcessId(0);
   TextDocumentClientCapabilities tdcc = new TextDocumentClientCapabilities();
   DocumentSymbolCapabilities dsc = new DocumentSymbolCapabilities();
   dsc.setHierarchicalDocumentSymbolSupport(true);
   dsc.setSymbolKind(new SymbolKindCapabilities(Arrays.asList(SymbolKind.values())));
   tdcc.setDocumentSymbol(dsc);
   WorkspaceClientCapabilities wcc = new WorkspaceClientCapabilities();
   wcc.setWorkspaceEdit(new WorkspaceEditCapabilities());
   wcc.getWorkspaceEdit().setDocumentChanges(true);
   wcc.getWorkspaceEdit().setResourceOperations(Arrays.asList(ResourceOperationKind.Create, ResourceOperationKind.Delete, ResourceOperationKind.Rename));
   initParams.setCapabilities(new ClientCapabilities(wcc, tdcc, null));
   CompletableFuture<InitializeResult> initResult = server.initialize(initParams);
   while (true) {
       try {
           return initResult.get(100, TimeUnit.MILLISECONDS);
       } catch (TimeoutException ex) {
           if (p != null && !p.isAlive()) {
               InitializeResult emptyResult = new InitializeResult();
               emptyResult.setCapabilities(new ServerCapabilities());
               return emptyResult;
           }
       }
   }
}
 
Example #26
Source File: LSPBindings.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Messages("LBL_Connecting=Connecting to language server")
public static void addBindings(FileObject root, int port, String... extensions) {
    BaseProgressUtils.showProgressDialogAndRun(() -> {
        try {
            Socket s = new Socket(InetAddress.getLocalHost(), port);
            LanguageClientImpl lc = new LanguageClientImpl();
            InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();
            Launcher<LanguageServer> launcher = LSPLauncher.createClientLauncher(lc, in, new OutputStream() {
                @Override
                public void write(int w) throws IOException {
                    out.write(w);
                    if (w == '\n')
                        out.flush();
                }
            });
            launcher.startListening();
            LanguageServer server = launcher.getRemoteProxy();
            InitializeResult result = initServer(null, server, root);
            LSPBindings bindings = new LSPBindings(server, result, null);

            lc.setBindings(bindings);

            workspace2Extension2Server.put(root, Arrays.stream(extensions).collect(Collectors.toMap(k -> k, v -> bindings)));
        } catch (InterruptedException | ExecutionException | IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }, Bundle.LBL_Connecting());
}
 
Example #27
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);
		}
	}
}
 
Example #28
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 #29
Source File: CommandExecutor.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
private static CompletableFuture<LanguageServer> getLanguageServerForCommand(Project project,
                                                                             Command command,
                                                                             Document document, LanguageServersRegistry.LanguageServerDefinition languageServerDefinition) throws IOException {
    CompletableFuture<LanguageServer> languageServerFuture = LanguageServiceAccessor.getInstance(project)
            .getInitializedLanguageServer(document, languageServerDefinition, serverCapabilities -> {
                ExecuteCommandOptions provider = serverCapabilities.getExecuteCommandProvider();
                return provider != null && provider.getCommands().contains(command.getCommand());
            });
    return languageServerFuture;
}
 
Example #30
Source File: CommandExecutor.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean executeCommandServerSide(Project project, Command command, String languageServerId,
                                                Document document) {
    if (languageServerId == null) {
        return false;
    }
    LanguageServersRegistry.LanguageServerDefinition languageServerDefinition = LanguageServersRegistry.getInstance()
            .getDefinition(languageServerId);
    if (languageServerDefinition == null) {
        return false;
    }

    try {
        CompletableFuture<LanguageServer> languageServerFuture = getLanguageServerForCommand(project, command, document,
                languageServerDefinition);
        if (languageServerFuture == null) {
            return false;
        }
        // Server can handle command
        languageServerFuture.thenAcceptAsync(server -> {
            ExecuteCommandParams params = new ExecuteCommandParams();
            params.setCommand(command.getCommand());
            params.setArguments(command.getArguments());
            server.getWorkspaceService().executeCommand(params);
        });
        return true;
    } catch (IOException e) {
        // log and let the code fall through for LSPEclipseUtils to handle
        LOGGER.warn(e.getLocalizedMessage(), e);
        return false;
    }

}