下面列出了怎么用org.eclipse.lsp4j.services.LanguageClient的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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();
}
}
public static void main(String[] args) {
List<String> arguments = Arrays.asList(args);
if (arguments.contains(HELP_PARAMETER)) {
System.out.println(HELP_MESSAGE);
} else if (arguments.contains(WEBSOCKET_PARAMETER)) {
int port = extractPort(arguments);
String hostname = extractHostname(arguments);
webSocketRunner = new WebSocketRunner();
String contextPath = extractContextPath(arguments);
webSocketRunner.runWebSocketServer(hostname, port, contextPath);
} else {
server = new CamelLanguageServer();
Launcher<LanguageClient> launcher = LSPLauncher.createServerLauncher(server, System.in, System.out);
server.connect(launcher.getRemoteProxy());
launcher.startListening();
}
}
@Test
public void diagnosticsNoTarget() throws Exception {
RdfLintLanguageServer lsp = new RdfLintLanguageServer();
InitializeParams initParams = new InitializeParams();
String rootPath = this.getClass().getClassLoader().getResource("testValidatorsImpl/").getPath();
String parentPath = rootPath + "TrimValidator/turtle_needtrim";
initParams.setRootUri(RdfLintLanguageServer.convertFilePath2Uri(parentPath));
lsp.initialize(initParams);
LanguageClient client = mock(LanguageClient.class);
lsp.connect(client);
lsp.refreshFileTripleSet();
verify(client, never()).publishDiagnostics(any());
}
@Test
public void diagnosticsClose() throws Exception {
RdfLintLanguageServer lsp = new RdfLintLanguageServer();
InitializeParams initParams = new InitializeParams();
String rootPath = this.getClass().getClassLoader().getResource("testValidatorsImpl/").getPath();
String parentPath = rootPath + "TrimValidator/turtle_needtrim";
initParams.setRootUri(RdfLintLanguageServer.convertFilePath2Uri(parentPath));
lsp.initialize(initParams);
LanguageClient client = mock(LanguageClient.class);
lsp.connect(client);
DidCloseTextDocumentParams closeParams = new DidCloseTextDocumentParams();
closeParams.setTextDocument(new TextDocumentIdentifier());
closeParams.getTextDocument()
.setUri(RdfLintLanguageServer.convertFilePath2Uri(parentPath + "/needtrim.rdf"));
lsp.didClose(closeParams);
verify(client, times(2)).publishDiagnostics(any());
}
private void setupAndRun(ExecutorService threadPool, XLanguageServerImpl languageServer)
throws InterruptedException, ExecutionException, IOException {
Builder<LanguageClient> lsBuilder = new PatchedLauncherBuilder<LanguageClient>()
.setLocalService(languageServer)
.setRemoteInterface(LanguageClient.class)
.setExecutorService(threadPool)
.configureGson(gsonBuilder -> {
gsonBuilder.registerTypeAdapterFactory(new ExecuteCommandParamsTypeAdapter.Factory(languageServer));
})
// .traceMessages(new PrintWriter(System.out))
// .wrapMessages(a -> a)
;
if (options.isStdio()) {
setupAndRunWithSystemIO(languageServer, lsBuilder);
} else {
setupAndRunWithSocket(languageServer, lsBuilder);
}
}
private void setupAndRunWithSocket(XLanguageServerImpl languageServer, Builder<LanguageClient> lsBuilder)
throws InterruptedException, ExecutionException, IOException {
InetSocketAddress address = new InetSocketAddress("localhost", options.getPort());
try (AsynchronousServerSocketChannel serverSocket = AsynchronousServerSocketChannel.open().bind(address);) {
// Attention: the VSCode LSP extension is waiting for this line 'Listening for LSP clients'.
N4jscConsole.println(LSP_SYNC_MESSAGE + " on port " + options.getPort() + "...");
try (AsynchronousSocketChannel socketChannel = serverSocket.accept().get();
InputStream in = Channels.newInputStream(socketChannel);
OutputStream out = Channels.newOutputStream(socketChannel)) {
N4jscConsole.println("Connected to LSP client");
run(languageServer, lsBuilder, in, out);
}
}
}
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();
}
@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");
}
}
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();
}
}
@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);
}
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();
}
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();
}
@BeforeEach
void setup() {
workspaceRoot = Paths.get(System.getProperty("user.dir")).resolve(PATH_WORKSPACE);
srcRoot = workspaceRoot.resolve(PATH_SRC);
if (!Files.exists(srcRoot)) {
srcRoot.toFile().mkdirs();
}
services = new GroovyServices(new CompilationUnitFactory());
services.setWorkspaceRoot(workspaceRoot);
services.connect(new LanguageClient() {
@Override
public void telemetryEvent(Object object) {
}
@Override
public CompletableFuture<MessageActionItem> showMessageRequest(ShowMessageRequestParams requestParams) {
return null;
}
@Override
public void showMessage(MessageParams messageParams) {
}
@Override
public void publishDiagnostics(PublishDiagnosticsParams diagnostics) {
}
@Override
public void logMessage(MessageParams message) {
}
});
}
@BeforeEach
void setup() {
workspaceRoot = Paths.get(System.getProperty("user.dir")).resolve(PATH_WORKSPACE);
srcRoot = workspaceRoot.resolve(PATH_SRC);
if (!Files.exists(srcRoot)) {
srcRoot.toFile().mkdirs();
}
services = new GroovyServices(new CompilationUnitFactory());
services.setWorkspaceRoot(workspaceRoot);
services.connect(new LanguageClient() {
@Override
public void telemetryEvent(Object object) {
}
@Override
public CompletableFuture<MessageActionItem> showMessageRequest(ShowMessageRequestParams requestParams) {
return null;
}
@Override
public void showMessage(MessageParams messageParams) {
}
@Override
public void publishDiagnostics(PublishDiagnosticsParams diagnostics) {
}
@Override
public void logMessage(MessageParams message) {
}
});
}
@BeforeEach
void setup() {
workspaceRoot = Paths.get(System.getProperty("user.dir")).resolve(PATH_WORKSPACE);
srcRoot = workspaceRoot.resolve(PATH_SRC);
if (!Files.exists(srcRoot)) {
srcRoot.toFile().mkdirs();
}
services = new GroovyServices(new CompilationUnitFactory());
services.setWorkspaceRoot(workspaceRoot);
services.connect(new LanguageClient() {
@Override
public void telemetryEvent(Object object) {
}
@Override
public CompletableFuture<MessageActionItem> showMessageRequest(ShowMessageRequestParams requestParams) {
return null;
}
@Override
public void showMessage(MessageParams messageParams) {
}
@Override
public void publishDiagnostics(PublishDiagnosticsParams diagnostics) {
}
@Override
public void logMessage(MessageParams message) {
}
});
}
@BeforeEach
void setup() {
workspaceRoot = Paths.get(System.getProperty("user.dir")).resolve(PATH_WORKSPACE);
srcRoot = workspaceRoot.resolve(PATH_SRC);
if (!Files.exists(srcRoot)) {
srcRoot.toFile().mkdirs();
}
services = new GroovyServices(new CompilationUnitFactory());
services.setWorkspaceRoot(workspaceRoot);
services.connect(new LanguageClient() {
@Override
public void telemetryEvent(Object object) {
}
@Override
public CompletableFuture<MessageActionItem> showMessageRequest(ShowMessageRequestParams requestParams) {
return null;
}
@Override
public void showMessage(MessageParams messageParams) {
}
@Override
public void publishDiagnostics(PublishDiagnosticsParams diagnostics) {
}
@Override
public void logMessage(MessageParams message) {
}
});
}
/**
* 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();
}
@Test
public void diagnosticsOpen() throws Exception {
RdfLintLanguageServer lsp = new RdfLintLanguageServer();
InitializeParams initParams = new InitializeParams();
String rootPath = this.getClass().getClassLoader().getResource("testValidatorsImpl/").getPath();
String parentPath = rootPath + "TrimValidator/turtle_needtrim";
initParams.setRootUri(RdfLintLanguageServer.convertFilePath2Uri(parentPath));
lsp.initialize(initParams);
LanguageClient client = mock(LanguageClient.class);
lsp.connect(client);
DidOpenTextDocumentParams openParams = new DidOpenTextDocumentParams();
openParams.setTextDocument(new TextDocumentItem());
openParams.getTextDocument()
.setUri(RdfLintLanguageServer.convertFilePath2Uri(parentPath + "/needtrim.rdf"));
openParams.getTextDocument().setText("<rdf:RDF\n"
+ " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n"
+ " xmlns:schema=\"http://schema.org/\"\n"
+ " >\n"
+ "\n"
+ " <rdf:Description rdf:about=\"something\">\n"
+ " <schema:familyName xml:lang=\"ja\">familyName </schema:familyName>\n"
+ " </rdf:Description>\n"
+ "\n"
+ "</rdf:RDF>");
lsp.didOpen(openParams);
verify(client, times(1)).publishDiagnostics(any());
}
@Test
public void diagnosticsChange() throws Exception {
RdfLintLanguageServer lsp = new RdfLintLanguageServer();
InitializeParams initParams = new InitializeParams();
String rootPath = this.getClass().getClassLoader().getResource("testValidatorsImpl/").getPath();
String parentPath = rootPath + "TrimValidator/turtle_needtrim";
initParams.setRootUri(RdfLintLanguageServer.convertFilePath2Uri(parentPath));
lsp.initialize(initParams);
LanguageClient client = mock(LanguageClient.class);
lsp.connect(client);
DidChangeTextDocumentParams changeParams = new DidChangeTextDocumentParams();
changeParams.setTextDocument(new VersionedTextDocumentIdentifier());
changeParams.getTextDocument()
.setUri(RdfLintLanguageServer.convertFilePath2Uri(parentPath + "/needtrim.rdf"));
List<TextDocumentContentChangeEvent> changeEvents = new LinkedList<>();
changeParams.setContentChanges(changeEvents);
changeEvents.add(new TextDocumentContentChangeEvent());
changeEvents.get(0).setText("<rdf:RDF\n"
+ " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n"
+ " xmlns:schema=\"http://schema.org/\"\n"
+ " >\n"
+ "\n"
+ " <rdf:Description rdf:about=\"something\">\n"
+ " <schema:familyName xml:lang=\"ja\">familyName </schema:familyName>\n"
+ " </rdf:Description>\n"
+ "\n"
+ "</rdf:RDF>");
lsp.didChange(changeParams);
verify(client, times(1)).publishDiagnostics(any());
}
@Test
public void diagnosticsChangeParseError() throws Exception {
RdfLintLanguageServer lsp = new RdfLintLanguageServer();
InitializeParams initParams = new InitializeParams();
String rootPath = this.getClass().getClassLoader().getResource("testValidatorsImpl/").getPath();
String parentPath = rootPath + "TrimValidator/turtle_needtrim";
initParams.setRootUri(RdfLintLanguageServer.convertFilePath2Uri(parentPath));
lsp.initialize(initParams);
LanguageClient client = mock(LanguageClient.class);
lsp.connect(client);
DidChangeTextDocumentParams changeParams = new DidChangeTextDocumentParams();
changeParams.setTextDocument(new VersionedTextDocumentIdentifier());
changeParams.getTextDocument()
.setUri(RdfLintLanguageServer.convertFilePath2Uri(parentPath + "/needtrim.rdf"));
List<TextDocumentContentChangeEvent> changeEvents = new LinkedList<>();
changeParams.setContentChanges(changeEvents);
changeEvents.add(new TextDocumentContentChangeEvent());
changeEvents.get(0).setText("<rdf:RDF\n"
+ " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n"
+ " xmlns:schema=\"http://schema.org/\"\n"
+ " >\n"
+ "\n"
+ " <rdf:Description rdf:about=\"something\">\n"
+ " <schema:familyName xml:lang=\"ja\">familyName</schema:familyN>\n"
+ " </rdf:Description>\n"
+ "\n"
+ "</rdf:RDF>");
lsp.didChange(changeParams);
verify(client, times(1)).publishDiagnostics(any());
}
@SuppressWarnings("hiding")
@Override
public void connect(LanguageClient client) {
this.client = client;
issueAcceptor.connect(client);
lspLogger.connect(client);
}
private Void doOrganizeImports(String uriString, ILanguageServerAccess.Context context,
LanguageClient languageClient, CancelIndicator cancelIndicator) {
Resource resource = context.getResource();
if (!(resource instanceof N4JSResource)) {
return null;
}
Script script = ((N4JSResource) resource).getScript();
Document document = context.getDocument();
// compute imports to be added for unresolved references
List<ImportDescriptor> importsToBeAdded = new ArrayList<>();
List<ReferenceResolution> resolutions = importHelper
.findResolutionsForAllUnresolvedReferences(script, cancelIndicator);
for (ReferenceResolution resolution : resolutions) {
if (resolution.importToBeAdded != null) {
importsToBeAdded.add(resolution.importToBeAdded);
}
}
// organize all imports (existing and new ones)
List<TextEdit> edits = importOrganizer.organizeImports(document, script, importsToBeAdded, cancelIndicator);
WorkspaceEdit workspaceEdit = new WorkspaceEdit(Collections.singletonMap(uriString, edits));
ApplyWorkspaceEditParams params = new ApplyWorkspaceEditParams(workspaceEdit, "Organize Imports");
languageClient.applyEdit(params);
return null;
}
/** */
public void log(String messageString, MessageType type) {
final LanguageClient lc = this.languageClient;
if (lc == null) {
return;
}
MessageParams message = new MessageParams();
message.setMessage(messageString);
message.setType(type);
lc.logMessage(message);
}
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
}
}
}
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();
}
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();
}
public void initialize(Iterable<? extends IResourceServiceProvider> allLanguages, ClientCapabilities capabilities,
LanguageClient client) {
this.client = client;
this.registeredCommands = HashMultimap.create();
boolean hasDynamicRegistration = false;
WorkspaceClientCapabilities workspace = capabilities.getWorkspace();
if (workspace != null) {
ExecuteCommandCapabilities executeCommandCapabilities = workspace.getExecuteCommand();
if (executeCommandCapabilities != null) {
Boolean dynamicRegistration = executeCommandCapabilities.getDynamicRegistration();
if (dynamicRegistration != null) {
hasDynamicRegistration = dynamicRegistration.booleanValue();
}
}
}
for (IResourceServiceProvider lang : allLanguages) {
IExecutableCommandService service = lang.get(IExecutableCommandService.class);
if (service != null) {
List<String> commands = service.initialize();
for (String c : commands) {
registeredCommands.put(c, service);
}
if (hasDynamicRegistration) {
service.initializeDynamicRegistration((String command) -> {
return register(command, service);
});
}
}
}
}
/**
* 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();
}
/**
* 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();
}
/**
* 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();
}