Java Code Examples for org.eclipse.lsp4j.jsonrpc.Launcher#startListening()

The following examples show how to use org.eclipse.lsp4j.jsonrpc.Launcher#startListening() . 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: XMLServerSocketLauncher.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Launches {@link XMLLanguageServer} using asynchronous server-socket channel and makes it accessible through the JSON
 * RPC protocol defined by the LSP.
 * 
 * @param args standard launch arguments. may contain <code>--port</code> argument to change the default port 5008
 */
public void launch(String[] args) throws Exception {
	AsynchronousServerSocketChannel _open = AsynchronousServerSocketChannel.open();
	int _port = getPort(args);
	InetSocketAddress _inetSocketAddress = new InetSocketAddress("0.0.0.0", _port);
	final AsynchronousServerSocketChannel serverSocket = _open.bind(_inetSocketAddress);
	while (true) {
		final AsynchronousSocketChannel socketChannel = serverSocket.accept().get();
		final InputStream in = Channels.newInputStream(socketChannel);
		final OutputStream out = Channels.newOutputStream(socketChannel);
		final ExecutorService executorService = Executors.newCachedThreadPool();
		XMLLanguageServer languageServer = new XMLLanguageServer();
		final Launcher<LanguageClient> launcher = Launcher.createIoLauncher(languageServer, LanguageClient.class,
				in, out, executorService, (MessageConsumer it) -> {
					return it;
				});
		languageServer.setClient(launcher.getRemoteProxy());
		launcher.startListening();
	}
}
 
Example 2
Source File: LauncherTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testCanceled() throws Exception {
	A a = new A() {
		@Override
		public void say(Param p) {
		}
	};
	Launcher<A> launcher = Launcher.createLauncher(a, A.class, new InputStream() {
		@Override
		public int read() throws IOException {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
			return '\n';
		}
	}, new ByteArrayOutputStream());
	Future<?> startListening = launcher.startListening();
	startListening.cancel(true);
	Assert.assertTrue(startListening.isDone());
	Assert.assertTrue(startListening.isCancelled());
}
 
Example 3
Source File: DebugLauncherTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testCanceled() throws Exception {
	A a = new A() {
		@Override
		public void say(Param p) {
		}
	};
	Launcher<A> launcher = DebugLauncher.createLauncher(a, A.class, new InputStream() {
		@Override
		public int read() throws IOException {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
			return '\n';
		}
	}, new ByteArrayOutputStream());
	Future<?> startListening = launcher.startListening();
	startListening.cancel(true);
	Assert.assertTrue(startListening.isDone());
	Assert.assertTrue(startListening.isCancelled());
}
 
Example 4
Source File: LspServer.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private void run(XLanguageServerImpl languageServer, Builder<LanguageClient> lsBuilder, InputStream in,
		OutputStream out) {

	Launcher<LanguageClient> launcher = lsBuilder
			.setInput(in)
			.setOutput(out)
			.create();

	languageServer.connect(launcher.getRemoteProxy());
	Future<Void> future = launcher.startListening();
	N4jscConsole.println("LSP Server connected");

	Futures.getUnchecked(future);

	N4jscConsole.println("Shutdown connection to LSP client");
	languageServer.getLSPExecutorService().shutdown();
}
 
Example 5
Source File: TeiidDdlLanguageServerRunner.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"try", "FutureReturnValueIgnored"})
public static void main(String[] args) throws DeploymentException, InterruptedException {
    LOGGER.info("   --  >>>  TeiidDdlLanguageServerRunner.main()");
    List<String> arguments = Arrays.asList(args);
    if (arguments.contains(WEBSOCKET_PARAMETER)) {
        LOGGER.info("   --  >>>  Started Teiid LS as WEB SOCKET");
        int port = extractPort(arguments);
        String hostname = extractHostname(arguments);
        String contextPath = extractContextPath(arguments);
        try (TeiidDdlWebSocketRunner runner = new TeiidDdlWebSocketRunner(hostname, port, contextPath);) {
            Thread.currentThread().join();
        }
    } else {
        LOGGER.info("   --  >>>  Started Teiid LS as JAVA SERVER");
        server = new TeiidDdlLanguageServer(null);

        Launcher<LanguageClient> launcher = LSPLauncher.createServerLauncher(server, System.in, System.out);

        server.connect(launcher.getRemoteProxy());

        launcher.startListening();
        LOGGER.info("   --  >>>  Teiid LS Started. launch listening started");
    }
}
 
Example 6
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 7
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 8
Source File: SocketServerLauncher.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public void launch(String[] args) {
	Injector injector = Guice.createInjector(getServerModule());
	try (AsynchronousServerSocketChannel serverSocket = AsynchronousServerSocketChannel.open()
			.bind(getSocketAddress(args))) {
		LOG.info("Started server socket at " + getSocketAddress(args));
		while (true) {
			AsynchronousSocketChannel socketChannel = serverSocket.accept().get();
			InputStream in = Channels.newInputStream(socketChannel);
			OutputStream out = Channels.newOutputStream(socketChannel);
			PrintWriter trace = getTrace(args);
			boolean validate = shouldValidate(args);
			LanguageServerImpl languageServer = injector.getInstance(LanguageServerImpl.class);
			LOG
					.info("Starting Xtext Language Server for client " + socketChannel.getRemoteAddress());
			Launcher<LanguageClient> launcher = Launcher.createLauncher(languageServer, LanguageClient.class, in,
					out, validate, trace);
			languageServer.connect(launcher.getRemoteProxy());
			launcher.startListening();
			LOG.info("Xtext Language Server has been started.");
		}
	} catch (Throwable t) {
		t.printStackTrace();
	}
}
 
Example 9
Source File: ProtocolTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * creates a proxy, delegating to a remote endpoint, forwarding to another remote endpoint, that delegates to an actual implementation.
 * @param intf
 * @param impl
 * @return
 * @throws IOException 
 */
public <T> T wrap(Class<T> intf, T impl) {
	PipedInputStream in1 = new PipedInputStream();
	PipedOutputStream out1 = new PipedOutputStream();
	Launcher<T> launcher1 = Launcher.createLauncher(impl, intf, in1, out1);
	
	PipedInputStream in2 = new PipedInputStream();
	PipedOutputStream out2 = new PipedOutputStream();
	Launcher<T> launcher2 = Launcher.createLauncher(new Object(), intf, in2, out2);
	try {
		in1.connect(out2);
		in2.connect(out1);
	} catch (IOException e) {
		throw new IllegalStateException(e);
	}
	launcher1.startListening();
	launcher2.startListening();
	return launcher2.getRemoteProxy();
}
 
Example 10
Source File: IntegrationTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testBothDirectionRequests() throws Exception {
	// create client side
	PipedInputStream in = new PipedInputStream();
	PipedOutputStream out = new PipedOutputStream();
	PipedInputStream in2 = new PipedInputStream();
	PipedOutputStream out2 = new PipedOutputStream();
	
	in.connect(out2);
	out.connect(in2);
	
	MyClient client = new MyClientImpl();
	Launcher<MyServer> clientSideLauncher = Launcher.createLauncher(client, MyServer.class, in, out);
	
	// create server side
	MyServer server = new MyServerImpl();
	Launcher<MyClient> serverSideLauncher = Launcher.createLauncher(server, MyClient.class, in2, out2);
	
	clientSideLauncher.startListening();
	serverSideLauncher.startListening();
	
	CompletableFuture<MyParam> fooFuture = clientSideLauncher.getRemoteProxy().askServer(new MyParam("FOO"));
	CompletableFuture<MyParam> barFuture = serverSideLauncher.getRemoteProxy().askClient(new MyParam("BAR"));
	
	Assert.assertEquals("FOO", fooFuture.get(TIMEOUT, TimeUnit.MILLISECONDS).value);
	Assert.assertEquals("BAR", barFuture.get(TIMEOUT, TimeUnit.MILLISECONDS).value);
}
 
Example 11
Source File: GroovyLanguageServer.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    GroovyLanguageServer server = new GroovyLanguageServer();
    Launcher<LanguageClient> launcher = Launcher.createLauncher(server, LanguageClient.class, System.in,
            System.out);
    server.connect(launcher.getRemoteProxy());
    launcher.startListening();
}
 
Example 12
Source File: IntegrationTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testUnknownMessages() throws Exception {
	// intercept log messages
	LogMessageAccumulator logMessages = new LogMessageAccumulator();
	try {
		logMessages.registerTo(GenericEndpoint.class);
		
		// create client messages
		String clientMessage1 = "{\"jsonrpc\": \"2.0\",\n"
				+ "\"method\": \"foo1\",\n" 
				+ "\"params\": \"bar\"\n"
				+ "}";
		String clientMessage2 = "{\"jsonrpc\": \"2.0\",\n"
				+ "\"id\": \"1\",\n" 
				+ "\"method\": \"foo2\",\n" 
				+ "\"params\": \"bar\"\n"
				+ "}";
		String clientMessages = getHeader(clientMessage1.getBytes().length) + clientMessage1
				+ getHeader(clientMessage2.getBytes().length) + clientMessage2;
		
		// create server side
		ByteArrayInputStream in = new ByteArrayInputStream(clientMessages.getBytes());
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		MyServer server = new MyServerImpl();
		Launcher<MyClient> serverSideLauncher = Launcher.createLauncher(server, MyClient.class, in, out);
		serverSideLauncher.startListening();
		
		logMessages.await(Level.WARNING, "Unsupported notification method: foo1");
		logMessages.await(Level.WARNING, "Unsupported request method: foo2");
		
		Assert.assertEquals("Content-Length: 95" + CRLF + CRLF
				+ "{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"error\":{\"code\":-32601,\"message\":\"Unsupported request method: foo2\"}}",
				out.toString());
	} finally {
		logMessages.unregister();
	}
}
 
Example 13
Source File: LauncherTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testDone() throws Exception {
	A a = new A() {
		@Override
		public void say(Param p) {
		}
	};
	Launcher<A> launcher = Launcher.createLauncher(a, A.class, new ByteArrayInputStream("".getBytes()), new ByteArrayOutputStream());
	Future<?> startListening = launcher.startListening();
	startListening.get(TIMEOUT, TimeUnit.MILLISECONDS);
	Assert.assertTrue(startListening.isDone());
	Assert.assertFalse(startListening.isCancelled());
}
 
Example 14
Source File: DebugIntegrationTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testUnexpectedParams() throws Exception {
	// intercept log messages
	LogMessageAccumulator logMessages = new LogMessageAccumulator();
	try {
		logMessages.registerTo(GenericEndpoint.class.getName());

		// create client messages
		String notificationMessage = "{\"type\":\"event\","
				+ "\"event\":\"myNotification\",\n"
				+ "\"body\": { \"value\": \"foo\" }\n"
				+ "}";
		String clientMessages = getHeader(notificationMessage.getBytes().length) + notificationMessage;

		// create server side
		ByteArrayInputStream in = new ByteArrayInputStream(clientMessages.getBytes());
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		UnexpectedParamsTestServer server = new UnexpectedParamsTestServer() {
			public void myNotification() {
			}
		};
		Launcher<MyClient> serverSideLauncher = DebugLauncher.createLauncher(server, MyClient.class, in, out);
		serverSideLauncher.startListening();

		logMessages.await(Level.WARNING, "Unexpected params '{\"value\":\"foo\"}' for " + "'public abstract void "
				+ UnexpectedParamsTestServer.class.getName() + ".myNotification()' is ignored");
	} finally {
		logMessages.unregister();
	}
}
 
Example 15
Source File: IntegrationTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMalformedJson2() throws Exception {
	// intercept log messages
	LogMessageAccumulator logMessages = new LogMessageAccumulator();
	try {
		logMessages.registerTo(StreamMessageProducer.class);
		
		String requestMessage1 = "{\"jsonrpc\": \"2.0\",\n"
				+ "\"params\": { \"value\": }\n"
				+ "\"id\": \"1\",\n" 
				+ "\"method\":\"askServer\",\n" 
				+ "}";
		String requestMessage2 = "{\"jsonrpc\": \"2.0\",\n"
				+ "\"id\": \"2\",\n" 
				+ "\"method\": \"askServer\",\n" 
				+ "\"params\": { \"value\": \"bar\" }\n"
				+ "}";
		String clientMessages = getHeader(requestMessage1.getBytes().length) + requestMessage1
				+ getHeader(requestMessage2.getBytes().length) + requestMessage2;
		
		ByteArrayInputStream in = new ByteArrayInputStream(clientMessages.getBytes());
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		MyServer server = new MyServerImpl();
		Launcher<MyClient> serverSideLauncher = Launcher.createLauncher(server, MyClient.class, in, out);
		serverSideLauncher.startListening();
		
		logMessages.await(Level.SEVERE, "com.google.gson.stream.MalformedJsonException: Expected value at line 2 column 22 path $.params.value");
		Assert.assertEquals("Content-Length: 51" + CRLF + CRLF
				+ "{\"jsonrpc\":\"2.0\",\"id\":\"2\",\"result\":{\"value\":\"bar\"}}",
				out.toString());
	} finally {
		logMessages.unregister();
	}
}
 
Example 16
Source File: Server.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void run(InputStream in, OutputStream out) throws Exception {
    LanguageServerImpl server = new LanguageServerImpl();
    Launcher<LanguageClient> serverLauncher = LSPLauncher.createServerLauncher(server, in, out);
    ((LanguageClientAware) server).connect(serverLauncher.getRemoteProxy());
    serverLauncher.startListening();

    while (true) {
        try {
            Thread.sleep(100000);
        } catch (InterruptedException ex) {
            //ignore
        }
    }
}
 
Example 17
Source File: XMLServerLauncher.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Launches {@link XMLLanguageServer} and makes it accessible through the JSON
 * RPC protocol defined by the LSP.
 * 
 * @param launcherFuture The future returned by
 *                       {@link org.eclipse.lsp4j.jsonrpc.Launcher#startListening()}.
 *                       (I'm not 100% sure how it meant to be used though, as
 *                       it's undocumented...)
 */
public static Future<?> launch(InputStream in, OutputStream out) {
	XMLLanguageServer server = new XMLLanguageServer();
	Function<MessageConsumer, MessageConsumer> wrapper;
	if ("false".equals(System.getProperty("watchParentProcess"))) {
		wrapper = it -> it;
	} else {
		wrapper = new ParentProcessWatcher(server);
	}
	Launcher<LanguageClient> launcher = createServerLauncher(server, in, out, Executors.newCachedThreadPool(), wrapper);
	server.setClient(launcher.getRemoteProxy());
	return launcher.startListening();
}
 
Example 18
Source File: IntegrationTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testUnexpectedParams() throws Exception {
	// intercept log messages
	LogMessageAccumulator logMessages = new LogMessageAccumulator();
	try {
		logMessages.registerTo(GenericEndpoint.class);
		
		// create client messages
		String notificationMessage = "{\"jsonrpc\": \"2.0\",\n"
				+ "\"method\": \"myNotification\",\n" 
				+ "\"params\": { \"value\": \"foo\" }\n"
				+ "}";
		String clientMessages = getHeader(notificationMessage.getBytes().length) + notificationMessage;
		
		// create server side
		ByteArrayInputStream in = new ByteArrayInputStream(clientMessages.getBytes());
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		UnexpectedParamsTestServer server = new UnexpectedParamsTestServer() {
			public void myNotification() {
			}
		};
		Launcher<MyClient> serverSideLauncher = Launcher.createLauncher(server, MyClient.class, in, out);
		serverSideLauncher.startListening();
		
		logMessages.await(Level.WARNING, "Unexpected params '{\"value\":\"foo\"}' for "
				+ "'public abstract void org.eclipse.lsp4j.jsonrpc.test.IntegrationTest$UnexpectedParamsTestServer.myNotification()' is ignored");
	} finally {
		logMessages.unregister();
	}
}
 
Example 19
Source File: DebugIntegrationTest.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testUnknownOptionalMessages() throws Exception {
	// intercept log messages
	LogMessageAccumulator logMessages = new LogMessageAccumulator();
	try {
		logMessages.registerTo(GenericEndpoint.class.getName());

		// create client messages
		String clientMessage1 = "{\"type\":\"event\","
				+ "\"event\":\"$/foo1\",\n"
				+ " \"body\":\"bar\"\n"
				+ "}";
		String clientMessage2 = "{\"type\":\"request\","
				+ "\"seq\":1,\n"
				+ "\"command\":\"$/foo2\",\n"
				+ " \"arguments\":\"bar\"\n"
				+ "}";
		String clientMessages = getHeader(clientMessage1.getBytes().length) + clientMessage1
				+ getHeader(clientMessage2.getBytes().length) + clientMessage2;

		// 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 CompletableFuture.completedFuture(param);
			}
		};
		Launcher<MyClient> serverSideLauncher = DebugLauncher.createLauncher(server, MyClient.class, in, out);
		serverSideLauncher.startListening();

		logMessages.await(Level.INFO, "Unsupported notification method: $/foo1");
		logMessages.await(Level.INFO, "Unsupported request method: $/foo2");

		Assert.assertEquals("Content-Length: 77\r\n\r\n" +
				"{\"type\":\"response\",\"seq\":1,\"request_seq\":1,\"command\":\"$/foo2\",\"success\":true}",
				out.toString());
	} finally {
		logMessages.unregister();
	}
}
 
Example 20
Source File: SarosLauncher.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Starts the server.
 *
 * @param args command-line arguments
 * @throws Exception on critical failures
 */
public static void main(String[] args) throws Exception {

  if (args.length > 1) {
    throw new IllegalArgumentException("wrong number of arguments");
  } else if (args.length != 1) {
    throw new IllegalArgumentException("port parameter not supplied");
  } else if (!args[0].matches("\\d+")) {
    throw new IllegalArgumentException("port is not a number");
  }

  URL log4jProperties = SarosLauncher.class.getResource(LOGGING_CONFIG_FILE);
  PropertyConfigurator.configure(log4jProperties);

  log.addAppender(new ConsoleAppender());

  int port = Integer.parseInt(args[0]);
  Socket socket = new Socket("localhost", port);

  log.info("listening on port " + port);

  Runtime.getRuntime()
      .addShutdownHook(
          new Thread() {
            public void run() {
              try {
                socket.close();
              } catch (IOException e) {
                // NOP
              }
            }
          });

  SarosLanguageServer langSvr = new SarosLanguageServer();
  Launcher<ISarosLanguageClient> l =
      Launcher.createLauncher(
          langSvr, ISarosLanguageClient.class, socket.getInputStream(), socket.getOutputStream());

  ISarosLanguageClient langClt = l.getRemoteProxy();
  log.addAppender(new LanguageClientAppender(langClt));
  langSvr.connect(langClt);

  l.startListening();
}