下面列出了org.eclipse.lsp4j.RenameParams#org.eclipse.lsp4j.MessageType 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void showMessage(MessageParams messageParams) {
String title = "Language Server message";
String message = messageParams.getMessage();
ApplicationUtils.invokeLater(() -> {
MessageType msgType = messageParams.getType();
if (msgType == MessageType.Error) {
Messages.showErrorDialog(message, title);
} else if (msgType == MessageType.Warning) {
Messages.showWarningDialog(message, title);
} else if (msgType == MessageType.Info) {
Messages.showInfoMessage(message, title);
} else if (msgType == MessageType.Log) {
Messages.showInfoMessage(message, title);
} else {
LOG.warn("No message type for " + message);
}
});
}
@Override
public void logMessage(MessageParams messageParams) {
String message = messageParams.getMessage();
MessageType msgType = messageParams.getType();
if (msgType == MessageType.Error) {
LOG.error(message);
} else if (msgType == MessageType.Warning) {
LOG.warn(message);
} else if (msgType == MessageType.Info) {
LOG.info(message);
}
if (msgType == MessageType.Log) {
LOG.debug(message);
} else {
LOG.warn("Unknown message type for " + message);
}
}
private static Icon messageTypeToIcon(MessageType type) {
Icon result = null;
switch (type) {
case Error:
result = AllIcons.General.Error;
break;
case Info:
case Log:
result = AllIcons.General.Information;
break;
case Warning:
result = AllIcons.General.Warning;
}
return result;
}
private static NotificationType messageTypeToNotificationType(MessageType type) {
NotificationType result = null;
switch (type) {
case Error:
result = NotificationType.ERROR;
break;
case Info:
case Log:
result = NotificationType.INFORMATION;
break;
case Warning:
result = NotificationType.WARNING;
}
return result;
}
@Override
public CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> documentSymbol(DocumentSymbolParams params) {
JavaSource js = getSource(params.getTextDocument().getUri());
List<Either<SymbolInformation, DocumentSymbol>> result = new ArrayList<>();
try {
js.runUserActionTask(cc -> {
cc.toPhase(JavaSource.Phase.RESOLVED);
for (Element tel : cc.getTopLevelElements()) {
DocumentSymbol ds = element2DocumentSymbol(cc, tel);
if (ds != null)
result.add(Either.forRight(ds));
}
}, true);
} catch (IOException ex) {
//TODO: include stack trace:
client.logMessage(new MessageParams(MessageType.Error, ex.getMessage()));
}
return CompletableFuture.completedFuture(result);
}
@Override
protected void append(LoggingEvent event) {
MessageParams mp = new MessageParams();
mp.setMessage(event.getMessage().toString());
mp.setType(MessageType.Info);
switch (event.getLevel().toInt()) {
case Level.FATAL_INT:
case Level.ERROR_INT:
mp.setType(MessageType.Error);
break;
case Level.INFO_INT:
mp.setType(MessageType.Info);
break;
case Level.WARN_INT:
mp.setType(MessageType.Warning);
break;
default:
return;
}
client.logMessage(mp);
}
@Override
public CompletableFuture<MessageActionItem> showMessageRequest(ShowMessageRequestParams showMessageRequestParams) {
List<MessageActionItem> actions = showMessageRequestParams.getActions();
String title = "Language Server message";
String message = showMessageRequestParams.getMessage();
MessageType msgType = showMessageRequestParams.getType();
Icon icon;
if (msgType == MessageType.Error) {
icon = UIUtil.getErrorIcon();
} else if (msgType == MessageType.Warning) {
icon = UIUtil.getWarningIcon();
} else if (msgType == MessageType.Info) {
icon = UIUtil.getInformationIcon();
} else if (msgType == MessageType.Log) {
icon = UIUtil.getInformationIcon();
} else {
icon = null;
LOG.warn("No message type for " + message);
}
List<String> titles = new ArrayList<>();
for (MessageActionItem item : actions) {
titles.add(item.getTitle());
}
FutureTask<Integer> task = new FutureTask<>(
() -> Messages.showDialog(message, title, (String[]) titles.toArray(), 0, icon));
ApplicationManager.getApplication().invokeAndWait(task);
int exitCode = 0;
try {
exitCode = task.get();
} catch (InterruptedException | ExecutionException e) {
LOG.warn(e.getMessage());
}
return CompletableFuture.completedFuture(new MessageActionItem(actions.get(exitCode).getTitle()));
}
@Override
public void publish(LogRecord record) {
if (languageClient == null) {
return;
}
String msg = formatRecord(record, Locale.getDefault());
MessageType messageType = getMessageType(record.getLevel());
MessageParams mp = new MessageParams(messageType, msg);
languageClient.logMessage(mp);
}
private static MessageType getMessageType(Level level) {
if (level == Level.WARNING) {
return MessageType.Warning;
}
if (level == Level.SEVERE) {
return MessageType.Error;
}
return MessageType.Info;
}
@Override
public void sendNotification(String message, MessageType messageType, Command... commands) {
SharedSettings sharedSettings = getSharedSettings();
if (sharedSettings.isActionableNotificationSupport() && sharedSettings.isOpenSettingsCommandSupport()) {
ActionableNotification notification = new ActionableNotification().withSeverity(messageType)
.withMessage(message).withCommands(Arrays.asList(commands));
languageClient.actionableNotification(notification);
} else {
// the open settings command is not supported by the client, display a simple
// message with LSP
languageClient.showMessage(new MessageParams(messageType, message));
}
}
private void sendInvalidFilePathWarning(Set<String> invalidPaths, PathFeature feature) {
String message = createWarningMessage(feature.getSettingId(), invalidPaths);
Command command = new Command("Configure setting", ClientCommands.OPEN_SETTINGS,
Collections.singletonList(feature.getSettingId()));
super.sendNotification(message, MessageType.Error, command);
}
/**
* Send limit exceeded warning to client
*
* @param uri the file uri
* @param resultLimit the result limit
* @param feature the feature
*/
private void sendLimitExceededWarning(String uri, int resultLimit, LimitFeature feature) {
String filename = Paths.get(URI.create(uri)).getFileName().toString();
String message = filename != null ? filename + ": " : "";
message += "For performance reasons, " + feature.getName() + " have been limited to " + resultLimit
+ " items.\nIf a new limit is set, please close and reopen this file to recompute " + feature.getName() + ".";
// create command that opens the settings UI on the client side, in order to
// quickly edit the setting
Command command = new Command("Configure limit", ClientCommands.OPEN_SETTINGS,
Collections.singletonList(feature.getSettingId()));
super.sendNotification(message, MessageType.Info ,command);
}
@BeforeEach
public void startup() {
TimeZone.setDefault(TimeZone.getTimeZone(("UTC")));
deleteLogFile();
mockLanguageClient = createLanguageClient(MessageType.Error, "Log Message");
LogsSettings settings = new LogsSettings();
// Enable log file
settings.setFile(path);
// Enable client
settings.setClient(true);
LogHelper.initializeRootLogger(mockLanguageClient, settings);
logFile = new File(path);
}
private void showException(String msg, Exception ex) {
StringWriter w = new StringWriter();
PrintWriter p = new PrintWriter(w);
ex.printStackTrace(p);
this.client.showMessage(
new MessageParams(MessageType.Info,
String.format("%s: %s: %s", msg, ex.getMessage(), w.toString())));
}
/**
* Visualize the collected performance data on the client and reset the data back to its initial state.
*
* @param access
* the language server access.
* @param cancelIndicator
* the cancel indicator.
*/
@ExecutableCommandHandler(RESET_PERFORMANCE_DATA)
public Void resetPerformanceDataCollector(ILanguageServerAccess access, CancelIndicator cancelIndicator) {
access.getLanguageClient()
.logMessage(new MessageParams(MessageType.Log, DataCollectorUtils.allDataToString(" ")));
access.getLanguageClient()
.logMessage(new MessageParams(MessageType.Log, "Reset collected performance data"));
CollectedDataAccess.resetAllData();
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 MessageType getMessageTypeFromSeverity(int severity) {
switch (severity) {
case IStatus.ERROR:
return MessageType.Error;
case IStatus.WARNING:
return MessageType.Warning;
case IStatus.INFO:
return MessageType.Info;
default:
return MessageType.Log;
}
}
public MessageType toMessageType() {
for (MessageType type : MessageType.values()) {
if (name().equalsIgnoreCase(type.name())) {
return type;
}
}
//'ignore' has no MessageType equivalent
return null;
}
/**
* Sends the logMessage message back to the client as a notification
* @param msg The message to send back to the client
*/
public void logMessage(MessageType type, String msg) {
MessageParams $= new MessageParams();
$.setMessage(msg);
$.setType(type);
client.logMessage($);
}
/**
* Sends the message to the client, to be displayed on a UI element.
*
* @param type
* @param msg
*/
public void showNotificationMessage(MessageType type, String msg){
MessageParams $ = new MessageParams();
$.setMessage(msg);
$.setType(type);
client.showMessage($);
}
/**
* 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();
}
});
}
@Test public void testNotification() throws IOException {
MessageParams p = new MessageParams();
p.setMessage("Hello World");
p.setType(MessageType.Info);
client.expectedNotifications.put("window/logMessage", p);
serverLauncher.getRemoteProxy().logMessage(p);
client.joinOnEmpty();
}
public ActionableNotification withSeverity(MessageType severity) {
this.severity = severity;
return this;
}
protected void sendNotification(String message, MessageType messageType, Command... commands) {
notificationService.sendNotification(message, messageType, commands);
}
private MockLanguageClient createLanguageClient(MessageType messageType, String message) {
MockLanguageClient newLanguageClient = new MockLanguageClient(messageType, message);
return newLanguageClient;
}
public MockLanguageClient(MessageType expectedMessageType, String message) {
this.expectedMessageType = expectedMessageType;
this.message = message;
}
/**
* Install the given NPM into the workspace.
*
* @param cancelIndicator
* not required.
*/
@ExecutableCommandHandler(JSONCodeActionService.INSTALL_NPM)
public Void installNpm(
String packageName,
String version,
String fileUri,
ILanguageServerAccess access,
CancelIndicator cancelIndicator) {
lspServer.getLSPExecutorService().submitAndCancelPrevious(XBuildManager.class, "InstallNpm", (ci) -> {
// FIXME: Use CliTools in favor of npmCli
NPMVersionRequirement versionRequirement = semverHelper.parse(version);
if (versionRequirement == null) {
versionRequirement = SemverUtils.createEmptyVersionRequirement();
}
String normalizedVersion = SemverSerializer.serialize(versionRequirement);
N4JSProjectName projectName = new N4JSProjectName(packageName);
LibraryChange change = new LibraryChange(LibraryChangeType.Install, null, projectName, normalizedVersion);
MultiStatus multiStatus = new MultiStatus("json", 1, null, null);
FileURI targetProject = new FileURI(URI.createURI(fileUri)).getParent();
npmCli.batchInstall(new NullProgressMonitor(), multiStatus, Arrays.asList(change), targetProject);
MessageParams messageParams = new MessageParams();
switch (multiStatus.getSeverity()) {
case IStatus.INFO:
messageParams.setType(MessageType.Info);
break;
case IStatus.WARNING:
messageParams.setType(MessageType.Warning);
break;
case IStatus.ERROR:
messageParams.setType(MessageType.Error);
break;
default:
return null;
}
StringWriter sw = new StringWriter();
PrintWriter printWriter = new PrintWriter(sw);
for (IStatus child : multiStatus.getChildren()) {
if (child.getSeverity() == multiStatus.getSeverity()) {
printWriter.println(child.getMessage());
}
}
printWriter.flush();
messageParams.setMessage(sw.toString());
access.getLanguageClient().showMessage(messageParams);
return null;
}).whenComplete((a, b) -> lspServer.reinitWorkspace());
return null;
}
/** */
public void log(String messageString) {
log(messageString, MessageType.Log);
}
/** */
public void info(String messageString) {
log(messageString, MessageType.Info);
}
/** */
public void warning(String messageString) {
log(messageString, MessageType.Warning);
}