下面列出了怎么用org.eclipse.lsp4j.jsonrpc.Endpoint的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @param out
* a consumer that transmits messages to the remote service
* @param localEndpoint
* the local service implementation
* @param exceptionHandler
* an exception handler that should never return null.
*/
@SuppressWarnings("unchecked")
public PatchedRemoteEndpoint(MessageConsumer out, Endpoint localEndpoint,
Function<Throwable, ResponseError> exceptionHandler) {
super(out, localEndpoint, exceptionHandler);
this.localEndpoint = localEndpoint;
this.exceptionHandler = exceptionHandler;
this.out = out;
Field field;
try {
field = RemoteEndpoint.class.getDeclaredField("receivedRequestMap");
field.setAccessible(true);
receivedRequestMap = (Map<String, CompletableFuture<?>>) field.get(this);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public CompletableFuture<?> request(String method, Object parameter) {
if (!extensionProviders.containsKey(method)) {
throw new UnsupportedOperationException("The json request \'" + method + "\' is unknown.");
}
for (Endpoint endpoint : extensionProviders.get(method)) {
try {
return endpoint.request(method, parameter);
} catch (UnsupportedOperationException e) {
if (e != ILanguageServerExtension.NOT_HANDLED_EXCEPTION) {
throw e;
}
}
}
return null;
}
@Override
public CompletableFuture<?> request(String method, Object parameter) {
if (!extensionProviders.containsKey(method)) {
throw new UnsupportedOperationException("The json request \'" + method + "\' is unknown.");
}
for (Endpoint endpoint : extensionProviders.get(method)) {
try {
return endpoint.request(method, parameter);
} catch (UnsupportedOperationException e) {
if (e != ILanguageServerExtension.NOT_HANDLED_EXCEPTION) {
throw e;
}
}
}
return null;
}
@Override
protected RemoteEndpoint createRemoteEndpoint(MessageJsonHandler jsonHandler) {
MessageConsumer outgoingMessageStream = new StreamMessageConsumer(output, jsonHandler);
outgoingMessageStream = wrapMessageConsumer(outgoingMessageStream);
Endpoint localEndpoint = ServiceEndpoints.toEndpoint(localServices);
RemoteEndpoint remoteEndpoint;
if (exceptionHandler == null)
remoteEndpoint = new PatchedRemoteEndpoint(outgoingMessageStream, localEndpoint);
else
remoteEndpoint = new PatchedRemoteEndpoint(outgoingMessageStream, localEndpoint, exceptionHandler);
jsonHandler.setMethodProvider(remoteEndpoint);
return remoteEndpoint;
}
@Override
public void notify(String method, Object parameter) {
for (Endpoint endpoint : extensionProviders.get(method)) {
try {
endpoint.notify(method, parameter);
} catch (UnsupportedOperationException e) {
if (e != ILanguageServerExtension.NOT_HANDLED_EXCEPTION) {
throw e;
}
}
}
}
@Override
public void notify(String method, Object parameter) {
for (Endpoint endpoint : extensionProviders.get(method)) {
try {
endpoint.notify(method, parameter);
} catch (UnsupportedOperationException e) {
if (e != ILanguageServerExtension.NOT_HANDLED_EXCEPTION) {
throw e;
}
}
}
}
@Override
protected RemoteEndpoint createRemoteEndpoint(MessageJsonHandler jsonHandler) {
MessageConsumer outgoingMessageStream = new WebSocketMessageConsumer(session, jsonHandler);
outgoingMessageStream = wrapMessageConsumer(outgoingMessageStream);
Endpoint localEndpoint = ServiceEndpoints.toEndpoint(localServices);
RemoteEndpoint remoteEndpoint;
if (exceptionHandler == null)
remoteEndpoint = new RemoteEndpoint(outgoingMessageStream, localEndpoint);
else
remoteEndpoint = new RemoteEndpoint(outgoingMessageStream, localEndpoint, exceptionHandler);
jsonHandler.setMethodProvider(remoteEndpoint);
return remoteEndpoint;
}
@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();
}
}
@Override
protected RemoteEndpoint createRemoteEndpoint(MessageJsonHandler jsonHandler) {
MessageConsumer outgoingMessageStream = new StreamMessageConsumer(output, jsonHandler);
outgoingMessageStream = wrapMessageConsumer(outgoingMessageStream);
Endpoint localEndpoint = ServiceEndpoints.toEndpoint(localServices);
RemoteEndpoint remoteEndpoint;
if (exceptionHandler == null)
remoteEndpoint = new DebugRemoteEndpoint(outgoingMessageStream, localEndpoint);
else
remoteEndpoint = new DebugRemoteEndpoint(outgoingMessageStream, localEndpoint, exceptionHandler);
jsonHandler.setMethodProvider(remoteEndpoint);
return remoteEndpoint;
}
/**
* Wraps a given {@link Endpoint} in the given service interface.
*
* @return the wrapped service object
*/
@SuppressWarnings("unchecked")
public static <T> T toServiceObject(Endpoint endpoint, Class<T> interface_) {
Class<?>[] interfArray = new Class[]{interface_, Endpoint.class};
EndpointProxy invocationHandler = new EndpointProxy(endpoint, interface_);
return (T) Proxy.newProxyInstance(interface_.getClassLoader(), interfArray, invocationHandler);
}
/**
* Wraps a given {@link Endpoint} in the given service interfaces.
*
* @return the wrapped service object
*/
public static Object toServiceObject(Endpoint endpoint, Collection<Class<?>> interfaces, ClassLoader classLoader) {
Class<?>[] interfArray = new Class[interfaces.size() + 1];
interfaces.toArray(interfArray);
interfArray[interfArray.length - 1] = Endpoint.class;
EndpointProxy invocationHandler = new EndpointProxy(endpoint, interfaces);
return Proxy.newProxyInstance(classLoader, interfArray, invocationHandler);
}
public EndpointProxy(Endpoint delegate, Collection<Class<?>> interfaces) {
if (delegate == null)
throw new NullPointerException("delegate");
if (interfaces == null)
throw new NullPointerException("interfaces");
if (interfaces.isEmpty())
throw new IllegalArgumentException("interfaces must not be empty.");
this.delegate = delegate;
try {
object_equals = Object.class.getDeclaredMethod("equals", Object.class);
object_hashCode = Object.class.getDeclaredMethod("hashCode");
object_toString = Object.class.getDeclaredMethod("toString");
} catch (NoSuchMethodException | SecurityException exception) {
throw new RuntimeException(exception);
}
methodInfos = new LinkedHashMap<>();
delegatedSegments = new LinkedHashMap<>();
for (Class<?> interf : interfaces) {
AnnotationUtil.findRpcMethods(interf, new HashSet<Class<?>>(), (methodInfo) -> {
if (methodInfos.put(methodInfo.method.getName(), methodInfo) != null) {
throw new IllegalStateException("Duplicate RPC method " + methodInfo.method);
}
});
AnnotationUtil.findDelegateSegments(interf, new HashSet<Class<?>>(), (method) -> {
Object delegateProxy = ServiceEndpoints.toServiceObject(delegate, method.getReturnType());
DelegateInfo info = new DelegateInfo();
info.delegate = delegateProxy;
info.method = method;
if (delegatedSegments.put(method.getName(), info) != null) {
throw new IllegalStateException("Duplicate RPC method " + method);
}
});
}
}
@Override
public CompletableFuture<?> request(String method, Object parameter) {
// Check the registered method handlers
Function<Object, CompletableFuture<Object>> handler = methodHandlers.get(method);
if (handler != null) {
return handler.apply(parameter);
}
// Ask the delegate objects whether they can handle the request generically
List<CompletableFuture<?>> futures = new ArrayList<>(delegates.size());
for (Object delegate : delegates) {
if (delegate instanceof Endpoint) {
futures.add(((Endpoint) delegate).request(method, parameter));
}
}
if (!futures.isEmpty()) {
return CompletableFuture.anyOf(futures.toArray(new CompletableFuture[futures.size()]));
}
// Create a log message about the unsupported method
String message = "Unsupported request method: " + method;
if (isOptionalMethod(method)) {
LOG.log(Level.INFO, message);
return CompletableFuture.completedFuture(null);
}
LOG.log(Level.WARNING, message);
CompletableFuture<?> exceptionalResult = new CompletableFuture<Object>();
ResponseError error = new ResponseError(ResponseErrorCode.MethodNotFound, message, null);
exceptionalResult.completeExceptionally(new ResponseErrorException(error));
return exceptionalResult;
}
@Override
public void notify(String method, Object parameter) {
// Check the registered method handlers
Function<Object, CompletableFuture<Object>> handler = methodHandlers.get(method);
if (handler != null) {
handler.apply(parameter);
return;
}
// Ask the delegate objects whether they can handle the notification generically
int notifiedDelegates = 0;
for (Object delegate : delegates) {
if (delegate instanceof Endpoint) {
((Endpoint) delegate).notify(method, parameter);
notifiedDelegates++;
}
}
if (notifiedDelegates == 0) {
// Create a log message about the unsupported method
String message = "Unsupported notification method: " + method;
if (isOptionalMethod(method)) {
LOG.log(Level.INFO, message);
} else {
LOG.log(Level.WARNING, message);
}
}
}
/**
* @since 2.16
*/
protected Multimap<String, Endpoint> getExtensionProviders() {
return ImmutableMultimap.copyOf(extensionProviders);
}
@Override
public void initialize(ILanguageServerAccess access) {
this.access = access;
this.access.addBuildListener(this);
this.client = ServiceEndpoints.toServiceObject((Endpoint) access.getLanguageClient(), CustomClient.class);
}
/**
* @since 2.16
*/
protected Multimap<String, Endpoint> getExtensionProviders() {
return ImmutableMultimap.copyOf(extensionProviders);
}
public DebugRemoteEndpoint(MessageConsumer out, Endpoint localEndpoint) {
super(out, localEndpoint);
}
public DebugRemoteEndpoint(MessageConsumer out, Endpoint localEndpoint,
Function<Throwable, ResponseError> exceptionHandler) {
super(out, localEndpoint, exceptionHandler);
}
public EndpointProxy(Endpoint delegate, Class<?> interface_) {
this(delegate, Collections.singletonList(interface_));
}
/**
* @param out
* a consumer that transmits messages to the remote service
* @param localEndpoint
* the local service implementation
*/
public PatchedRemoteEndpoint(MessageConsumer out, Endpoint localEndpoint) {
this(out, localEndpoint, DEFAULT_EXCEPTION_HANDLER);
}
/**
* Wraps a given object with service annotations behind an {@link Endpoint} interface.
*
* @return the wrapped service endpoint
*/
public static Endpoint toEndpoint(Object serviceObject) {
return new GenericEndpoint(serviceObject);
}
/**
* Wraps a collection of objects with service annotations behind an {@link Endpoint} interface.
*
* @return the wrapped service endpoint
*/
public static Endpoint toEndpoint(Collection<Object> serviceObjects) {
return new GenericEndpoint(serviceObjects);
}