diff --git a/headless-services/.mvn/wrapper/maven-wrapper.jar b/headless-services/.mvn/wrapper/maven-wrapper.jar index c6feb8bb6..c1dd12f17 100644 Binary files a/headless-services/.mvn/wrapper/maven-wrapper.jar and b/headless-services/.mvn/wrapper/maven-wrapper.jar differ diff --git a/headless-services/.mvn/wrapper/maven-wrapper.properties b/headless-services/.mvn/wrapper/maven-wrapper.properties index 33232336d..db95c131d 100644 --- a/headless-services/.mvn/wrapper/maven-wrapper.properties +++ b/headless-services/.mvn/wrapper/maven-wrapper.properties @@ -1 +1,18 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip \ No newline at end of file +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.5/apache-maven-3.8.5-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar diff --git a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/composable/CompositeLanguageServerComponents.java b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/composable/CompositeLanguageServerComponents.java index 841c7ae73..b187dc269 100644 --- a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/composable/CompositeLanguageServerComponents.java +++ b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/composable/CompositeLanguageServerComponents.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2018, 2021 Pivotal, Inc. + * Copyright (c) 2018, 2022 Pivotal, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -10,23 +10,29 @@ *******************************************************************************/ package org.springframework.ide.vscode.commons.languageserver.composable; +import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.CodeActionCapabilities; +import org.eclipse.lsp4j.Command; import org.eclipse.lsp4j.Hover; import org.eclipse.lsp4j.HoverParams; import org.eclipse.lsp4j.jsonrpc.CancelChecker; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.eclipse.lsp4j.jsonrpc.messages.Either; import org.springframework.ide.vscode.commons.languageserver.reconcile.IProblemCollector; import org.springframework.ide.vscode.commons.languageserver.reconcile.IReconcileEngine; +import org.springframework.ide.vscode.commons.languageserver.util.CodeActionHandler; import org.springframework.ide.vscode.commons.languageserver.util.HoverHandler; import org.springframework.ide.vscode.commons.languageserver.util.SimpleLanguageServer; import org.springframework.ide.vscode.commons.languageserver.util.SimpleTextDocumentService; import org.springframework.ide.vscode.commons.util.Assert; import org.springframework.ide.vscode.commons.util.text.IDocument; +import org.springframework.ide.vscode.commons.util.text.IRegion; import org.springframework.ide.vscode.commons.util.text.LanguageId; import org.springframework.ide.vscode.commons.util.text.TextDocument; @@ -34,8 +40,6 @@ import com.google.common.collect.ImmutableMap; public class CompositeLanguageServerComponents implements LanguageServerComponents { - private static Logger log = LoggerFactory.getLogger(CompositeLanguageServerComponents.class); - public static class Builder { private Map componentsByLanguageId = new HashMap<>(); @@ -55,6 +59,7 @@ public class CompositeLanguageServerComponents implements LanguageServerComponen private final Map componentsByLanguageId; private final IReconcileEngine reconcileEngine; private final HoverHandler hoverHandler; + private final CodeActionHandler codeActionHandler; public CompositeLanguageServerComponents(SimpleLanguageServer server, Builder builder) { this.componentsByLanguageId = ImmutableMap.copyOf(builder.componentsByLanguageId); @@ -96,6 +101,23 @@ public class CompositeLanguageServerComponents implements LanguageServerComponen return SimpleTextDocumentService.NO_HOVER; } }; + + this.codeActionHandler = new CodeActionHandler() { + + @Override + public List> handle(CancelChecker cancelToken, CodeActionCapabilities capabilities, TextDocument doc, + IRegion region) { + LanguageId language = doc.getLanguageId(); + LanguageServerComponents subComponents = componentsByLanguageId.get(language); + if (subComponents != null) { + return subComponents.getCodeActionProvider() + .map(subEngine -> subEngine.handle(cancelToken, capabilities, doc, region)) + .orElse(Collections.emptyList()); + } + //No applicable subEngine... + return Collections.emptyList(); + } + }; } @Override @@ -123,4 +145,9 @@ public class CompositeLanguageServerComponents implements LanguageServerComponen return null; } + @Override + public Optional getCodeActionProvider() { + return Optional.of(codeActionHandler); + } + } diff --git a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/composable/LanguageServerComponents.java b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/composable/LanguageServerComponents.java index f45d1b21e..cce5f1f3c 100644 --- a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/composable/LanguageServerComponents.java +++ b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/composable/LanguageServerComponents.java @@ -13,10 +13,9 @@ package org.springframework.ide.vscode.commons.languageserver.composable; import java.util.Optional; import java.util.Set; -import org.springframework.ide.vscode.commons.languageserver.completion.ICompletionEngine; import org.springframework.ide.vscode.commons.languageserver.reconcile.IReconcileEngine; +import org.springframework.ide.vscode.commons.languageserver.util.CodeActionHandler; import org.springframework.ide.vscode.commons.languageserver.util.HoverHandler; -import org.springframework.ide.vscode.commons.languageserver.util.LanguageSpecific; import org.springframework.ide.vscode.commons.util.text.LanguageId; public interface LanguageServerComponents { @@ -24,4 +23,5 @@ public interface LanguageServerComponents { Set getInterestingLanguages(); default Optional getReconcileEngine() { return Optional.empty(); } HoverHandler getHoverProvider(); + default Optional getCodeActionProvider() { return Optional.empty(); } } diff --git a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/quickfix/Quickfix.java b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/quickfix/Quickfix.java index 2b68e6f2f..e74cba7c1 100644 --- a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/quickfix/Quickfix.java +++ b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/quickfix/Quickfix.java @@ -10,7 +10,12 @@ *******************************************************************************/ package org.springframework.ide.vscode.commons.languageserver.quickfix; +import java.util.List; +import java.util.stream.Collectors; + +import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.CodeActionContext; +import org.eclipse.lsp4j.CodeActionKind; import org.eclipse.lsp4j.Command; import org.eclipse.lsp4j.Diagnostic; import org.eclipse.lsp4j.Range; @@ -51,12 +56,17 @@ public class Quickfix { return range; } - public Command getCodeAction() { - return new Command( + public CodeAction getCodeAction(CodeActionContext context) { + CodeAction ca = new CodeAction(); + ca.setKind(CodeActionKind.QuickFix); + ca.setTitle(data.title); + ca.setDiagnostics(appliesToDiagnostics(context)); + ca.setCommand(new Command( data.title, CODE_ACTION_CMD_ID, ImmutableList.of(data.type.getId(), data.params) - ); + )); + return ca; } public boolean appliesTo(Range range, CodeActionContext context) { @@ -71,4 +81,10 @@ public class Quickfix { } return true; } + + private List appliesToDiagnostics(CodeActionContext context) { + return context.getDiagnostics().stream() + .filter(diag -> this.diagMsg == null || this.diagMsg.equals(diag.getMessage())) + .collect(Collectors.toList()); + } } diff --git a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/quickfix/QuickfixRegistry.java b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/quickfix/QuickfixRegistry.java index 8471083a7..813baa19d 100644 --- a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/quickfix/QuickfixRegistry.java +++ b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/quickfix/QuickfixRegistry.java @@ -49,6 +49,22 @@ public class QuickfixRegistry { } }; } + + public synchronized QuickfixType getQuickfixType(String typeName) { + QuickfixHandler handler = registry.get(typeName); + return new QuickfixType() { + + @Override + public QuickfixEdit createEdits(Object params) { + return handler.createEdits(params); + } + + @Override + public String getId() { + return typeName; + } + }; + } public Mono handle(QuickfixResolveParams params) { QuickfixHandler handler = registry.get(params.getType()); diff --git a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/CodeActionHandler.java b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/CodeActionHandler.java new file mode 100644 index 000000000..de49c27c7 --- /dev/null +++ b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/CodeActionHandler.java @@ -0,0 +1,17 @@ +package org.springframework.ide.vscode.commons.languageserver.util; + +import java.util.List; + +import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.CodeActionCapabilities; +import org.eclipse.lsp4j.Command; +import org.eclipse.lsp4j.jsonrpc.CancelChecker; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.springframework.ide.vscode.commons.util.text.IRegion; +import org.springframework.ide.vscode.commons.util.text.TextDocument; + +public interface CodeActionHandler { + + List> handle(CancelChecker cancelToken, CodeActionCapabilities capabilities, TextDocument doc, IRegion region); + +} diff --git a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/CodeActionResolver.java b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/CodeActionResolver.java new file mode 100644 index 000000000..876571db4 --- /dev/null +++ b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/CodeActionResolver.java @@ -0,0 +1,9 @@ +package org.springframework.ide.vscode.commons.languageserver.util; + +import org.eclipse.lsp4j.CodeAction; + +public interface CodeActionResolver { + + void resolve(CodeAction codeAction); + +} diff --git a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/ServerCapabilityInitializer.java b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/ServerCapabilityInitializer.java index 95f1b9a3f..fc661f54d 100644 --- a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/ServerCapabilityInitializer.java +++ b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/ServerCapabilityInitializer.java @@ -18,6 +18,7 @@ import org.eclipse.lsp4j.ServerCapabilities; * in the application context and call on them during language server initialization to allow * it to participate in initializing the ServerCapability the server returns to the client. */ +@FunctionalInterface public interface ServerCapabilityInitializer { void initialize(InitializeParams params, ServerCapabilities cap); } diff --git a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/SimpleLanguageServer.java b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/SimpleLanguageServer.java index 49a603934..290788df9 100644 --- a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/SimpleLanguageServer.java +++ b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/SimpleLanguageServer.java @@ -34,6 +34,8 @@ import java.util.function.Consumer; import org.eclipse.lsp4j.ApplyWorkspaceEditParams; import org.eclipse.lsp4j.ApplyWorkspaceEditResponse; import org.eclipse.lsp4j.ClientCapabilities; +import org.eclipse.lsp4j.CodeActionKind; +import org.eclipse.lsp4j.CodeActionOptions; import org.eclipse.lsp4j.CodeLensOptions; import org.eclipse.lsp4j.Diagnostic; import org.eclipse.lsp4j.DiagnosticSeverity; @@ -262,7 +264,7 @@ public final class SimpleLanguageServer implements Sts4LanguageServer, LanguageC ); return quickfixResolve(quickfixParams) .flatMap((QuickfixEdit edit) -> { - Mono applyEdit = Mono.fromFuture(client.applyEdit(new ApplyWorkspaceEditParams(edit.workspaceEdit))); + Mono applyEdit = Mono.fromFuture(client.applyEdit(new ApplyWorkspaceEditParams(edit.workspaceEdit, quickfixParams.getType()))); return applyEdit.flatMap(r -> { if (r.isApplied()) { if (edit.cursorMovement!=null) { @@ -436,7 +438,10 @@ public final class SimpleLanguageServer implements Sts4LanguageServer, LanguageC c.setHoverProvider(true); if (hasQuickFixes()) { - c.setCodeActionProvider(true); + CodeActionOptions codeActionOptions = new CodeActionOptions(); + codeActionOptions.setCodeActionKinds(List.of(CodeActionKind.QuickFix)); + codeActionOptions.setWorkDoneProgress(true); + c.setCodeActionProvider(codeActionOptions); } if (hasDefinitionHandler()) { c.setDefinitionProvider(true); @@ -464,7 +469,9 @@ public final class SimpleLanguageServer implements Sts4LanguageServer, LanguageC supportedCommands.add(CODE_ACTION_COMMAND_ID); } supportedCommands.addAll(commands.keySet()); - c.setExecuteCommandProvider(new ExecuteCommandOptions(supportedCommands)); + ExecuteCommandOptions executeCommandOptions = new ExecuteCommandOptions(supportedCommands); + executeCommandOptions.setWorkDoneProgress(true); + c.setExecuteCommandProvider(executeCommandOptions); } if (hasWorkspaceSymbolHandler()) { c.setWorkspaceSymbolProvider(true); @@ -566,7 +573,7 @@ public final class SimpleLanguageServer implements Sts4LanguageServer, LanguageC } protected SimpleTextDocumentService createTextDocumentService() { - return new SimpleTextDocumentService(this, props); + return new SimpleTextDocumentService(this, props, appContext); } public SimpleWorkspaceService createWorkspaceService() { diff --git a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/SimpleTextDocumentService.java b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/SimpleTextDocumentService.java index b5fa78b60..1055edca1 100644 --- a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/SimpleTextDocumentService.java +++ b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/util/SimpleTextDocumentService.java @@ -13,6 +13,7 @@ package org.springframework.ide.vscode.commons.languageserver.util; import java.util.Collection; import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; @@ -23,7 +24,9 @@ import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.stream.Collectors; +import org.eclipse.lsp4j.ClientCapabilities; import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.CodeActionCapabilities; import org.eclipse.lsp4j.CodeActionParams; import org.eclipse.lsp4j.CodeLens; import org.eclipse.lsp4j.CodeLensParams; @@ -54,6 +57,7 @@ import org.eclipse.lsp4j.RenameParams; import org.eclipse.lsp4j.SignatureHelp; import org.eclipse.lsp4j.SignatureHelpParams; import org.eclipse.lsp4j.SymbolInformation; +import org.eclipse.lsp4j.TextDocumentClientCapabilities; import org.eclipse.lsp4j.TextDocumentContentChangeEvent; import org.eclipse.lsp4j.TextDocumentIdentifier; import org.eclipse.lsp4j.TextDocumentItem; @@ -68,12 +72,13 @@ import org.eclipse.lsp4j.services.LanguageClient; import org.eclipse.lsp4j.services.TextDocumentService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; import org.springframework.ide.vscode.commons.languageserver.config.LanguageServerProperties; import org.springframework.ide.vscode.commons.languageserver.quickfix.Quickfix; import org.springframework.ide.vscode.commons.util.Assert; import org.springframework.ide.vscode.commons.util.BadLocationException; -import org.springframework.ide.vscode.commons.util.CollectorUtil; import org.springframework.ide.vscode.commons.util.text.LanguageId; +import org.springframework.ide.vscode.commons.util.text.Region; import org.springframework.ide.vscode.commons.util.text.TextDocument; import com.google.common.collect.ImmutableList; @@ -104,10 +109,14 @@ public class SimpleTextDocumentService implements TextDocumentService, DocumentE private DocumentHighlightHandler documentHighlightHandler; private CodeLensHandler codeLensHandler; private CodeLensResolveHandler codeLensResolveHandler; + private CodeActionHandler codeActionHandler; - public SimpleTextDocumentService(SimpleLanguageServer server, LanguageServerProperties props) { + final private ApplicationContext appContext; + + public SimpleTextDocumentService(SimpleLanguageServer server, LanguageServerProperties props, ApplicationContext appContext) { this.server = server; this.props = props; + this.appContext = appContext; this.messageWorkerThreadPool = Executors.newCachedThreadPool(); } @@ -414,6 +423,36 @@ public class SimpleTextDocumentService implements TextDocumentService, DocumentE return CompletableFuture.completedFuture(ImmutableList.of()); } } + + private List> computeCodeActions(CancelChecker cancelToken, CodeActionCapabilities capabilities, TrackedDocument doc, CodeActionParams params) { + List> list = doc.getQuickfixes().stream() + .filter((fix) -> fix.appliesTo(params.getRange(), params.getContext())) + .map(f -> f.getCodeAction(params.getContext())) + .map(command -> Either.forRight(command)) + .collect(Collectors.toList()); + + if (codeActionHandler != null) { + try { + int start = doc.getDocument().toOffset(params.getRange().getStart()); + int end = doc.getDocument().toOffset(params.getRange().getEnd()); + list.addAll(codeActionHandler.handle(cancelToken, capabilities, doc.getDocument(), new Region(start, end - start))); + } catch (Exception e) { + log.error("Failed to compute quick refactorings", e); + } + } + + return list; + } + + private static CodeActionCapabilities getCodeActionCapabilities(ClientCapabilities capabilities) { + if (capabilities != null) { + TextDocumentClientCapabilities docs = capabilities.getTextDocument(); + if (docs != null) { + return docs.getCodeAction(); + } + } + return null; + } @Override public CompletableFuture>> codeAction(CodeActionParams params) { @@ -423,17 +462,16 @@ public class SimpleTextDocumentService implements TextDocumentService, DocumentE TrackedDocument doc = documents.get(params.getTextDocument().getUri()); if (doc != null) { - ImmutableList> list = doc.getQuickfixes().stream() - .filter((fix) -> fix.appliesTo(params.getRange(), params.getContext())) - .map(Quickfix::getCodeAction) - .map(command -> Either.forLeft(command)) - .collect(CollectorUtil.toImmutableList()); - return CompletableFuture.completedFuture(list); + + return server.getClientCapabilities() + .thenApply(SimpleTextDocumentService::getCodeActionCapabilities) + .thenComposeAsync(capabilities -> + CompletableFutures.computeAsync(messageWorkerThreadPool, cancelToken -> computeCodeActions(cancelToken, capabilities, doc, params))); } else { return CompletableFuture.completedFuture(ImmutableList.of()); } } - + @Override public CompletableFuture> codeLens(CodeLensParams params) { CodeLensHandler handler = this.codeLensHandler; @@ -461,6 +499,22 @@ public class SimpleTextDocumentService implements TextDocumentService, DocumentE } } + @Override + public CompletableFuture resolveCodeAction(CodeAction ca) { + return CompletableFutures.computeAsync(messageWorkerThreadPool, cancelToken -> { + if (appContext!=null) { + Map resolvers = appContext.getBeansOfType(CodeActionResolver.class); + for (CodeActionResolver r : resolvers.values()) { + r.resolve(ca); + if (ca.getEdit() != null) { + return ca; + } + } + } + return ca; + }); + } + @Override public void didSave(DidSaveTextDocumentParams params) { // Workaround for PT 147263283, where error markers in STS are lost on document save. @@ -559,6 +613,11 @@ public class SimpleTextDocumentService implements TextDocumentService, DocumentE Assert.isNull("A code lens handler is already set, multiple handlers not supported yet", codeLensHandler); this.codeLensHandler = h; } + + public synchronized void onCodeAction(CodeActionHandler h) { + Assert.isNull("A code action handler is already set, multiple handlers not supported yet", codeActionHandler); + this.codeActionHandler = h; + } public boolean hasCodeLensHandler() { return this.codeLensHandler != null; diff --git a/headless-services/commons/java-properties/pom.xml b/headless-services/commons/java-properties/pom.xml index eb4b82370..f80906817 100644 --- a/headless-services/commons/java-properties/pom.xml +++ b/headless-services/commons/java-properties/pom.xml @@ -28,7 +28,7 @@ org.antlr antlr4-runtime - 4.5.3 + 4.9.3 diff --git a/headless-services/commons/pom.xml b/headless-services/commons/pom.xml index 8b6e4595c..4786cb84f 100644 --- a/headless-services/commons/pom.xml +++ b/headless-services/commons/pom.xml @@ -106,6 +106,11 @@ 0.7.5.RELEASE 2.4 1.13 + + + 7.21.3 + 4.19.3 + 2.13.2 true vmware diff --git a/headless-services/mvnw b/headless-services/mvnw index f13e1380f..5643201c7 100755 --- a/headless-services/mvnw +++ b/headless-services/mvnw @@ -8,7 +8,7 @@ # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an @@ -19,7 +19,7 @@ # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script +# Maven Start Up Batch script # # Required ENV vars: # ------------------ @@ -36,6 +36,10 @@ if [ -z "$MAVEN_SKIP_RC" ] ; then + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + if [ -f /etc/mavenrc ] ; then . /etc/mavenrc fi @@ -54,38 +58,16 @@ case "`uname`" in CYGWIN*) cygwin=true ;; MINGW*) mingw=true;; Darwin*) darwin=true - # - # Look for the Apple JDKs first to preserve the existing behaviour, and then look - # for the new JDKs provided by Oracle. - # - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then - # - # Oracle JDKs - # - export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then - # - # Apple JDKs - # - export JAVA_HOME=`/usr/libexec/java_home` - fi - ;; + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; esac if [ -z "$JAVA_HOME" ] ; then @@ -130,13 +112,12 @@ if $cygwin ; then CLASSPATH=`cygpath --path --unix "$CLASSPATH"` fi -# For Migwn, ensure paths are in UNIX format before anything is touched +# For Mingw, ensure paths are in UNIX format before anything is touched if $mingw ; then [ -n "$M2_HOME" ] && M2_HOME="`(cd "$M2_HOME"; pwd)`" [ -n "$JAVA_HOME" ] && JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? fi if [ -z "$JAVA_HOME" ]; then @@ -168,7 +149,7 @@ if [ -z "$JAVACMD" ] ; then JAVACMD="$JAVA_HOME/bin/java" fi else - JAVACMD="`which java`" + JAVACMD="`\\unset -f command; \\command -v java`" fi fi @@ -187,14 +168,25 @@ CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher # traverses directory structure from process work directory to filesystem root # first directory with .mvn subdirectory is considered project base directory find_maven_basedir() { - local basedir=$(pwd) - local wdir=$(pwd) + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" while [ "$wdir" != '/' ] ; do if [ -d "$wdir"/.mvn ] ; then basedir=$wdir break fi - wdir=$(cd "$wdir/.."; pwd) + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround done echo "${basedir}" } @@ -206,7 +198,94 @@ concat_lines() { fi } -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" # For Cygwin, switch paths to Windows format before running java @@ -228,9 +307,10 @@ export MAVEN_CMD_LINE_ARGS WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain -# avoid using MAVEN_CMD_LINE_ARGS below since that would loose parameter escaping in $@ exec "$JAVACMD" \ $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + "-Dmaven.home=${M2_HOME}" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/headless-services/mvnw.cmd b/headless-services/mvnw.cmd index bb9bb461e..8a15b7f31 100644 --- a/headless-services/mvnw.cmd +++ b/headless-services/mvnw.cmd @@ -7,7 +7,7 @@ @REM "License"); you may not use this file except in compliance @REM with the License. You may obtain a copy of the License at @REM -@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM http://www.apache.org/licenses/LICENSE-2.0 @REM @REM Unless required by applicable law or agreed to in writing, @REM software distributed under the License is distributed on an @@ -18,7 +18,7 @@ @REM ---------------------------------------------------------------------------- @REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script +@REM Maven Start Up Batch script @REM @REM Required ENV vars: @REM JAVA_HOME - location of a JDK home dir @@ -26,7 +26,7 @@ @REM Optional ENV vars @REM M2_HOME - location of maven2's installed home dir @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven @REM e.g. to debug Maven itself, use @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 @@ -35,7 +35,9 @@ @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' @echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% @REM set %HOME% to equivalent of $HOME @@ -44,8 +46,8 @@ if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") @REM Execute a user defined script before this one if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre @REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* :skipRcPre @setlocal @@ -80,8 +82,6 @@ goto error :init -set MAVEN_CMD_LINE_ARGS=%MAVEN_CONFIG% %* - @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". @REM Fallback to current working directory if not found. @@ -117,12 +117,54 @@ for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do s :endReadAdditionalConfig SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR=""%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain -# avoid using MAVEN_CMD_LINE_ARGS below since that would loose parameter escaping in %* -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* if ERRORLEVEL 1 goto error goto end @@ -132,15 +174,15 @@ set ERROR_CODE=1 :end @endlocal & set ERROR_CODE=%ERROR_CODE% -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost @REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" :skipRcPost @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause +if "%MAVEN_BATCH_PAUSE%"=="on" pause -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% -exit /B %ERROR_CODE% +cmd /C exit /B %ERROR_CODE% diff --git a/headless-services/spring-boot-language-server/pom.xml b/headless-services/spring-boot-language-server/pom.xml index 198b22f2d..f8f341540 100644 --- a/headless-services/spring-boot-language-server/pom.xml +++ b/headless-services/spring-boot-language-server/pom.xml @@ -38,6 +38,17 @@ true + + + rewrite-snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + + true + + + false + + @@ -93,6 +104,64 @@ org.eclipse.jdt.core ${jdt.core.version} + + org.openrewrite + rewrite-properties + ${rewrite-version} + + + org.openrewrite + rewrite-maven + ${rewrite-version} + + + org.openrewrite + rewrite-yaml + ${rewrite-version} + + + org.openrewrite + rewrite-java + ${rewrite-version} + + + + com.fasterxml.jackson.core + jackson-core + ${rewrite-jackson.version} + + + com.fasterxml.jackson.core + jackson-databind + ${rewrite-jackson.version} + + + com.fasterxml.jackson.core + jackson-annotations + ${rewrite-jackson.version} + + + com.fasterxml.jackson.datatype + jackson-datatype-jdk8 + ${rewrite-jackson.version} + + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + ${rewrite-jackson.version} + + + + org.openrewrite.recipe + rewrite-spring + ${rewrite-spring-version} + + + + org.openrewrite + rewrite-java-11 + ${rewrite-version} + commons-io commons-io diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/BootLanguageServerBootApp.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/BootLanguageServerBootApp.java index d032f0a12..a6f05ff1c 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/BootLanguageServerBootApp.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/BootLanguageServerBootApp.java @@ -18,6 +18,10 @@ import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; +import org.eclipse.lsp4j.CodeActionKind; +import org.eclipse.lsp4j.CodeActionOptions; +import org.eclipse.lsp4j.InitializeParams; +import org.eclipse.lsp4j.ServerCapabilities; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.SpringApplication; @@ -27,6 +31,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClas import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.ide.vscode.boot.common.PropertyCompletionFactory; @@ -43,6 +48,9 @@ import org.springframework.ide.vscode.boot.java.livehover.v2.SpringProcessConnec import org.springframework.ide.vscode.boot.java.livehover.v2.SpringProcessConnectorRemote.RemoteBootAppData; import org.springframework.ide.vscode.boot.java.livehover.v2.SpringProcessConnectorService; import org.springframework.ide.vscode.boot.java.livehover.v2.SpringProcessLiveDataProvider; +import org.springframework.ide.vscode.boot.java.rewrite.ORCompilationUnitCache; +import org.springframework.ide.vscode.boot.java.rewrite.RewriteRefactorings; +import org.springframework.ide.vscode.boot.java.rewrite.RewriteRecipeRepository; import org.springframework.ide.vscode.boot.java.utils.CompilationUnitCache; import org.springframework.ide.vscode.boot.java.utils.SymbolCache; import org.springframework.ide.vscode.boot.java.utils.SymbolCacheOnDisc; @@ -68,6 +76,7 @@ import org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFin import org.springframework.ide.vscode.commons.languageserver.java.ProjectObserver; import org.springframework.ide.vscode.commons.languageserver.util.DocumentEventListenerManager; import org.springframework.ide.vscode.commons.languageserver.util.LspClient; +import org.springframework.ide.vscode.commons.languageserver.util.ServerCapabilityInitializer; import org.springframework.ide.vscode.commons.languageserver.util.SimpleLanguageServer; import org.springframework.ide.vscode.commons.util.FileObserver; import org.springframework.ide.vscode.commons.util.LogRedirect; @@ -210,6 +219,10 @@ public class BootLanguageServerBootApp { return SourceLinkFactory.createSourceLinks(server, cuCache, params.projectFinder); } + @Bean ORCompilationUnitCache orcuCache(SimpleLanguageServer server, BootLanguageServerParams params) { + return new ORCompilationUnitCache(params.projectFinder, server, params.projectObserver); + } + @Bean CompilationUnitCache cuCache(SimpleLanguageServer server, BootLanguageServerParams params) { return new CompilationUnitCache(params.projectFinder, server, params.projectObserver); } @@ -288,4 +301,23 @@ public class BootLanguageServerBootApp { @Bean FutureProjectFinder futureProjectFinder(JavaProjectFinder projectFinder, Optional projectObserver) { return new FutureProjectFinder(projectFinder, projectObserver); } + + @Bean RewriteRefactorings rewriteRefactorings(ApplicationContext appContext) { + return new RewriteRefactorings(); + } + + @Bean + ServerCapabilityInitializer bootServerCapabilitiesInitializer() { + return (InitializeParams params, ServerCapabilities cap) -> { + CodeActionOptions codeActionOptions = new CodeActionOptions(); + codeActionOptions.setCodeActionKinds(List.of(CodeActionKind.Refactor, CodeActionKind.QuickFix)); + codeActionOptions.setResolveProvider(true); + codeActionOptions.setWorkDoneProgress(true); + cap.setCodeActionProvider(codeActionOptions); + }; + } + + @Bean RewriteRecipeRepository rewriteRecipesRepository(SimpleLanguageServer server, JavaProjectFinder projectFinder) { + return new RewriteRecipeRepository(server, projectFinder); + } } diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/BootLanguageServerInitializer.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/BootLanguageServerInitializer.java index b7771e87d..a8132e789 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/BootLanguageServerInitializer.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/BootLanguageServerInitializer.java @@ -120,6 +120,8 @@ public class BootLanguageServerInitializer implements InitializingBean { HoverHandler hoverHandler = components.getHoverProvider(); documents.onHover(hoverHandler); + components.getCodeActionProvider().ifPresent(documents::onCodeAction); + config.addListener(evt -> { components.getReconcileEngine().ifPresent(reconciler -> { log.info("A configuration changed, triggering reconcile on all open documents"); diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/RewriteConfig.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/RewriteConfig.java new file mode 100644 index 000000000..79af87818 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/RewriteConfig.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.app; + +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.ide.vscode.boot.java.handlers.AutowiredConstructorReconciler; +import org.springframework.ide.vscode.boot.java.rewrite.ORCompilationUnitCache; +import org.springframework.ide.vscode.boot.java.rewrite.RewriteRecipeRepository; +import org.springframework.ide.vscode.boot.java.rewrite.RewriteRefactorings; +import org.springframework.ide.vscode.boot.java.rewrite.codeaction.ConvertAutowiredField; +import org.springframework.ide.vscode.boot.java.rewrite.codeaction.NoRequestMapping; +import org.springframework.ide.vscode.boot.java.rewrite.codeaction.NoRequestMappings; +import org.springframework.ide.vscode.boot.java.rewrite.quickfix.AutowiredConstructorQuickFixHandler; +import org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFinder; +import org.springframework.ide.vscode.commons.languageserver.quickfix.QuickfixRegistry; +import org.springframework.ide.vscode.commons.languageserver.util.SimpleLanguageServer; + +@Configuration +public class RewriteConfig implements InitializingBean { + + @Autowired + private SimpleLanguageServer server; + + @Autowired + private JavaProjectFinder projectFinder; + + @Autowired + private ORCompilationUnitCache orCuCache; + + @Bean + ConvertAutowiredField convertAutowiredField(SimpleLanguageServer server, JavaProjectFinder projectFinder, + RewriteRefactorings rewriteRefactorings, RewriteRecipeRepository recipesRepo, + ORCompilationUnitCache orCuCache) { + return new ConvertAutowiredField(server, projectFinder, rewriteRefactorings, orCuCache); + } + + @ConditionalOnClass({org.openrewrite.java.spring.NoRequestMappingAnnotation.class}) + @Bean + NoRequestMapping noRequestMapping(SimpleLanguageServer server, JavaProjectFinder projectFinder, + RewriteRefactorings rewriteRefactorings, RewriteRecipeRepository recipesRepo, + ORCompilationUnitCache orCuCache) { + return new NoRequestMapping(server, projectFinder, rewriteRefactorings, orCuCache); + } + + @ConditionalOnClass({org.openrewrite.java.spring.NoRequestMappingAnnotation.class}) + @Bean + NoRequestMappings noRequestMappings(SimpleLanguageServer server, JavaProjectFinder projectFinder, + RewriteRefactorings rewriteRefactorings, RewriteRecipeRepository recipesRepo, + ORCompilationUnitCache orCuCache) { + return new NoRequestMappings(server, projectFinder, rewriteRefactorings, orCuCache); + } + + @Override + public void afterPropertiesSet() throws Exception { + QuickfixRegistry registry = server.getQuickfixRegistry(); + + registry.register(AutowiredConstructorReconciler.REMOVE_UNNECESSARY_AUTOWIRED_FROM_CONSTRUCTOR, new AutowiredConstructorQuickFixHandler(server, projectFinder, orCuCache)); + + } + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/BootJavaLanguageServerComponents.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/BootJavaLanguageServerComponents.java index 482ba1d8d..94a6c2b50 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/BootJavaLanguageServerComponents.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/BootJavaLanguageServerComponents.java @@ -27,6 +27,7 @@ import org.springframework.ide.vscode.boot.app.SpringSymbolIndex; import org.springframework.ide.vscode.boot.java.annotations.AnnotationHierarchyAwareLookup; import org.springframework.ide.vscode.boot.java.autowired.AutowiredHoverProvider; import org.springframework.ide.vscode.boot.java.conditionals.ConditionalsLiveHoverProvider; +import org.springframework.ide.vscode.boot.java.handlers.BootJavaCodeActionProvider; import org.springframework.ide.vscode.boot.java.handlers.BootJavaCodeLensEngine; import org.springframework.ide.vscode.boot.java.handlers.BootJavaDocumentHighlightEngine; import org.springframework.ide.vscode.boot.java.handlers.BootJavaDocumentSymbolHandler; @@ -37,6 +38,7 @@ import org.springframework.ide.vscode.boot.java.handlers.BootJavaWorkspaceSymbol import org.springframework.ide.vscode.boot.java.handlers.CodeLensProvider; import org.springframework.ide.vscode.boot.java.handlers.HighlightProvider; import org.springframework.ide.vscode.boot.java.handlers.HoverProvider; +import org.springframework.ide.vscode.boot.java.handlers.JavaCodeAction; import org.springframework.ide.vscode.boot.java.handlers.ReferenceProvider; import org.springframework.ide.vscode.boot.java.links.SourceLinks; import org.springframework.ide.vscode.boot.java.livehover.ActiveProfilesProvider; @@ -62,6 +64,7 @@ import org.springframework.ide.vscode.commons.languageserver.composable.Language import org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFinder; import org.springframework.ide.vscode.commons.languageserver.java.ProjectObserver; import org.springframework.ide.vscode.commons.languageserver.reconcile.IReconcileEngine; +import org.springframework.ide.vscode.commons.languageserver.util.CodeActionHandler; import org.springframework.ide.vscode.commons.languageserver.util.CodeLensHandler; import org.springframework.ide.vscode.commons.languageserver.util.DocumentHighlightHandler; import org.springframework.ide.vscode.commons.languageserver.util.HoverHandler; @@ -107,6 +110,7 @@ public class BootJavaLanguageServerComponents implements LanguageServerComponent private CodeLensHandler codeLensHandler; private DocumentHighlightHandler highlightsEngine; private BootJavaReconcileEngine reconcileEngine; + private BootJavaCodeActionProvider codeActionProvider; private SpringProcessTracker liveProcessTracker; @@ -175,7 +179,12 @@ public class BootJavaLanguageServerComponents implements LanguageServerComponent highlightsEngine = createDocumentHighlightEngine(indexer); documents.onDocumentHighlight(highlightsEngine); - reconcileEngine = new BootJavaReconcileEngine(cuCache, projectFinder); + reconcileEngine = new BootJavaReconcileEngine(server, cuCache, projectFinder); + + codeActionProvider = new BootJavaCodeActionProvider( + projectFinder, + cuCache, + appContext.getBeansOfType(JavaCodeAction.class).values()); config.addListener(ignore -> { log.info("update live process tracker settings - start"); @@ -200,7 +209,7 @@ public class BootJavaLanguageServerComponents implements LanguageServerComponent log.info("update live process tracker settings - done"); }); - + server.doOnInitialized(this::initialized); server.onShutdown(this::shutdown); } @@ -339,4 +348,10 @@ public class BootJavaLanguageServerComponents implements LanguageServerComponent return LANGUAGES; } + @Override + public Optional getCodeActionProvider() { + return Optional.ofNullable(codeActionProvider); + } + + } diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/SpringJavaProblemType.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/SpringJavaProblemType.java index 36dd8cba2..02e622ee7 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/SpringJavaProblemType.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/SpringJavaProblemType.java @@ -14,7 +14,7 @@ import org.springframework.ide.vscode.commons.languageserver.reconcile.ProblemSe import org.springframework.ide.vscode.commons.languageserver.reconcile.ProblemType; import org.springframework.ide.vscode.commons.util.Assert; -import static org.springframework.ide.vscode.commons.languageserver.reconcile.ProblemSeverity.ERROR;; +import static org.springframework.ide.vscode.commons.languageserver.reconcile.ProblemSeverity.*; /** * This enum is supposed to represent *all* the different types of problems SpringBoot language server @@ -22,7 +22,9 @@ import static org.springframework.ide.vscode.commons.languageserver.reconcile.Pr */ public enum SpringJavaProblemType implements ProblemType { - JAVA_SPEL_EXPRESSION_SYNTAX(ERROR, "SpEL parser raised a ParseException", "SpEL Expression Syntax"); + JAVA_SPEL_EXPRESSION_SYNTAX(ERROR, "SpEL parser raised a ParseException", "SpEL Expression Syntax"), + + JAVA_AUTOWIRED_CONSTRUCTOR(WARNING, "Unnecessary @Autowired over the only constructor", "Unnecessary @Autowired"); private final ProblemSeverity defaultSeverity; private String description; diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/AnnotationParamReconciler.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/AnnotationParamReconciler.java index 0e75cccf7..5b5c95cfb 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/AnnotationParamReconciler.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/AnnotationParamReconciler.java @@ -13,6 +13,7 @@ package org.springframework.ide.vscode.boot.java.handlers; import java.util.List; import java.util.Set; +import org.eclipse.jdt.core.dom.Annotation; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.MemberValuePair; @@ -21,11 +22,12 @@ import org.eclipse.jdt.core.dom.SingleMemberAnnotation; import org.eclipse.jdt.core.dom.StringLiteral; import org.springframework.ide.vscode.boot.java.annotations.AnnotationHierarchies; import org.springframework.ide.vscode.commons.languageserver.reconcile.IProblemCollector; +import org.springframework.ide.vscode.commons.util.text.IDocument; /** * @author Martin Lippert */ -public class AnnotationParamReconciler { +public class AnnotationParamReconciler implements AnnotationReconciler { private final String annotationType; private final String paramName; @@ -41,8 +43,16 @@ public class AnnotationParamReconciler { this.paramValuePostfix = paramValuePostfix; this.reconciler = reconciler; } + + public void visit(IDocument doc, Annotation node, ITypeBinding typeBinding, IProblemCollector problemCollector) { + if (node instanceof SingleMemberAnnotation) { + visitSingleMemberAnnotation((SingleMemberAnnotation) node, typeBinding, problemCollector); + } else if (node instanceof NormalAnnotation) { + visitNornalAnnotation((NormalAnnotation) node, typeBinding, problemCollector); + } + } - public void visit(SingleMemberAnnotation node, ITypeBinding typeBinding, IProblemCollector problemCollector) { + protected void visitSingleMemberAnnotation(SingleMemberAnnotation node, ITypeBinding typeBinding, IProblemCollector problemCollector) { if (this.paramName != null) { return; } @@ -59,7 +69,7 @@ public class AnnotationParamReconciler { } } - public void visit(NormalAnnotation node, ITypeBinding typeBinding, IProblemCollector problemCollector) { + protected void visitNornalAnnotation(NormalAnnotation node, ITypeBinding typeBinding, IProblemCollector problemCollector) { if (paramName == null) { return; } diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/AnnotationReconciler.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/AnnotationReconciler.java new file mode 100644 index 000000000..e90c9b173 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/AnnotationReconciler.java @@ -0,0 +1,12 @@ +package org.springframework.ide.vscode.boot.java.handlers; + +import org.eclipse.jdt.core.dom.Annotation; +import org.eclipse.jdt.core.dom.ITypeBinding; +import org.springframework.ide.vscode.commons.languageserver.reconcile.IProblemCollector; +import org.springframework.ide.vscode.commons.util.text.IDocument; + +public interface AnnotationReconciler { + + void visit(IDocument doc, Annotation node, ITypeBinding typeBinding, IProblemCollector problemCollector); + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/AutowiredConstructorReconciler.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/AutowiredConstructorReconciler.java new file mode 100644 index 000000000..8b3be18fe --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/AutowiredConstructorReconciler.java @@ -0,0 +1,87 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.handlers; + +import java.util.List; +import java.util.Optional; + +import org.eclipse.jdt.core.dom.Annotation; +import org.eclipse.jdt.core.dom.IMethodBinding; +import org.eclipse.jdt.core.dom.ITypeBinding; +import org.eclipse.jdt.core.dom.MethodDeclaration; +import org.springframework.ide.vscode.boot.java.Annotations; +import org.springframework.ide.vscode.boot.java.SpringJavaProblemType; +import org.springframework.ide.vscode.commons.languageserver.quickfix.Quickfix.QuickfixData; +import org.springframework.ide.vscode.commons.languageserver.quickfix.QuickfixRegistry; +import org.springframework.ide.vscode.commons.languageserver.quickfix.QuickfixType; +import org.springframework.ide.vscode.commons.languageserver.reconcile.IProblemCollector; +import org.springframework.ide.vscode.commons.languageserver.reconcile.ReconcileProblemImpl; +import org.springframework.ide.vscode.commons.util.text.IDocument; + +public class AutowiredConstructorReconciler implements AnnotationReconciler { + + public static final String REMOVE_UNNECESSARY_AUTOWIRED_FROM_CONSTRUCTOR = "RemoveUnnecessaryConstructorAutowired"; + + private QuickfixRegistry quickfixRegistry; + + public AutowiredConstructorReconciler(QuickfixRegistry quickfixRegistry) { + this.quickfixRegistry = quickfixRegistry; + } + + @Override + public void visit(IDocument doc, Annotation node, ITypeBinding typeBinding, IProblemCollector problemCollector) { + getSingleAutowiredConstructorDeclaringType(node, typeBinding).ifPresent(type -> { + ReconcileProblemImpl problem = new ReconcileProblemImpl(SpringJavaProblemType.JAVA_AUTOWIRED_CONSTRUCTOR, "Unnecesary @Autowired", node.getStartPosition(), node.getLength()); + QuickfixType quickfixType = quickfixRegistry.getQuickfixType(AutowiredConstructorReconciler.REMOVE_UNNECESSARY_AUTOWIRED_FROM_CONSTRUCTOR); + if (quickfixType != null) { + problem.addQuickfix(new QuickfixData<>( + quickfixType, + List.of(doc.getUri(), type.getQualifiedName()), + "Remove unnecessary @Autowired" + )); + } + problemCollector.accept(problem); + }); + } + + static Optional getSingleAutowiredConstructorDeclaringType(Annotation a, ITypeBinding type) { + if (type != null && Annotations.AUTOWIRED.equals(type.getQualifiedName())) { + if (a.getParent() instanceof MethodDeclaration) { + MethodDeclaration method = (MethodDeclaration) a.getParent(); + IMethodBinding methodBinding = method.resolveBinding(); + if (methodBinding != null) { + ITypeBinding declaringType = methodBinding.getDeclaringClass(); + if (declaringType != null && isOnlyOneConstructor(declaringType)) { + return Optional.of(declaringType); + } + } + } + } + return Optional.empty(); + } + + private static boolean isOnlyOneConstructor(ITypeBinding t) { + int numberOfConstructors = 0; + if (!t.isInterface()) { + for (IMethodBinding m : t.getDeclaredMethods()) { + if (m.isConstructor()) { + numberOfConstructors++; + if (numberOfConstructors > 1) { + break; + } + } + } + } + return numberOfConstructors == 1; + } + + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/BootJavaCodeActionProvider.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/BootJavaCodeActionProvider.java new file mode 100644 index 000000000..6958c66dc --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/BootJavaCodeActionProvider.java @@ -0,0 +1,65 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.handlers; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.NodeFinder; +import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.CodeActionCapabilities; +import org.eclipse.lsp4j.Command; +import org.eclipse.lsp4j.jsonrpc.CancelChecker; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.springframework.ide.vscode.boot.java.utils.CompilationUnitCache; +import org.springframework.ide.vscode.commons.java.IJavaProject; +import org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFinder; +import org.springframework.ide.vscode.commons.languageserver.util.CodeActionHandler; +import org.springframework.ide.vscode.commons.util.text.IRegion; +import org.springframework.ide.vscode.commons.util.text.TextDocument; + +public class BootJavaCodeActionProvider implements CodeActionHandler { + + final private JavaProjectFinder projectFinder; + final private CompilationUnitCache cuCache; + private Collection javaCodeActions; + + public BootJavaCodeActionProvider(JavaProjectFinder projectFinder, CompilationUnitCache cuCache, Collection javaCodeActions) { + this.projectFinder = projectFinder; + this.cuCache = cuCache; + this.javaCodeActions = javaCodeActions; + } + + @Override + public List> handle(CancelChecker cancelToken, CodeActionCapabilities capabilities, TextDocument doc, IRegion region) { + Optional project = projectFinder.find(doc.getId()); + if (project.isPresent()) { + return cuCache.withCompilationUnit(project.get(), URI.create(doc.getId().getUri()), cu -> { + ASTNode found = NodeFinder.perform(cu, region.getOffset(), region.getLength()); + List> codeActions = new ArrayList<>(); + for (JavaCodeAction jca : javaCodeActions) { + List> cas = jca.getCodeActions(capabilities, doc, region, project.get(), cu, found); + if (cas != null) { + codeActions.addAll(cas); + } + } + return codeActions; + }); + } + return Collections.emptyList(); + } + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/BootJavaReconcileEngine.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/BootJavaReconcileEngine.java index efaa08d0c..be8ab09f6 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/BootJavaReconcileEngine.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/BootJavaReconcileEngine.java @@ -13,8 +13,10 @@ package org.springframework.ide.vscode.boot.java.handlers; import java.net.URI; import org.eclipse.jdt.core.dom.ASTVisitor; +import org.eclipse.jdt.core.dom.Annotation; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.ITypeBinding; +import org.eclipse.jdt.core.dom.MarkerAnnotation; import org.eclipse.jdt.core.dom.NormalAnnotation; import org.eclipse.jdt.core.dom.SingleMemberAnnotation; import org.eclipse.lsp4j.TextDocumentIdentifier; @@ -24,8 +26,10 @@ import org.springframework.ide.vscode.boot.java.utils.CompilationUnitCache; import org.springframework.ide.vscode.boot.java.value.Constants; import org.springframework.ide.vscode.commons.java.IJavaProject; import org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFinder; +import org.springframework.ide.vscode.commons.languageserver.quickfix.QuickfixRegistry; import org.springframework.ide.vscode.commons.languageserver.reconcile.IProblemCollector; import org.springframework.ide.vscode.commons.languageserver.reconcile.IReconcileEngine; +import org.springframework.ide.vscode.commons.languageserver.util.SimpleLanguageServer; import org.springframework.ide.vscode.commons.util.text.IDocument; /** @@ -50,16 +54,18 @@ public class BootJavaReconcileEngine implements IReconcileEngine { private final JavaProjectFinder projectFinder; private final CompilationUnitCache compilationUnitCache; - private final AnnotationParamReconciler[] reconcilers; + private final AnnotationReconciler[] reconcilers; private final SpelExpressionReconciler spelExpressionReconciler; + private final QuickfixRegistry quickfixRegistry; - public BootJavaReconcileEngine(CompilationUnitCache compilationUnitCache, JavaProjectFinder projectFinder) { + public BootJavaReconcileEngine(SimpleLanguageServer server, CompilationUnitCache compilationUnitCache, JavaProjectFinder projectFinder) { this.compilationUnitCache = compilationUnitCache; this.projectFinder = projectFinder; + this.quickfixRegistry = server.getQuickfixRegistry(); this.spelExpressionReconciler = new SpelExpressionReconciler(); - this.reconcilers = new AnnotationParamReconciler[] { + this.reconcilers = new AnnotationReconciler[] { new AnnotationParamReconciler(Constants.SPRING_VALUE, null, "#{", "}", spelExpressionReconciler), new AnnotationParamReconciler(Constants.SPRING_VALUE, "value", "#{", "}", spelExpressionReconciler), @@ -83,7 +89,9 @@ public class BootJavaReconcileEngine implements IReconcileEngine { new AnnotationParamReconciler(SPRING_POST_FILTER, "value", "", "", spelExpressionReconciler), new AnnotationParamReconciler(SPRING_CONDITIONAL_ON_EXPRESSION, null, "", "", spelExpressionReconciler), - new AnnotationParamReconciler(SPRING_CONDITIONAL_ON_EXPRESSION, "value", "", "", spelExpressionReconciler) + new AnnotationParamReconciler(SPRING_CONDITIONAL_ON_EXPRESSION, "value", "", "", spelExpressionReconciler), + + new AutowiredConstructorReconciler(quickfixRegistry) }; } @@ -103,7 +111,7 @@ public class BootJavaReconcileEngine implements IReconcileEngine { compilationUnitCache.withCompilationUnit(project, uri, cu -> { if (cu != null) { - reconcileAST(cu, problemCollector); + reconcileAST(doc, cu, problemCollector); } return null; @@ -115,13 +123,13 @@ public class BootJavaReconcileEngine implements IReconcileEngine { } } - private void reconcileAST(CompilationUnit cu, IProblemCollector problemCollector) { + private void reconcileAST(IDocument doc, CompilationUnit cu, IProblemCollector problemCollector) { cu.accept(new ASTVisitor() { @Override public boolean visit(SingleMemberAnnotation node) { try { - visitAnnotationWithDefaultParam(node, problemCollector); + visitAnnotation(doc, node, problemCollector); } catch (Exception e) { } @@ -131,32 +139,32 @@ public class BootJavaReconcileEngine implements IReconcileEngine { @Override public boolean visit(NormalAnnotation node) { try { - visitAnnotationWithParams(node, problemCollector); + visitAnnotation(doc, node, problemCollector); } catch (Exception e) { } return super.visit(node); } + + @Override + public boolean visit(MarkerAnnotation node) { + try { + visitAnnotation(doc, node, problemCollector); + } + catch (Exception e) { + } + return super.visit(node); + } }); } - protected void visitAnnotationWithDefaultParam(SingleMemberAnnotation node, IProblemCollector problemCollector) { + protected void visitAnnotation(IDocument doc, Annotation node, IProblemCollector problemCollector) { ITypeBinding typeBinding = node.resolveTypeBinding(); if (typeBinding != null) { for (int i = 0; i < reconcilers.length; i++) { - reconcilers[i].visit(node, typeBinding, problemCollector); - } - } - } - - protected void visitAnnotationWithParams(NormalAnnotation node, IProblemCollector problemCollector) { - ITypeBinding typeBinding = node.resolveTypeBinding(); - - if (typeBinding != null) { - for (int i = 0; i < reconcilers.length; i++) { - reconcilers[i].visit(node, typeBinding, problemCollector); + reconcilers[i].visit(doc, node, typeBinding, problemCollector); } } } diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/JavaCodeAction.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/JavaCodeAction.java new file mode 100644 index 000000000..b77f52303 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/handlers/JavaCodeAction.java @@ -0,0 +1,32 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.handlers; + +import java.util.List; + +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.CodeActionCapabilities; +import org.eclipse.lsp4j.Command; +import org.eclipse.lsp4j.WorkspaceEdit; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.springframework.ide.vscode.commons.java.IJavaProject; +import org.springframework.ide.vscode.commons.util.text.IRegion; +import org.springframework.ide.vscode.commons.util.text.TextDocument; + +public interface JavaCodeAction { + + default WorkspaceEdit perform(List args) { return null; } + + List> getCodeActions(CodeActionCapabilities capabilities, TextDocument doc, IRegion region, IJavaProject project, CompilationUnit cu, ASTNode node); + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/ConvertAutowiredParameterIntoConstructorParameter.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/ConvertAutowiredParameterIntoConstructorParameter.java new file mode 100644 index 000000000..62b6cd2c4 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/ConvertAutowiredParameterIntoConstructorParameter.java @@ -0,0 +1,200 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.rewrite; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.openrewrite.Cursor; +import org.openrewrite.ExecutionContext; +import org.openrewrite.Recipe; +import org.openrewrite.TreeVisitor; +import org.openrewrite.java.AnnotationMatcher; +import org.openrewrite.java.JavaIsoVisitor; +import org.openrewrite.java.JavaTemplate; +import org.openrewrite.java.JavaVisitor; +import org.openrewrite.java.RemoveAnnotationVisitor; +import org.openrewrite.java.tree.J; +import org.openrewrite.java.tree.J.Block; +import org.openrewrite.java.tree.J.ClassDeclaration; +import org.openrewrite.java.tree.J.Empty; +import org.openrewrite.java.tree.J.MethodDeclaration; +import org.openrewrite.java.tree.J.VariableDeclarations; +import org.openrewrite.java.tree.JavaType.FullyQualified; +import org.openrewrite.java.tree.Statement; +import org.openrewrite.java.tree.TypeTree; +import org.openrewrite.java.tree.TypeUtils; +import org.springframework.ide.vscode.boot.java.Annotations; + +public class ConvertAutowiredParameterIntoConstructorParameter extends Recipe { + + private String classFqName; + private String fieldName; + + public ConvertAutowiredParameterIntoConstructorParameter(String classFqName, String fieldName) { + super(); + this.classFqName = classFqName; + this.fieldName = fieldName; + } + + @Override + public String getDisplayName() { + return "Convert autowired field into constructor parameter"; + } + + @Override + protected TreeVisitor getVisitor() { + return new JavaVisitor() { + + @Override + public J visitClassDeclaration(ClassDeclaration classDecl, ExecutionContext p) { + if (classFqName.equals(classDecl.getType().getFullyQualifiedName())) { + return super.visitClassDeclaration(classDecl, p); + } + return classDecl; + } + + @Override + public J visitVariableDeclarations(VariableDeclarations multiVariable, ExecutionContext p) { + Cursor blockCursor = getCursor().dropParentUntil(Block.class::isInstance); + VariableDeclarations mv = multiVariable; + if (blockCursor != null && blockCursor.getParent().getValue() instanceof ClassDeclaration + && multiVariable.getVariables().size() == 1 + && fieldName.equals(multiVariable.getVariables().get(0).getName().printTrimmed())) { + + mv = (VariableDeclarations) new RemoveAnnotationVisitor(new AnnotationMatcher("@" + Annotations.AUTOWIRED)).visit(multiVariable, p); + doAfterVisit(new AddContructorParameterVisitor(classFqName, fieldName, multiVariable.getTypeExpression())); + } + return mv; + } + + }; + } + + private static class AddContructorParameterVisitor extends JavaVisitor { + + private String classFqName; + private String fieldName; + private TypeTree type; + + public AddContructorParameterVisitor(String classFqName, String fieldName, TypeTree type) { + super(); + this.classFqName = classFqName; + this.fieldName = fieldName; + this.type = type; + } + + @Override + public J visitClassDeclaration(ClassDeclaration classDecl, ExecutionContext p) { + ClassDeclaration c = classDecl; + if (classFqName.equals(c.getType().getFullyQualifiedName())) { + List constructors = ORAstUtils.getMethods(c).stream().filter(m -> m.isConstructor()).collect(Collectors.toList()); + if (constructors.isEmpty()) { + doAfterVisit(new AddConstructorVisitor(c.getSimpleName(), fieldName, type)); + } else { + Optional autowiredConstructor = constructors.stream().filter(constr -> constr.getLeadingAnnotations().stream() + .map(a -> TypeUtils.asFullyQualified(a.getType())) + .filter(Objects::nonNull) + .map(fq -> fq.getFullyQualifiedName()) + .filter(fqn -> Annotations.AUTOWIRED.equals(fqn)) + .findFirst() + .isPresent() + ) + .findFirst(); + if (autowiredConstructor.isPresent()) { + // Autowired constructor found - add argument to it + doAfterVisit(new AddMethodParameter(autowiredConstructor.get(), fieldName, type)); + } else { + if (constructors.size() == 1) { + doAfterVisit(new AddMethodParameter(constructors.get(0), fieldName, type)); + } + } + } + } + return c; + } + + } + + private static class AddConstructorVisitor extends JavaVisitor { + private String className; + private String fieldName; + private TypeTree type; + + public AddConstructorVisitor(String className, String fieldName, TypeTree type) { + this.className = className; + this.fieldName = fieldName; + this.type = type; + } + + @Override + public J visitBlock(Block block, ExecutionContext p) { + if (getCursor().getParent() != null) { + Object n = getCursor().getParent().getValue(); + if (n instanceof ClassDeclaration) { + ClassDeclaration classDecl = (ClassDeclaration) n; + if (classDecl.getKind() == ClassDeclaration.Kind.Type.Class && className.equals(classDecl.getSimpleName())) { + JavaTemplate.Builder template = JavaTemplate.builder(() -> getCursor(), "" + + classDecl.getSimpleName() + "(" + type.printTrimmed() + " " + fieldName + ") {\n" + + "this." + fieldName + " = " + fieldName + ";\n" + + "}\n" + ); + FullyQualified fq = TypeUtils.asFullyQualified(type.getType()); + if (fq != null) { + template.imports(fq.getFullyQualifiedName()); + maybeAddImport(fq); + } + Optional firstMethod = block.getStatements().stream().filter(MethodDeclaration.class::isInstance).findFirst(); + if (firstMethod.isPresent()) { + return block.withTemplate(template.build(), firstMethod.get().getCoordinates().before()); + } else { + return block.withTemplate(template.build(), block.getCoordinates().lastStatement()); + } + } + } + } + return block; + } + } + + private static class AddMethodParameter extends JavaIsoVisitor { + + private MethodDeclaration method; + private String fieldName; + private TypeTree type; + + public AddMethodParameter(MethodDeclaration method, String fieldName, TypeTree type) { + this.method = method; + this.fieldName = fieldName; + this.type = type; + } + + @Override + public MethodDeclaration visitMethodDeclaration(MethodDeclaration method, ExecutionContext p) { + if (method == this.method) { + String paramsStr = Stream.concat(method.getParameters().stream().filter(s -> !Empty.class.isInstance(s)).map(s -> s.printTrimmed()), Stream.of(type.printTrimmed() + " " + fieldName)).collect(Collectors.joining(", ")); + JavaTemplate.Builder paramsTemplate = JavaTemplate.builder(() -> getCursor(), paramsStr); + JavaTemplate.Builder statementTemplate = JavaTemplate.builder(() -> getCursor(), "this." + fieldName + " = " + fieldName + ";\n"); + return method + .withTemplate(paramsTemplate.build(), method.getCoordinates().replaceParameters()) + .withTemplate(statementTemplate.build(), method.getBody().getCoordinates().lastStatement()); + } + return method; + } + + + + } + +} \ No newline at end of file diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/MavenProjectParser.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/MavenProjectParser.java new file mode 100644 index 000000000..ff7fdabca --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/MavenProjectParser.java @@ -0,0 +1,334 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.rewrite; + +import static org.openrewrite.Tree.randomId; + +import java.io.FileReader; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.function.BiPredicate; +import java.util.function.UnaryOperator; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import org.openrewrite.ExecutionContext; +import org.openrewrite.SourceFile; +import org.openrewrite.internal.ListUtils; +import org.openrewrite.java.JavaParser; +import org.openrewrite.java.marker.JavaProject; +import org.openrewrite.java.marker.JavaSourceSet; +import org.openrewrite.java.marker.JavaVersion; +import org.openrewrite.marker.BuildTool; +import org.openrewrite.marker.Marker; +import org.openrewrite.maven.MavenParser; +import org.openrewrite.maven.tree.Dependency; +import org.openrewrite.maven.tree.MavenResolutionResult; +import org.openrewrite.maven.tree.Pom; +import org.openrewrite.maven.tree.ResolvedPom; +import org.openrewrite.properties.PropertiesParser; +import org.openrewrite.xml.XmlParser; +import org.openrewrite.xml.tree.Xml; +import org.openrewrite.yaml.YamlParser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Parse a Maven project on disk into a list of {@link org.openrewrite.SourceFile} including + * Maven, Java, YAML, properties, and XML AST representations of sources and resources found. + */ +public class MavenProjectParser { + + private static final Pattern mavenWrapperVersionPattern = Pattern.compile(".*apache-maven/(.*?)/.*"); + private static final Logger logger = LoggerFactory.getLogger(MavenProjectParser.class); + + private final MavenParser mavenParser; + private final JavaParser.Builder javaParserBuilder; + private final ExecutionContext ctx; + + public MavenProjectParser(MavenParser.Builder mavenParserBuilder, + JavaParser.Builder javaParserBuilder, + ExecutionContext ctx) { + this.mavenParser = mavenParserBuilder.build(); + this.javaParserBuilder = javaParserBuilder; + this.ctx = ctx; + } + + /** + * Given a root path to a maven project, this parser will parse the maven project (including submodules) + * and return a list of ALL source files for all maven modules under the root path. + *
+     * Notes About Provenance Information:
+     *
+     * There are always three markers applied to each source file and there can potentially be up to five provenance
+     * markers in total:
+     *
+     * BuildTool     - What build tool was used to compile the source file (This will always be Maven)
+     * JavaVersion   - What Java version/vendor was used when compiling the source file.
+     * JavaProject   - For each maven module/sub-module, the same JavaProject will be associated with ALL source files
+     *                 belonging to that module.
+     *
+     * Optional:
+     *
+     * GitProvenance - If the entire project exists in the context of a git repository, all source files (for all modules) will have the same GitProvenance.
+     * JavaSourceSet - All Java source files and all resource files that exist in src/main or src/test will have a JavaSourceSet marker assigned to them.
+     *
+     * 
+ * @param projectDirectory A path to the root folder containing a meven project. + * @return A list of source files that have been parsed from the root folder + */ + public List parse(Path projectDirectory, List dependencies) { + List mavens = mavenParser.parse(getMavenPoms(projectDirectory, ctx), projectDirectory, ctx); + mavens = sort(mavens); + + JavaParser javaParser = javaParserBuilder.build(); + + logger.info("The order in which projects are being parsed is:"); + for (Xml.Document maven : mavens) { + logger.info(" {}:{}", getModel(maven).getGroupId(), getModel(maven).getArtifactId()); + } + + List sourceFiles = new ArrayList<>(); + for (Xml.Document maven : mavens) { + List projectProvenance = getJavaProvenance(maven, projectDirectory); + sourceFiles.add(addProjectProvenance(maven, projectProvenance)); + +// List dependencies = downloadArtifacts(getResolvedPom(maven).getDependencies().get(Scope.Compile)); + javaParser.setSourceSet("main"); + javaParser.setClasspath(dependencies); + sourceFiles.addAll(ListUtils.map(javaParser.parse( + getJavaSources(getModel(maven).getRequested(), projectDirectory, ctx), projectDirectory, ctx), addProvenance(projectProvenance))); + //Resources in the src/main should also have the main source set attached to them. + parseResources(getResources(getModel(maven).getRequested(), projectDirectory, ctx), projectDirectory, sourceFiles, projectProvenance, javaParser.getSourceSet(ctx)); + +// List testDependencies = downloadArtifacts(maven.getModel().getDependencies(Scope.Test)); + javaParser.setSourceSet("test"); +// javaParser.setClasspath(testDependencies); + sourceFiles.addAll(ListUtils.map(javaParser.parse( + getTestJavaSources(getModel(maven).getRequested(), projectDirectory, ctx), projectDirectory, ctx), addProvenance(projectProvenance))); + //Resources in the src/test should also have the test source set attached to them. + parseResources(getTestResources(getModel(maven).getRequested(), projectDirectory, ctx), projectDirectory, sourceFiles, projectProvenance, javaParser.getSourceSet(ctx)); + } + + return sourceFiles; + } + + private List getJavaProvenance(Xml.Document maven, Path projectDirectory) { + ResolvedPom mavenModel = getModel(maven); + String javaRuntimeVersion = System.getProperty("java.runtime.version"); + String javaVendor = System.getProperty("java.vm.vendor"); + String sourceCompatibility = javaRuntimeVersion; + String targetCompatibility = javaRuntimeVersion; + String propertiesSourceCompatibility = mavenModel.getValue(mavenModel.getValue("maven.compiler.source")); + if (propertiesSourceCompatibility != null) { + sourceCompatibility = propertiesSourceCompatibility; + } + String propertiesTargetCompatibility = mavenModel.getValue(mavenModel.getValue("maven.compiler.target")); + if (propertiesTargetCompatibility != null) { + targetCompatibility = propertiesTargetCompatibility; + } + + Path wrapperPropertiesPath = projectDirectory.resolve(".mvn/wrapper/maven-wrapper.properties"); + String mavenVersion = "3.6"; + if (Files.exists(wrapperPropertiesPath)) { + try { + Properties wrapperProperties = new Properties(); + wrapperProperties.load(new FileReader(wrapperPropertiesPath.toFile())); + String distributionUrl = (String) wrapperProperties.get("distributionUrl"); + if (distributionUrl != null) { + Matcher wrapperVersionMatcher = mavenWrapperVersionPattern.matcher(distributionUrl); + if (wrapperVersionMatcher.matches()) { + mavenVersion = wrapperVersionMatcher.group(1); + } + } + } catch (IOException e) { + ctx.getOnError().accept(e); + } + } + + return Arrays.asList( + new BuildTool(randomId(), BuildTool.Type.Maven, mavenVersion), + new JavaVersion(randomId(), javaRuntimeVersion, javaVendor, sourceCompatibility, targetCompatibility), + new JavaProject(randomId(), mavenModel.getRequested().getName(), new JavaProject.Publication( + mavenModel.getGroupId(), + mavenModel.getArtifactId(), + mavenModel.getVersion() + )) + ); + } + + private void parseResources(List resources, Path projectDirectory, List sourceFiles, List projectProvenance, JavaSourceSet sourceSet) { + List provenance = new ArrayList<>(projectProvenance); + provenance.add(sourceSet); + + sourceFiles.addAll(ListUtils.map(new XmlParser().parse( + resources.stream() + .filter(p -> p.getFileName().toString().endsWith(".xml") || + p.getFileName().toString().endsWith(".wsdl") || + p.getFileName().toString().endsWith(".xhtml") || + p.getFileName().toString().endsWith(".xsd") || + p.getFileName().toString().endsWith(".xsl") || + p.getFileName().toString().endsWith(".xslt")) + .collect(Collectors.toList()), + projectDirectory, + ctx + ), addProvenance(provenance))); + + sourceFiles.addAll(ListUtils.map(new YamlParser().parse( + resources.stream() + .filter(p -> p.getFileName().toString().endsWith(".yml") || p.getFileName().toString().endsWith(".yaml")) + .collect(Collectors.toList()), + projectDirectory, + ctx + ), addProvenance(provenance))); + + sourceFiles.addAll(ListUtils.map(new PropertiesParser().parse( + resources.stream() + .filter(p -> p.getFileName().toString().endsWith(".properties")) + .collect(Collectors.toList()), + projectDirectory, + ctx + ), addProvenance(provenance))); + } + + private S addProjectProvenance(S s, List projectProvenance) { + for (Marker marker : projectProvenance) { + s = s.withMarkers(s.getMarkers().addIfAbsent(marker)); + } + return s; + } + + private UnaryOperator addProvenance(List projectProvenance) { + return s -> { + s = addProjectProvenance(s, projectProvenance); + return s; + }; + } + +// private List downloadArtifacts(Set dependencies) { +// return dependencies.stream() +// .filter(d -> d.getRepository() != null) +// .map(artifactDownloader::downloadArtifact) +// .filter(Objects::nonNull) +// .collect(Collectors.toList()); +// } + + public static List sort(List mavens) { + // the value is the set of maven projects that depend on the key + Map> byDependedOn = new HashMap<>(); + + for (Xml.Document maven : mavens) { + byDependedOn.computeIfAbsent(maven, m -> new HashSet<>()); + for (Dependency dependency : getModel(maven).getRequested().getDependencies()) { + for (Xml.Document test : mavens) { + if (getModel(test).getGroupId().equals(dependency.getGroupId()) && + getModel(test).getArtifactId().equals(dependency.getArtifactId())) { + byDependedOn.computeIfAbsent(maven, m -> new HashSet<>()).add(test); + } + } + } + } + + List sorted = new ArrayList<>(mavens.size()); + next: + while (!byDependedOn.isEmpty()) { + for (Map.Entry> mavenAndDependencies : byDependedOn.entrySet()) { + if (mavenAndDependencies.getValue().isEmpty()) { + Xml.Document maven = mavenAndDependencies.getKey(); + byDependedOn.remove(maven); + sorted.add(maven); + for (Set dependencies : byDependedOn.values()) { + dependencies.remove(maven); + } + continue next; + } + } + } + + return sorted; + } + + private static List getSources(Path srcDir, ExecutionContext ctx, String... fileTypes) { + if (!srcDir.toFile().exists()) { + return List.of(); + } + + BiPredicate predicate = (p, bfa) -> + bfa.isRegularFile() && Arrays.stream(fileTypes).anyMatch(type -> p.getFileName().toString().endsWith(type)); + try { + return Files.find(srcDir, 999, predicate).collect(Collectors.toList()); + } catch (IOException e) { + ctx.getOnError().accept(e); + return List.of(); + } + } + + public static List getMavenPoms(Path projectDir, ExecutionContext ctx) { + return getSources(projectDir, ctx, "pom.xml").stream() + .filter(p -> p.getFileName().toString().equals("pom.xml") && + !p.toString().contains("/src/")) + .collect(Collectors.toList()); + } + + private static ResolvedPom getModel(Xml.Document maven) { + MavenResolutionResult pom = getResolvedPom(maven); + return pom == null ? null : pom.getPom(); + } + + private static MavenResolutionResult getResolvedPom(Xml.Document maven) { + return maven.getMarkers().findFirst(MavenResolutionResult.class).orElse(null); + } + + private static List getJavaSources(Pom pom, Path projectDir, ExecutionContext ctx) { + if (pom.getPackaging() != null && !"jar".equals(pom.getPackaging()) && !"bundle".equals(pom.getPackaging())) { + return List.of(); + } + return getSources(projectDir.resolve(pom.getSourcePath()).getParent().resolve(Paths.get("src", "main", "java")), + ctx, ".java"); + } + + private static List getTestJavaSources(Pom pom, Path projectDir, ExecutionContext ctx) { + if (pom.getPackaging() != null && !"jar".equals(pom.getPackaging()) && !"bundle".equals(pom.getPackaging())) { + return List.of(); + } + return getSources(projectDir.resolve(pom.getSourcePath()).getParent().resolve(Paths.get("src", "test", "java")), + ctx, ".java"); + } + + private static List getResources(Pom pom, Path projectDir, ExecutionContext ctx) { + if (pom.getPackaging() != null && !"jar".equals(pom.getPackaging()) && !"bundle".equals(pom.getPackaging())) { + return List.of(); + } + return getSources(projectDir.resolve(pom.getSourcePath()).getParent().resolve(Paths.get("src", "main", "resources")), + ctx, ".properties", ".xml", ".yml", ".yaml"); + } + + private static List getTestResources(Pom pom, Path projectDir, ExecutionContext ctx) { + if (pom.getPackaging() != null && !"jar".equals(pom.getPackaging()) && !"bundle".equals(pom.getPackaging())) { + return List.of(); + } + return getSources(projectDir.resolve(pom.getSourcePath()).getParent().resolve(Paths.get("src", "test", "resources")), + ctx, ".properties", ".xml", ".yml", ".yaml"); + } + + +} \ No newline at end of file diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/ORAstUtils.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/ORAstUtils.java new file mode 100644 index 000000000..cf9736cec --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/ORAstUtils.java @@ -0,0 +1,337 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.rewrite; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.openrewrite.ExecutionContext; +import org.openrewrite.InMemoryExecutionContext; +import org.openrewrite.Parser; +import org.openrewrite.Recipe; +import org.openrewrite.Tree; +import org.openrewrite.TreeVisitor; +import org.openrewrite.java.JavaParser; +import org.openrewrite.java.JavaVisitor; +import org.openrewrite.java.tree.J; +import org.openrewrite.java.tree.J.CompilationUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ORAstUtils { + + private static final Logger log = LoggerFactory.getLogger(ORAstUtils.class); + +// private static class ParentMarker implements Marker { +// +// private UUID uuid; +// private J parent; +// +// public ParentMarker(J parent) { +// this.uuid = Tree.randomId(); +// this.parent = parent; +// } +// +// @Override +// public UUID getId() { +// return uuid; +// } +// +// public J getParent() { +// return parent; +// } +// +// public J getGrandParent() { +// if (parent != null) { +// return parent.getMarkers().findFirst(ParentMarker.class).map(m -> m.getParent()).orElse(null); +// } +// return null; +// } +// +// public T getFirstAnsector(Class clazz) { +// if (clazz.isInstance(parent)) { +// return clazz.cast(parent); +// } else if (parent != null) { +// return parent.getMarkers().findFirst(ParentMarker.class).map(m -> m.getFirstAnsector(clazz)).orElse(null); +// } +// return null; +// } +// +// @Override +// public T withId(UUID id) { +// this.uuid = id; +// return (T) this; +// } +// } +// +// private static class AncestersMarker implements Marker { +// +// private UUID uuid; +// private List ancesters = List.of(); +// +// public AncestersMarker(List ancesters) { +// this.uuid = Tree.randomId(); +// this.ancesters = ancesters; +// } +// +// @Override +// public UUID getId() { +// return uuid; +// } +// +// @SuppressWarnings("unchecked") +// public T getFirstAnsector(Class clazz) { +// if (ancesters != null) { +// for (J node : ancesters) { +// if (clazz.isInstance(node)) { +// return (T) node; +// } +// } +// } +// return null; +// } +// +// public J getParent() { +// if (ancesters != null && !ancesters.isEmpty()) { +// return ancesters.get(0); +// } +// return null; +// } +// +// public J getGrandParent() { +// if (ancesters != null && ancesters.size() > 1) { +// return ancesters.get(1); +// } +// return null; +// } +// } +// +// private static class MarkParentRecipe extends Recipe { +// +// @Override +// public String getDisplayName() { +// return "Create parent AST node references via markers"; +// } +// +// @Override +// protected TreeVisitor getVisitor() { +// return new JavaIsoVisitor<>() { +// +// private Cursor parentCursor(Class clazz) { +// for (Cursor c = getCursor(); c != null +// && !(c.getValue() instanceof SourceFile); c = c.getParent()) { +// Object o = c.getValue(); +// if (clazz.isInstance(o)) { +// return c; +// } +// } +// return null; +// } +// +// @Override +// public J visit(Tree tree, ExecutionContext p) { +// if (tree instanceof J) { +// J j = (J) tree; +// J newJ = super.visit(j, p).withMarkers(j.getMarkers().addIfAbsent(new ParentMarker(null))); +// +// List children = p.pollMessage(j.getId().toString(), Collections.emptyList()); +// for (J child : children) { +// child.getMarkers().findFirst(ParentMarker.class).map(m -> m.parent = newJ); +// } +// +// // Prepare myself for the parent; +// +// Cursor parentCursor = parentCursor(J.class); +// if (parentCursor != null) { +// J parent = parentCursor.getValue(); +// String parentId = parent.getId().toString(); +// List siblings = p.pollMessage(parentId, new ArrayList()); +// siblings.add(newJ); +// p.putMessage(parentId, siblings); +// } +// return newJ; +// } +// return (J) tree; +// } +// }; +// } +// +// } +// +// public static J findAstNodeAt(CompilationUnit cu, int offset) { +// AtomicReference f = new AtomicReference<>(); +// new JavaIsoVisitor>() { +// public J visit(Tree tree, AtomicReference found) { +// if (tree == null) { +// return null; +// } +// if (found.get() == null && tree instanceof J) { +// J node = (J) tree; +// Range range = node.getMarkers().findFirst(Range.class).orElse(null); +// if (range != null +// && range.getStart().getOffset() <= offset +// && offset <= range.getEnd().getOffset()) { +// super.visit(tree, found); +// if (found.get() == null) { +// found.set(node); +// return node; +// } +// } else { +// return (J) tree; +// } +// } +// return (J) tree; +// }; +// }.visitNonNull(cu, f); +// return f.get(); +// } +// +// @SuppressWarnings("unchecked") +// public static T findNode(J node, Class clazz) { +// if (clazz.isInstance(node)) { +// return (T) node; +// } +// return node.getMarkers().findFirst(ParentMarker.class).map(m -> m.getFirstAnsector(clazz)).orElse(null); +// } +// +// public static J getParent(J node) { +// return node.getMarkers().findFirst(ParentMarker.class).map(m -> m.getParent()).orElse(null); +// } + + public static List parse(JavaParser parser, Iterable sourceFiles) { + InMemoryExecutionContext ctx = new InMemoryExecutionContext(e -> log.error("", e)); + ctx.putMessage(JavaParser.SKIP_SOURCE_SET_TYPE_GENERATION, true); + List cus = parser.parse(sourceFiles, null, ctx); + return cus; +// List results = new UpdateSourcePositions().doNext(new MarkParentRecipe()).run(cus); +// return results.stream().map(r -> r.getAfter() == null ? r.getBefore() : r.getAfter()).map(CompilationUnit.class::cast).collect(Collectors.toList()); + } + + public static List parseInputs(JavaParser parser, Iterable inputs) { + InMemoryExecutionContext ctx = new InMemoryExecutionContext(e -> log.error("", e)); + ctx.putMessage(JavaParser.SKIP_SOURCE_SET_TYPE_GENERATION, true); + List cus = parser.parseInputs(inputs, null, ctx); + return cus; +// List results = new UpdateSourcePositions().doNext(new MarkParentRecipe()).run(cus); +// return results.stream().map(r -> r.getAfter() == null ? r.getBefore() : r.getAfter()).map(CompilationUnit.class::cast).collect(Collectors.toList()); + } + + public static J.EnumValueSet getEnumValues(J.ClassDeclaration classDecl) { + return classDecl.getBody().getStatements().stream() + .filter(J.EnumValueSet.class::isInstance) + .map(J.EnumValueSet.class::cast) + .findAny() + .orElse(null); + } + + public static List getFields(J.ClassDeclaration classDecl) { + return classDecl.getBody().getStatements().stream() + .filter(J.VariableDeclarations.class::isInstance) + .map(J.VariableDeclarations.class::cast) + .collect(Collectors.toList()); + } + + public static List getMethods(J.ClassDeclaration classDecl) { + return classDecl.getBody().getStatements().stream() + .filter(J.MethodDeclaration.class::isInstance) + .map(J.MethodDeclaration.class::cast) + .collect(Collectors.toList()); + } + + public static String getSimpleName(String fqName) { + int idx = fqName.lastIndexOf('.'); + if (idx < fqName.length() - 1) { + return fqName.substring(idx + 1); + } + return fqName; + } + + @SuppressWarnings("unchecked") + private static TreeVisitor getVisitor(Recipe r) { + try { + Method m = Recipe.class.getDeclaredMethod("getVisitor"); + m.setAccessible(true); + return (TreeVisitor) m.invoke(r); + } catch (Exception e) { + return null; + } + } + + @SuppressWarnings("unchecked") + private static List> getAfterVisitors(TreeVisitor visitor) { + try { + Method m = TreeVisitor.class.getDeclaredMethod("getAfterVisit"); + m.setAccessible(true); + return (List>) m.invoke(visitor); + } catch (Exception e) { + return Collections.emptyList(); + } + } + + private static void makeVisitorNonTopLevel(JavaVisitor visitor) { + try { + Field f = TreeVisitor.class.getDeclaredField("afterVisit"); + f.setAccessible(true); + f.set(visitor, new ArrayList<>()); + } catch (Exception e) { + // ignore + } + } + + @SuppressWarnings("unchecked") + public static Recipe nodeRecipe(Recipe r, Predicate condition) { + return new NodeRecipe((JavaVisitor) getVisitor(r), condition); + } + + private static class NodeRecipe extends Recipe { + + private JavaVisitor visitor; + private Predicate condition; + + public NodeRecipe(JavaVisitor visitor, Predicate condition) { + this.visitor = visitor; + this.condition = condition; + } + + @Override + public String getDisplayName() { + return ""; + } + + @Override + protected TreeVisitor getVisitor() { + return new JavaVisitor<>() { + + @Override + public J visit(Tree tree, ExecutionContext ctx) { + J t = super.visit(tree, ctx); + if (condition.test(t)) { + makeVisitorNonTopLevel(visitor); + t = visitor.visit(t, ctx, getCursor()); + for (TreeVisitor v : getAfterVisitors(visitor)) { + doAfterVisit(v); + } + } + return t; + } + + }; + } + } + + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/ORCompilationUnitCache.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/ORCompilationUnitCache.java new file mode 100644 index 000000000..57768bb8c --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/ORCompilationUnitCache.java @@ -0,0 +1,267 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.rewrite; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.net.URI; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.io.IOUtils; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.openrewrite.Parser.Input; +import org.openrewrite.java.JavaParser; +import org.openrewrite.java.tree.J.CompilationUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.ide.vscode.boot.java.utils.CompilationUnitCache; +import org.springframework.ide.vscode.boot.java.utils.DocumentContentProvider; +import org.springframework.ide.vscode.commons.java.IClasspath; +import org.springframework.ide.vscode.commons.java.IClasspathUtil; +import org.springframework.ide.vscode.commons.java.IJavaProject; +import org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFinder; +import org.springframework.ide.vscode.commons.languageserver.java.ProjectObserver; +import org.springframework.ide.vscode.commons.languageserver.util.SimpleLanguageServer; +import org.springframework.ide.vscode.commons.languageserver.util.SimpleTextDocumentService; +import org.springframework.ide.vscode.commons.util.text.TextDocument; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.RemovalListener; +import com.google.common.cache.RemovalNotification; + +import reactor.core.Disposable; + +public class ORCompilationUnitCache implements DocumentContentProvider, Disposable { + + private static final Logger logger = LoggerFactory.getLogger(CompilationUnitCache.class); + + private static final long CU_ACCESS_EXPIRATION = 1; + private JavaProjectFinder projectFinder; + private ProjectObserver projectObserver; + + private final ProjectObserver.Listener projectListener; + private final SimpleTextDocumentService documentService; + + private final Cache uriToCu; + private final Cache> projectToDocs; + private final Cache javaParsers; + + public ORCompilationUnitCache(JavaProjectFinder projectFinder, SimpleLanguageServer server, ProjectObserver projectObserver) { + this.projectFinder = projectFinder; + this.projectObserver = projectObserver; + + // PT 154618835 - Avoid retaining the CU in the cache as it consumes memory if it hasn't been + // accessed after some time + this.uriToCu = CacheBuilder.newBuilder() + .expireAfterWrite(CU_ACCESS_EXPIRATION, TimeUnit.MINUTES) + .removalListener(new RemovalListener() { + + @Override + public void onRemoval(RemovalNotification notification) { + invalidateCuForJavaFile(notification.getKey().toString()); + } + }) + .build(); + this.projectToDocs = CacheBuilder.newBuilder().build(); + this.javaParsers = CacheBuilder.newBuilder().build(); + + this.documentService = server == null ? null : server.getTextDocumentService(); + + // IMPORTANT ===> these notifications arrive within the lsp message loop, so reactions to them have to be fast + // and not be blocked by waiting for anything + if (this.documentService != null) { + this.documentService.onDidChangeContent(doc -> invalidateCuForJavaFile(doc.getDocument().getId().getUri())); + this.documentService.onDidClose(doc -> invalidateCuForJavaFile(doc.getId().getUri())); + } + +// if (this.projectFinder != null) { +// for (IJavaProject project : this.projectFinder.all()) { +// logger.info("CU Cache: initial lookup env creation for project <{}>", project.getElementName()); +// loadJavaParser(project); +// } +// } + + this.projectListener = new ProjectObserver.Listener() { + + @Override + public void deleted(IJavaProject project) { + logger.info("CU Cache: deleted project {}", project.getElementName()); + invalidateProject(project); + } + + @Override + public void created(IJavaProject project) { + logger.info("CU Cache: created project {}", project.getElementName()); + invalidateProject(project); +// loadJavaParser(project); + } + + @Override + public void changed(IJavaProject project) { + logger.info("CU Cache: changed project {}", project.getElementName()); + invalidateProject(project); + // Load the new cache the value right away +// loadJavaParser(project); + } + }; + + if (this.projectObserver != null) { + this.projectObserver.addListener(this.projectListener); + } + + } + + public void dispose() { + if (this.projectObserver != null) { + this.projectObserver.removeListener(this.projectListener); + } + } + + private JavaParser createJavaParser(IJavaProject project) { + try { + List classpath = getClasspathEntries(project).stream().map(s -> new File(s).toPath()).collect(Collectors.toList()); + JavaParser jp = JavaParser.fromJavaVersion().build(); + jp.setClasspath(classpath); + return jp; + } catch (Exception e) { + logger.error("{}", e); + return null; + } + } + + + private JavaParser loadJavaParser(IJavaProject project) { + try { + return javaParsers.get(project, () -> createJavaParser(project)); + } catch (ExecutionException e) { + logger.error("{}", e); + return null; + } + } + + private static Set getClasspathEntries(IJavaProject project) throws Exception { + if (project == null) { + return Collections.emptySet(); + } else { + IClasspath classpath = project.getClasspath(); + Stream classpathEntries = IClasspathUtil.getAllBinaryRoots(classpath).stream(); + return classpathEntries + .filter(file -> file.exists()) + .map(file -> file.getAbsolutePath()).collect(Collectors.toSet()); + } + } + + private void invalidateCuForJavaFile(String uriStr) { + logger.info("CU Cache: invalidate AST for {}", uriStr); + + URI uri = URI.create(uriStr); + uriToCu.invalidate(uri); + Optional project = projectFinder.find(new TextDocumentIdentifier(uriStr)); + if (project.isPresent()) { + JavaParser parser = javaParsers.getIfPresent(project.get()); + if (parser != null) { + parser.reset(); + } + } + } + + private void invalidateProject(IJavaProject project) { + logger.info("CU Cache: invalidate project <{}>", project.getElementName()); + + Set docUris = projectToDocs.getIfPresent(project); + if (docUris != null) { + uriToCu.invalidateAll(docUris); + projectToDocs.invalidate(project); + } + javaParsers.invalidate(project); + } + + @Override + public String fetchContent(URI uri) throws Exception { + if (documentService != null) { + TextDocument document = documentService.getLatestSnapshot(uri.toString()); + if (document != null) { + return document.get(); + } + } + return IOUtils.toString(uri); + } + + /** + * Does not need to be via callback - kept the same in order to keep the same API to replace JDT with Rewrite in distant future + */ + public T withCompilationUnit(IJavaProject project, URI uri, Function requestor) { + logger.info("CU Cache: work item submitted for doc {}", uri.toString()); + + if (project != null) { + + CompilationUnit cu = null; + + try { + cu = uriToCu.get(uri, () -> { + JavaParser javaParser = loadJavaParser(project); + Input input = new Input(Paths.get(uri), () -> { + try { + return new ByteArrayInputStream(fetchContent(uri).getBytes()); + } catch (Exception e) { + throw new IllegalStateException("Unexpected error fetching document content"); + } + }); + + List cus = ORAstUtils.parseInputs(javaParser, List.of(input)); + + logger.info("CU Cache: created new AST for {}", uri.toString()); + + return cus.get(0); + }); + + if (cu != null) { + projectToDocs.get(project, () -> new HashSet<>()).add(uri); + } + + } catch (Exception e) { + logger.error("", e); + } + + if (cu != null) { + try { + logger.info("CU Cache: start work on AST for {}", uri.toString()); + return requestor.apply(cu); + } + catch (CancellationException e) { + throw e; + } + catch (Exception e) { + logger.error("", e); + } + finally { + logger.info("CU Cache: end work on AST for {}", uri.toString()); + } + } + } + + return requestor.apply(null); + } + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/ORDocUtils.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/ORDocUtils.java new file mode 100644 index 000000000..899f0d600 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/ORDocUtils.java @@ -0,0 +1,191 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.rewrite; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.lsp4j.CreateFile; +import org.eclipse.lsp4j.DeleteFile; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.TextDocumentEdit; +import org.eclipse.lsp4j.TextEdit; +import org.eclipse.lsp4j.VersionedTextDocumentIdentifier; +import org.eclipse.lsp4j.WorkspaceEdit; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.openrewrite.Result; +import org.openrewrite.shaded.jgit.diff.Edit; +import org.openrewrite.shaded.jgit.diff.EditList; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.ide.vscode.boot.java.utils.JGitUtils; +import org.springframework.ide.vscode.commons.languageserver.completion.DocumentEdits; +import org.springframework.ide.vscode.commons.languageserver.util.SimpleTextDocumentService; +import org.springframework.ide.vscode.commons.util.BadLocationException; +import org.springframework.ide.vscode.commons.util.text.IDocument; +import org.springframework.ide.vscode.commons.util.text.IRegion; +import org.springframework.ide.vscode.commons.util.text.LanguageId; +import org.springframework.ide.vscode.commons.util.text.TextDocument; + +public class ORDocUtils { + + private static final Logger log = LoggerFactory.getLogger(ORDocUtils.class); + + public static Optional computeEdits(IDocument doc, Result result) { + TextDocument newDoc = new TextDocument(null, LanguageId.PLAINTEXT, 0, result.getAfter().printAll()); + + EditList diff = JGitUtils.getDiff(result.getBefore().printAll(), newDoc.get()); + if (!diff.isEmpty()) { + DocumentEdits edits = new DocumentEdits(doc, false); + for (Edit e : diff) { + try { + switch(e.getType()) { + case DELETE: + edits.delete(doc.getLineOffset(e.getBeginA()), getStartOfLine(doc, e.getEndA())); + break; + case INSERT: + edits.insert(doc.getLineOffset(e.getBeginA()), newDoc.textBetween(newDoc.getLineOffset(e.getBeginB()), getStartOfLine(newDoc, e.getEndB()))); + break; + case REPLACE: + edits.replace(doc.getLineOfOffset(e.getBeginA()), getStartOfLine(doc, e.getEndA()), newDoc.textBetween(newDoc.getLineOffset(e.getBeginB()), getStartOfLine(newDoc, e.getEndB()))); + break; + case EMPTY: + break; + } + } catch (BadLocationException ex) { + log.error("Diff conversion failed", ex); + } + } + return Optional.of(edits); + } + return Optional.empty(); + + } + + public static Optional computeTextDocEdit(TextDocument doc, Result result) { + TextDocument newDoc = new TextDocument(null, LanguageId.PLAINTEXT, 0, result.getAfter().printAll()); + + EditList diff = JGitUtils.getDiff(result.getBefore().printAll(), newDoc.get()); + if (!diff.isEmpty()) { + TextDocumentEdit edit = new TextDocumentEdit(); + edit.setTextDocument(new VersionedTextDocumentIdentifier(doc.getUri(), doc.getVersion())); + List textEdits = new ArrayList<>(); + edit.setEdits(textEdits); + for (Edit e : diff) { + try { + switch(e.getType()) { + case DELETE: + TextEdit textEdit = new TextEdit(); + int start = doc.getLineOffset(e.getBeginA()); + int end = getStartOfLine(doc, e.getEndA()); + textEdit.setRange(new Range(doc.toPosition(start), doc.toPosition(end))); + textEdit.setNewText(""); + textEdits.add(textEdit); + break; + case INSERT: + textEdit = new TextEdit(); + Position position = doc.toPosition(doc.getLineOffset(e.getBeginA())); + textEdit.setRange(new Range(position, position)); + textEdit.setNewText(newDoc.textBetween(newDoc.getLineOffset(e.getBeginB()), getStartOfLine(newDoc, e.getEndB()))); + textEdits.add(textEdit); + break; + case REPLACE: + textEdit = new TextEdit(); + start = doc.getLineOffset(e.getBeginA()); + end = getStartOfLine(doc, e.getEndA()); + textEdit.setRange(new Range(doc.toPosition(start), doc.toPosition(end))); + textEdit.setNewText(newDoc.textBetween(newDoc.getLineOffset(e.getBeginB()), getStartOfLine(newDoc, e.getEndB()))); + textEdits.add(textEdit); + break; + case EMPTY: + break; + } + } catch (BadLocationException ex) { + log.error("Diff conversion failed", ex); + } + } + return Optional.of(edit); + } + return Optional.empty(); + } + + public static Optional computeSimpleTextDocEdit(TextDocument doc, Result result) { + TextDocument newDoc = new TextDocument(null, LanguageId.PLAINTEXT, 0, result.getAfter().printAll()); + + EditList diff = JGitUtils.getDiff(result.getBefore().printAll(), newDoc.get()); + if (!diff.isEmpty()) { + TextDocumentEdit edit = new TextDocumentEdit(); + edit.setTextDocument(new VersionedTextDocumentIdentifier(doc.getUri(), doc.getVersion())); + TextEdit te = new TextEdit(); + te.setNewText(result.getAfter().printAll()); + try { + te.setRange(new Range(new Position(0,0), doc.toPosition(doc.getLength()))); + } catch (BadLocationException e) { + // ignore + } + edit.setEdits(List.of(te)); + return Optional.of(edit); + } + return Optional.empty(); + } + + private static int getStartOfLine(IDocument doc, int lineNumber) { + IRegion lineInformation = doc.getLineInformation(lineNumber); + if (lineInformation != null) { + return lineInformation.getOffset(); + } + if (lineNumber > 0) { + IRegion currentLine = doc.getLineInformation(lineNumber - 1); + return currentLine.getOffset() + currentLine.getLength(); + } + return 0; + } + + public static Optional createWorkspaceEdit(Path absoluteProjectDir, SimpleTextDocumentService documents, List results) { + if (results.isEmpty()) { + return Optional.empty(); + } + WorkspaceEdit we = new WorkspaceEdit(); + we.setDocumentChanges(new ArrayList<>()); + for (Result result : results) { + if (result.getBefore() == null) { + String docUri = absoluteProjectDir.resolve(result.getAfter().getSourcePath()).toUri().toString(); + CreateFile ro = new CreateFile(); + ro.setUri(docUri); + we.getDocumentChanges().add(Either.forRight(ro)); + + TextDocumentEdit te = new TextDocumentEdit(); + te.setTextDocument(new VersionedTextDocumentIdentifier(docUri, 0)); + Position cursor = new Position(0,0); + te.setEdits(List.of(new TextEdit(new Range(cursor, cursor), result.getAfter().printAll()))); + we.getDocumentChanges().add(Either.forLeft(te)); + } else if (result.getAfter() == null) { + String docUri = absoluteProjectDir.resolve(result.getBefore().getSourcePath()).toUri().toString(); + we.getDocumentChanges().add(Either.forRight(new DeleteFile(docUri))); + } else { + String docUri = absoluteProjectDir.resolve(result.getBefore().getSourcePath()).toUri().toString(); + TextDocument doc = documents.getLatestSnapshot(docUri); + if (doc == null) { + doc = new TextDocument(docUri, null, 0, result.getBefore().printAll()); + ORDocUtils.computeTextDocEdit(doc, result).ifPresent(te -> we.getDocumentChanges().add(Either.forLeft(te))); + } else { + ORDocUtils.computeTextDocEdit(doc, result).ifPresent(te -> we.getDocumentChanges().add(Either.forLeft(te))); + } + } + + } + return Optional.of(we); + } + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/RewriteRecipeRepository.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/RewriteRecipeRepository.java new file mode 100644 index 000000000..c41dea59b --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/RewriteRecipeRepository.java @@ -0,0 +1,252 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.rewrite; + +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.eclipse.lsp4j.ApplyWorkspaceEditParams; +import org.eclipse.lsp4j.Registration; +import org.eclipse.lsp4j.RegistrationParams; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.eclipse.lsp4j.Unregistration; +import org.eclipse.lsp4j.UnregistrationParams; +import org.eclipse.lsp4j.WorkspaceEdit; +import org.openrewrite.ExecutionContext; +import org.openrewrite.InMemoryExecutionContext; +import org.openrewrite.Recipe; +import org.openrewrite.Result; +import org.openrewrite.SourceFile; +import org.openrewrite.Validated; +import org.openrewrite.config.Environment; +import org.openrewrite.java.JavaParser; +import org.openrewrite.maven.MavenParser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.ide.vscode.commons.java.IClasspath; +import org.springframework.ide.vscode.commons.java.IClasspathUtil; +import org.springframework.ide.vscode.commons.java.IJavaProject; +import org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFinder; +import org.springframework.ide.vscode.commons.languageserver.util.SimpleLanguageServer; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableList.Builder; +import com.google.common.collect.ImmutableMap; +import com.google.gson.JsonElement; + +public class RewriteRecipeRepository { + + private static final Logger log = LoggerFactory.getLogger(RewriteRecipeRepository.class); + private static final String WORKSPACE_EXECUTE_COMMAND = "workspace/executeCommand"; + + private static final String RECIPES_LOADING_PROGRESS = "loading-rewrite-recipes"; + + final private SimpleLanguageServer server; + + final private Map recipes; + final private List globalCommandRecipes; + + final private JavaProjectFinder projectFinder; + + final public CompletableFuture loaded; + + private static final Set TOP_LEVEL_RECIPES = Set.of( + "org.openrewrite.java.spring.boot2.SpringBoot2JUnit4to5Migration", + "org.openrewrite.java.spring.boot2.SpringBoot2BestPractices", + "org.openrewrite.java.spring.boot2.SpringBoot1To2Migration", + "org.openrewrite.java.testing.junit5.JUnit5BestPractices", + "org.openrewrite.java.testing.junit5.JUnit4to5Migration", + "org.openrewrite.java.spring.boot2.UpgradeSpringBoot_2_6" + ); + + public RewriteRecipeRepository(SimpleLanguageServer server, JavaProjectFinder projectFinder) { + this.server = server; + this.projectFinder = projectFinder; + this.recipes = new HashMap<>(); + this.globalCommandRecipes = new ArrayList<>(); + this.loaded = CompletableFuture.runAsync(this::loadRecipes); + } + + private void loadRecipes() { + try { + log.info("Loading Rewrite Recipes..."); + for (Recipe r : Environment.builder().scanRuntimeClasspath().build().listRecipes()) { + if (r.getName() != null) { + if (recipes.containsKey(r.getName())) { + log.error("Duplicate ids: '" + r.getName() + "'"); + } + recipes.put(r.getName(), r); + + if (TOP_LEVEL_RECIPES.contains(r.getName())) { + Validated validation = Validated.invalid(null, null, null); + try { + validation = r.validate(); + } catch (Exception e) { + // ignore + } + if (validation.isValid()) { + globalCommandRecipes.add(r); + } + } + } + } + log.info("Done loading Rewrite Recipes"); + server.doOnInitialized(() -> registerCommands()); + } catch (Throwable t) { + log.error("", t); + } + } + + public Optional getRecipe(String name) { + return Optional.ofNullable(recipes.get(name)); + } + + private void registerCommands() { + log.info("Registering commands for rewrite recipes..."); + + Builder listBuilder = ImmutableList.builder(); + + server.onCommand("sts/rewrite/list", params -> { + JsonElement uri = (JsonElement) params.getArguments().get(0); + return CompletableFuture.completedFuture(uri == null ? Collections.emptyList() : listProjectRefactoringCommands(uri.getAsString())); + }); + listBuilder.add("sts/rewrite/list"); + + for (Recipe r : globalCommandRecipes) { + listBuilder.add(createGlobalCommand(r)); + } + + String registrationId = UUID.randomUUID().toString(); + RegistrationParams params = new RegistrationParams(ImmutableList.of( + new Registration(registrationId, + WORKSPACE_EXECUTE_COMMAND, + ImmutableMap.of("commands", listBuilder.build()) + ) + )); + + server.getClient().registerCapability(params).thenAccept((v) -> { + server.onShutdown(() -> server.getClient().unregisterCapability(new UnregistrationParams(List.of(new Unregistration(registrationId, WORKSPACE_EXECUTE_COMMAND))))); + log.info("Done registering commands for rewrite recipes"); + server.getProgressService().progressEvent(RECIPES_LOADING_PROGRESS, null); + }); + + } + + private String createGlobalCommand(Recipe r) { + String commandId = "sts/rewrite/recipe/" + r.getName(); + server.onCommand(commandId, params -> { + String progressToken = params.getWorkDoneToken() == null || params.getWorkDoneToken().getLeft() == null ? r.getName() : params.getWorkDoneToken().getLeft(); + return CompletableFuture.supplyAsync(() -> { + JsonElement uri = (JsonElement) params.getArguments().get(0); + server.getProgressService().progressEvent(progressToken, r.getDisplayName() + ": initiated..."); + return projectFinder.find(new TextDocumentIdentifier(uri.getAsString())); + }).thenCompose(p -> { + if (p.isPresent()) { + return CompletableFuture.completedFuture(apply(r, p.get())).thenCompose(we -> { + if (we.isPresent()) { + server.getProgressService().progressEvent(progressToken, + r.getDisplayName() + ": applying document changes..."); + return server.getClient().applyEdit(new ApplyWorkspaceEditParams(we.get(), r.getDisplayName())).thenCompose(res -> { + if (res.isApplied()) { + server.getProgressService().progressEvent(progressToken, null); + return CompletableFuture.completedFuture("success"); + } else { + server.getProgressService().progressEvent(progressToken, null); + return CompletableFuture.completedFuture(null); + } + }); + } + return CompletableFuture.completedFuture(null); + }); + } + return CompletableFuture.completedFuture(null); + }); + + }); + return commandId; + } + + private Optional apply(Recipe r, IJavaProject project) { + Path absoluteProjectDir = Paths.get(project.getLocationUri()); + server.getProgressService().progressEvent(r.getName(), r.getDisplayName() + ": parsing files..."); + MavenProjectParser projectParser = createRewriteMavenParser(absoluteProjectDir, + new InMemoryExecutionContext()); + List sources = projectParser.parse(absoluteProjectDir, getClasspathEntries(project)); + server.getProgressService().progressEvent(r.getName(), + r.getDisplayName() + ": computing changes..."); + List results = r.run(sources, new InMemoryExecutionContext(e -> log.error("", e))); + return ORDocUtils.createWorkspaceEdit(absoluteProjectDir, server.getTextDocumentService(), results); + } + + private List listProjectRefactoringCommands(String uri) { + if (uri != null) { + Optional projectOpt = projectFinder.find(new TextDocumentIdentifier(uri)); + if (projectOpt.isPresent()) { + List commandDescriptors = new ArrayList<>(globalCommandRecipes.size()); + for (Recipe r : globalCommandRecipes) { + commandDescriptors.add(new RecipeDescriptor(r.getName(), r.getDisplayName(), r.getDescription())); + } + return commandDescriptors; + } + } + return Collections.emptyList(); + } + + private static MavenProjectParser createRewriteMavenParser(Path absoluteProjectDir, ExecutionContext context) { + MavenParser.Builder mavenParserBuilder = MavenParser.builder() + .mavenConfig(absoluteProjectDir.resolve(".mvn/maven.config")); + + MavenProjectParser mavenProjectParser = new MavenProjectParser( + mavenParserBuilder, + JavaParser.fromJavaVersion(), + context + ); + return mavenProjectParser; + } + + private static List getClasspathEntries(IJavaProject project) { + if (project == null) { + return List.of(); + } else { + IClasspath classpath = project.getClasspath(); + Stream classpathEntries = IClasspathUtil.getAllBinaryRoots(classpath).stream(); + return classpathEntries + .filter(file -> file.exists()) + .filter(file -> file.getName().endsWith(".jar")) + .map(file -> file.getAbsoluteFile().toPath()).collect(Collectors.toList()); + } + } + + @SuppressWarnings("unused") + private static class RecipeDescriptor { + String id; + String label; + String description; + public RecipeDescriptor(String id, String label, String description) { + this.id = id; + this.label = label; + this.description = description; + } + } + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/RewriteRefactorings.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/RewriteRefactorings.java new file mode 100644 index 000000000..8640c70cb --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/RewriteRefactorings.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.rewrite; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; + +import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.WorkspaceEdit; +import org.springframework.ide.vscode.commons.languageserver.util.CodeActionResolver; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; + +public class RewriteRefactorings implements CodeActionResolver { + + private Map, WorkspaceEdit>> refactoringsMap = new ConcurrentHashMap<>(); + + public void addRefactoring(String id, Function, WorkspaceEdit> handler) { + if (refactoringsMap.containsKey(id)) { + throw new IllegalStateException("Refactoring with id '" + id + "' already exists!"); + } + refactoringsMap.put(id, handler); + } + + @Override + public void resolve(CodeAction codeAction) { + if (codeAction.getData() instanceof JsonObject) { + JsonObject o = (JsonObject) codeAction.getData(); + try { + Data data = new Gson().fromJson(o, Data.class); + if (data != null && data.id != null) { + Function, WorkspaceEdit> handler = refactoringsMap.get(data.id); + if (handler != null) { + WorkspaceEdit edit = handler.apply(data.arguments); + if (edit != null) { + codeAction.setEdit(edit); + } + } + } + } catch (Exception e) { + // ignore + } + } + } + + public static class Data { + public String id; + public List arguments; + public Data(String id, List arguments) { + this.id = id; + this.arguments = arguments; + } + } + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/codeaction/AbstractRewriteJavaCodeAction.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/codeaction/AbstractRewriteJavaCodeAction.java new file mode 100644 index 000000000..758509a76 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/codeaction/AbstractRewriteJavaCodeAction.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.rewrite.codeaction; + +import java.util.List; +import java.util.Optional; + +import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.CodeActionCapabilities; +import org.eclipse.lsp4j.CodeActionKind; +import org.eclipse.lsp4j.CodeActionResolveSupportCapabilities; +import org.eclipse.lsp4j.TextDocumentEdit; +import org.eclipse.lsp4j.WorkspaceEdit; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.openrewrite.Recipe; +import org.openrewrite.Result; +import org.springframework.ide.vscode.boot.java.handlers.JavaCodeAction; +import org.springframework.ide.vscode.boot.java.rewrite.ORCompilationUnitCache; +import org.springframework.ide.vscode.boot.java.rewrite.ORDocUtils; +import org.springframework.ide.vscode.boot.java.rewrite.RewriteRefactorings; +import org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFinder; +import org.springframework.ide.vscode.commons.languageserver.util.SimpleLanguageServer; +import org.springframework.ide.vscode.commons.util.text.TextDocument; + +public abstract class AbstractRewriteJavaCodeAction implements JavaCodeAction { + + protected ORCompilationUnitCache orCuCache; + protected String codeActionId; + protected SimpleLanguageServer server; + protected JavaProjectFinder projectFinder; + + public AbstractRewriteJavaCodeAction(SimpleLanguageServer server, JavaProjectFinder projectFinder, + RewriteRefactorings rewriteRefactorings, ORCompilationUnitCache orCuCache, String codeActionId) { + this.server = server; + this.projectFinder = projectFinder; + this.orCuCache = orCuCache; + this.codeActionId = codeActionId; + rewriteRefactorings.addRefactoring(codeActionId, this::perform); + } + + protected CodeAction createCodeAction(String title, List arguments) { + CodeAction ca = new CodeAction(); + ca.setKind(CodeActionKind.Refactor); + ca.setTitle(title); + ca.setData(new RewriteRefactorings.Data(codeActionId, arguments)); + return ca; + } + + protected WorkspaceEdit applyRecipe(Recipe r, TextDocument doc, org.openrewrite.java.tree.J.CompilationUnit cu) { + List results = r.run(List.of(cu)); + if (!results.isEmpty() && results.get(0).getAfter() != null) { + Optional edit = ORDocUtils.computeTextDocEdit(doc, results.get(0)); + return edit.map(e -> { + WorkspaceEdit workspaceEdit = new WorkspaceEdit(); + workspaceEdit.setDocumentChanges(List.of(Either.forLeft(e))); + return workspaceEdit; + }).orElse(null); + } + return null; + } + + protected static boolean isResolve(CodeActionCapabilities capabilities, String property) { + if (capabilities != null) { + CodeActionResolveSupportCapabilities resolveSupport = capabilities.getResolveSupport(); + if (resolveSupport != null) { + List properties = resolveSupport.getProperties(); + return properties != null && properties.contains(property); + } + } + return false; + } + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/codeaction/ConvertAutowiredField.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/codeaction/ConvertAutowiredField.java new file mode 100644 index 000000000..cb7f0b0e1 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/codeaction/ConvertAutowiredField.java @@ -0,0 +1,110 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.rewrite.codeaction; + +import java.net.URI; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.Annotation; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.FieldDeclaration; +import org.eclipse.jdt.core.dom.IAnnotationBinding; +import org.eclipse.jdt.core.dom.TypeDeclaration; +import org.eclipse.jdt.core.dom.VariableDeclarationFragment; +import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.CodeActionCapabilities; +import org.eclipse.lsp4j.Command; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.eclipse.lsp4j.WorkspaceEdit; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.springframework.ide.vscode.boot.java.Annotations; +import org.springframework.ide.vscode.boot.java.rewrite.ConvertAutowiredParameterIntoConstructorParameter; +import org.springframework.ide.vscode.boot.java.rewrite.ORCompilationUnitCache; +import org.springframework.ide.vscode.boot.java.rewrite.RewriteRefactorings; +import org.springframework.ide.vscode.commons.java.IJavaProject; +import org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFinder; +import org.springframework.ide.vscode.commons.languageserver.util.SimpleLanguageServer; +import org.springframework.ide.vscode.commons.languageserver.util.SimpleTextDocumentService; +import org.springframework.ide.vscode.commons.util.text.IRegion; +import org.springframework.ide.vscode.commons.util.text.TextDocument; + +public class ConvertAutowiredField extends AbstractRewriteJavaCodeAction { + + private static final String CODE_ACTION_ID = "ConvertAutowiredParameterIntoConstructorParameter"; + + public ConvertAutowiredField(SimpleLanguageServer server, JavaProjectFinder projectFinder, + RewriteRefactorings rewriteRefactorings, ORCompilationUnitCache orCuCache) { + super(server, projectFinder, rewriteRefactorings, orCuCache, CODE_ACTION_ID); + } + + @Override + public WorkspaceEdit perform(List args) { + SimpleTextDocumentService documents = server.getTextDocumentService(); + String docUri = (String) args.get(0); + String classFqName = (String) args.get(1); + String fieldName = (String) args.get(2); + TextDocument doc = documents.getLatestSnapshot(docUri); + + Optional project = projectFinder.find(new TextDocumentIdentifier(docUri)); + + if (project.isPresent()) { + return orCuCache.withCompilationUnit(project.get(), URI.create(docUri), cu -> { + if (cu == null) { + throw new IllegalStateException("Cannot parse Java file: " + docUri); + } + return applyRecipe(new ConvertAutowiredParameterIntoConstructorParameter(classFqName, fieldName), doc, cu); + }); + } + return null; + } + + @Override + public List> getCodeActions(CodeActionCapabilities capabilities, TextDocument doc, IRegion region, IJavaProject project, + CompilationUnit cu, ASTNode node) { + // Only supports resolvable code action for now + if (!isResolve(capabilities, "edit")) { + return Collections.emptyList(); + } + + for (; node != null && !(node instanceof FieldDeclaration); node = node.getParent()) { + // nothing + } + if (node instanceof FieldDeclaration) { + FieldDeclaration fd = (FieldDeclaration) node; + + if (fd.fragments().size() == 1) { + @SuppressWarnings("unchecked") + Optional autowired = fd.modifiers().stream().filter(Annotation.class::isInstance) + .map(Annotation.class::cast).filter(a -> { + IAnnotationBinding binding = ((Annotation) a).resolveAnnotationBinding(); + if (binding != null && binding.getAnnotationType() != null) { + return Annotations.AUTOWIRED.equals(binding.getAnnotationType().getQualifiedName()); + } + return false; + }).findFirst(); + + if (autowired.isPresent()) { + + return List.of(Either.forRight(createCodeAction("Convert into Constructor Parameter", + List.of(doc.getId().getUri(), + ((TypeDeclaration) fd.getParent()).resolveBinding().getQualifiedName(), + ((VariableDeclarationFragment) fd.fragments().get(0)).getName().getIdentifier())))); + } + } + + } + return Collections.emptyList(); + } + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/codeaction/NoRequestMapping.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/codeaction/NoRequestMapping.java new file mode 100644 index 000000000..285f77a7e --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/codeaction/NoRequestMapping.java @@ -0,0 +1,111 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.rewrite.codeaction; + +import java.net.URI; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.IMethodBinding; +import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.CodeActionCapabilities; +import org.eclipse.lsp4j.Command; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.eclipse.lsp4j.WorkspaceEdit; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.openrewrite.java.MethodMatcher; +import org.openrewrite.java.spring.NoRequestMappingAnnotation; +import org.springframework.ide.vscode.boot.java.rewrite.ORAstUtils; +import org.springframework.ide.vscode.boot.java.rewrite.ORCompilationUnitCache; +import org.springframework.ide.vscode.boot.java.rewrite.RewriteRefactorings; +import org.springframework.ide.vscode.commons.java.IJavaProject; +import org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFinder; +import org.springframework.ide.vscode.commons.languageserver.util.SimpleLanguageServer; +import org.springframework.ide.vscode.commons.languageserver.util.SimpleTextDocumentService; +import org.springframework.ide.vscode.commons.util.text.IRegion; +import org.springframework.ide.vscode.commons.util.text.TextDocument; + +public class NoRequestMapping extends NoRequestMappings { + + private static final String CODE_ACTION_ID = "RemoveRequestMappings"; + + public NoRequestMapping(SimpleLanguageServer server, JavaProjectFinder projectFinder, + RewriteRefactorings rewriteRefactorings, ORCompilationUnitCache orCuCache) { + super(server, projectFinder, rewriteRefactorings, orCuCache, CODE_ACTION_ID); + } + + @Override + public WorkspaceEdit perform(List args) { + SimpleTextDocumentService documents = server.getTextDocumentService(); + String docUri = (String) args.get(0); + String matchStr = (String) args.get(1); + TextDocument doc = documents.getLatestSnapshot(docUri); + + Optional project = projectFinder.find(new TextDocumentIdentifier(docUri)); + + if (project.isPresent()) { + return orCuCache.withCompilationUnit(project.get(), URI.create(docUri), cu -> { + if (cu == null) { + throw new IllegalStateException("Cannot parse Java file: " + docUri); + } + MethodMatcher macther = new MethodMatcher(matchStr); + + return applyRecipe(ORAstUtils.nodeRecipe(new NoRequestMappingAnnotation(), t -> { + if (t instanceof org.openrewrite.java.tree.J.MethodDeclaration) { + org.openrewrite.java.tree.J.MethodDeclaration m = (org.openrewrite.java.tree.J.MethodDeclaration) t; + return macther.matches(m.getMethodType()); + } + return false; + }), doc, cu); + }); + } + return null; + } + + @Override + public List> getCodeActions(CodeActionCapabilities capabilities, TextDocument doc, IRegion region, IJavaProject project, + CompilationUnit cu, ASTNode node) { + // Only supports resolvable code action for now + if (!isResolve(capabilities, "edit")) { + return Collections.emptyList(); + } + return findAppropriateMethodDeclaration(node).map(method -> { + String methodMatcher = "* " + method.getName().getIdentifier() + "(*)"; + IMethodBinding methodBinding = method.resolveBinding(); + if (methodBinding != null) { + StringBuilder sb = new StringBuilder(methodBinding.getDeclaringClass().getQualifiedName()); + sb.append(' '); + sb.append(methodBinding.getName()); + sb.append('('); + sb.append(Arrays.stream(methodBinding.getParameterTypes()).map(b -> { + if (b.isParameterizedType() ) { + return b.getErasure().getQualifiedName(); + } + return b.getQualifiedName(); + }).collect(Collectors.joining(","))); + sb.append(')'); + methodMatcher = sb.toString(); + } + return createCodeAction("Replace single @RequestMapping with @GetMapping etc.", List.of( + doc.getId().getUri(), + methodMatcher + )); + }).map(ca -> List.of(Either.forRight(ca))).orElse(Collections.emptyList()); + } + + + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/codeaction/NoRequestMappings.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/codeaction/NoRequestMappings.java new file mode 100644 index 000000000..ab550db6b --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/codeaction/NoRequestMappings.java @@ -0,0 +1,104 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.rewrite.codeaction; + +import java.net.URI; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.Annotation; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.ITypeBinding; +import org.eclipse.jdt.core.dom.MethodDeclaration; +import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.CodeActionCapabilities; +import org.eclipse.lsp4j.Command; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.eclipse.lsp4j.WorkspaceEdit; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.openrewrite.java.spring.NoRequestMappingAnnotation; +import org.springframework.ide.vscode.boot.java.Annotations; +import org.springframework.ide.vscode.boot.java.rewrite.ORCompilationUnitCache; +import org.springframework.ide.vscode.boot.java.rewrite.RewriteRefactorings; +import org.springframework.ide.vscode.commons.java.IJavaProject; +import org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFinder; +import org.springframework.ide.vscode.commons.languageserver.util.SimpleLanguageServer; +import org.springframework.ide.vscode.commons.languageserver.util.SimpleTextDocumentService; +import org.springframework.ide.vscode.commons.util.text.IRegion; +import org.springframework.ide.vscode.commons.util.text.TextDocument; + +public class NoRequestMappings extends AbstractRewriteJavaCodeAction { + + private static final String CODE_ACTION_ID = "RemoveAllRequestMappings"; + + public NoRequestMappings(SimpleLanguageServer server, JavaProjectFinder projectFinder, + RewriteRefactorings rewriteRefactorings, ORCompilationUnitCache orCuCache) { + this(server, projectFinder, rewriteRefactorings, orCuCache, CODE_ACTION_ID); + } + + public NoRequestMappings(SimpleLanguageServer server, JavaProjectFinder projectFinder, + RewriteRefactorings rewriteRefactorings, ORCompilationUnitCache orCuCache, String codeActionId) { + super(server, projectFinder, rewriteRefactorings, orCuCache, codeActionId); + } + + final protected Optional findAppropriateMethodDeclaration(ASTNode node) { + for (; node != null && !(node instanceof Annotation); node = node.getParent()) { + // nothing + } + if (node instanceof Annotation) { + Annotation a = (Annotation) node; + ITypeBinding type = a.resolveTypeBinding(); + if (type != null && Annotations.SPRING_REQUEST_MAPPING.equals(type.getQualifiedName())) { + if (a.getParent() instanceof MethodDeclaration) { + return Optional.of((MethodDeclaration) a.getParent()); + } + } + + } + return Optional.empty(); + } + + @Override + public WorkspaceEdit perform(List args) { + SimpleTextDocumentService documents = server.getTextDocumentService(); + String docUri = (String) args.get(0); + TextDocument doc = documents.getLatestSnapshot(docUri); + + Optional project = projectFinder.find(new TextDocumentIdentifier(docUri)); + + if (project.isPresent()) { + return orCuCache.withCompilationUnit(project.get(), URI.create(docUri), cu -> { + if (cu == null) { + throw new IllegalStateException("Cannot parse Java file: " + docUri); + } + return applyRecipe(new NoRequestMappingAnnotation(), doc, cu); + }); + } + return null; + } + + @Override + public List> getCodeActions(CodeActionCapabilities capabilities, TextDocument doc, IRegion region, IJavaProject project, + CompilationUnit cu, ASTNode node) { + // Only supports resolvable code action for now + if (!isResolve(capabilities, "edit")) { + return Collections.emptyList(); + } + return findAppropriateMethodDeclaration(node).map(m -> createCodeAction("Replace all @RequestMapping with @GetMapping etc.", List.of( + doc.getId().getUri() + ))).map(ca -> List.of(Either.forRight(ca))).orElse(Collections.emptyList()); + } + + + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/quickfix/AutowiredConstructorQuickFixHandler.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/quickfix/AutowiredConstructorQuickFixHandler.java new file mode 100644 index 000000000..7baed1892 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/quickfix/AutowiredConstructorQuickFixHandler.java @@ -0,0 +1,86 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.rewrite.quickfix; + +import java.net.URI; +import java.util.List; +import java.util.Optional; + +import org.eclipse.lsp4j.TextDocumentEdit; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.eclipse.lsp4j.WorkspaceEdit; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.openrewrite.Result; +import org.openrewrite.java.spring.NoAutowiredOnConstructor; +import org.springframework.ide.vscode.boot.java.rewrite.ORAstUtils; +import org.springframework.ide.vscode.boot.java.rewrite.ORCompilationUnitCache; +import org.springframework.ide.vscode.boot.java.rewrite.ORDocUtils; +import org.springframework.ide.vscode.commons.java.IJavaProject; +import org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFinder; +import org.springframework.ide.vscode.commons.languageserver.util.SimpleLanguageServer; +import org.springframework.ide.vscode.commons.languageserver.util.SimpleTextDocumentService; +import org.springframework.ide.vscode.commons.util.text.TextDocument; + +public class AutowiredConstructorQuickFixHandler extends RewriteQuickFixHandler { + + final private SimpleLanguageServer server; + final private JavaProjectFinder projectFinder; + final private ORCompilationUnitCache orCuCache; + + public AutowiredConstructorQuickFixHandler(SimpleLanguageServer server, JavaProjectFinder projectFinder, ORCompilationUnitCache orCuCache) { + super(); + this.server = server; + this.projectFinder = projectFinder; + this.orCuCache = orCuCache; + } + + protected WorkspaceEdit perform(List args) { + SimpleTextDocumentService documents = server.getTextDocumentService(); + String docUri = (String) args.get(0); + String classFqName = (String) args.get(1); + TextDocument doc = documents.getLatestSnapshot(docUri); + + Optional project = projectFinder.find(new TextDocumentIdentifier(docUri)); + + if (project.isPresent()) { + return removeUnnecessaryAutowiredFromConstructor(project.get(), doc, classFqName); + } + + return null; + } + + private WorkspaceEdit removeUnnecessaryAutowiredFromConstructor(IJavaProject project, TextDocument doc, String classFqName) { + String docUri = doc.getId().getUri(); + return orCuCache.withCompilationUnit(project, URI.create(docUri), cu -> { + if (cu == null) { + throw new IllegalStateException("Cannot parse Java file: " + docUri); + } + List results = ORAstUtils.nodeRecipe(new NoAutowiredOnConstructor(), t -> { + if (t instanceof org.openrewrite.java.tree.J.ClassDeclaration) { + org.openrewrite.java.tree.J.ClassDeclaration c = (org.openrewrite.java.tree.J.ClassDeclaration) t; + return c.getType() != null && classFqName.equals(c.getType().getFullyQualifiedName()); + } + return false; + }).run(List.of(cu)); + if (!results.isEmpty() && results.get(0).getAfter() != null) { + Optional edit = ORDocUtils.computeTextDocEdit(doc, results.get(0)); + return edit.map(e -> { + WorkspaceEdit workspaceEdit = new WorkspaceEdit(); + workspaceEdit.setDocumentChanges(List.of(Either.forLeft(e))); + return workspaceEdit; + }).orElse(null); + } + + return null; + }); + } + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/quickfix/RewriteQuickFixHandler.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/quickfix/RewriteQuickFixHandler.java new file mode 100644 index 000000000..4ac968dd2 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/rewrite/quickfix/RewriteQuickFixHandler.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * Copyright (c) 2022 VMware, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VMware, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.rewrite.quickfix; + +import java.util.List; + +import org.eclipse.lsp4j.WorkspaceEdit; +import org.springframework.ide.vscode.commons.languageserver.quickfix.QuickfixEdit; +import org.springframework.ide.vscode.commons.languageserver.quickfix.QuickfixHandler; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; + +public abstract class RewriteQuickFixHandler implements QuickfixHandler { + + final static private Gson gson = new Gson(); + + @Override + public QuickfixEdit createEdits(Object p) { + if (p instanceof JsonElement) { + List l = gson.fromJson((JsonElement) p, List.class); + return new QuickfixEdit(perform(l), null); + } + return null; + } + + abstract protected WorkspaceEdit perform(List l); + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/utils/JGitUtils.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/utils/JGitUtils.java new file mode 100644 index 000000000..189d918ae --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/utils/JGitUtils.java @@ -0,0 +1,20 @@ +package org.springframework.ide.vscode.boot.java.utils; + +import java.nio.charset.StandardCharsets; + +import org.openrewrite.shaded.jgit.diff.EditList; +import org.openrewrite.shaded.jgit.diff.HistogramDiff; +import org.openrewrite.shaded.jgit.diff.RawText; +import org.openrewrite.shaded.jgit.diff.RawTextComparator; + +public class JGitUtils { + + public static EditList getDiff(String txt1, String txt2) { + RawText rt1 = new RawText(txt1.getBytes(StandardCharsets.UTF_8)); + RawText rt2 = new RawText(txt2.getBytes(StandardCharsets.UTF_8)); + EditList diffList = new EditList(); + diffList.addAll(new HistogramDiff().diff(RawTextComparator.DEFAULT, rt1, rt2)); + return diffList; + } + +} diff --git a/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/requestmapping/test/RequestMappingSnippetTests.java b/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/requestmapping/test/RequestMappingSnippetTests.java new file mode 100644 index 000000000..d92b1191e --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/requestmapping/test/RequestMappingSnippetTests.java @@ -0,0 +1,130 @@ +/******************************************************************************* + * Copyright (c) 2022 Pivotal, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Pivotal, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.requestmapping.test; + +import static org.junit.Assert.assertEquals; + +import java.io.InputStream; +import java.util.List; + +import org.apache.commons.io.IOUtils; +import org.eclipse.lsp4j.CompletionItem; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Import; +import org.springframework.ide.vscode.boot.bootiful.BootLanguageServerTest; +import org.springframework.ide.vscode.boot.bootiful.HoverTestConf; +import org.springframework.ide.vscode.commons.java.IJavaProject; +import org.springframework.ide.vscode.commons.util.text.LanguageId; +import org.springframework.ide.vscode.languageserver.testharness.Editor; +import org.springframework.ide.vscode.project.harness.BootLanguageServerHarness; +import org.springframework.ide.vscode.project.harness.ProjectsHarness; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@BootLanguageServerTest +@Import(HoverTestConf.class) +public class RequestMappingSnippetTests { + + @Autowired private BootLanguageServerHarness harness; + private Editor editor; + + @Before + public void setup() throws Exception { + IJavaProject testProject = ProjectsHarness.INSTANCE.mavenProject("test-request-mapping-live-hover"); + harness.useProject(testProject); + harness.intialize(null); + } + + @Test + public void getMapping() throws Exception { + prepareCase("Get<*>"); + assertOneSnippet("package example;\n" + + "\n" + + "import org.springframework.stereotype.Controller;\n" + + "import org.springframework.web.bind.annotation.DeleteMapping;\n" + + "import org.springframework.web.bind.annotation.GetMapping;\n" + + "import org.springframework.web.bind.annotation.PathVariable;\n" + + "import org.springframework.web.bind.annotation.PostMapping;\n" + + "import org.springframework.web.bind.annotation.PutMapping;\n" + + "import org.springframework.web.bind.annotation.RequestBody;\n" + + "import org.springframework.web.bind.annotation.RequestMapping;\n" + + "import org.springframework.web.bind.annotation.ResponseBody;\n" + + "\n" + + "/** Boot Java - Test Completion */\n" + + "@Controller\n" + + "public class RestApi {\n" + + "\n" + + "@GetMapping(value=\"${1:path}\")\n" + + "public ${2:SomeData} ${3:getMethodName}(@RequestParam ${4:String} ${5:param}) {\n" + + " return new ${2:SomeData}($0);\n" + + "}\n" + + "<*>\n" + + "\n" + + "\n" + + " @RequestMapping(\"/hello\")\n" + + " @ResponseBody\n" + + " public String hello() {\n" + + " return \"Hello there!\";\n" + + " }\n" + + " \n" + + " \n" + + " @RequestMapping(\"/goodbye\")\n" + + " @ResponseBody\n" + + " public String goodbye() {\n" + + " return \"Good bye\";\n" + + " }\n" + + "\n" + + " @GetMapping(\"/person/{name}\")\n" + + " public String getMapping(@PathVariable String name) {\n" + + " return \"Hello \" + name;\n" + + " }\n" + + "\n" + + " @DeleteMapping(\"/delete/{id}\")\n" + + " public String removeMe(@PathVariable int id) {\n" + + " System.out.println(\"You are removed: \" + id);\n" + + " return \"Done\";\n" + + " }\n" + + "\n" + + " @PostMapping(\"/postHello\")\n" + + " public String postMethod(@RequestBody String name) {\n" + + " System.out.println(\"Posted hello: \" + name);\n" + + " return name;\n" + + " }\n" + + "\n" + + " @PutMapping(\"/put/{id}\")\n" + + " public String putMethod(@PathVariable int id, @RequestBody String name) {\n" + + " System.out.println(\"Added \" + name + \" with ID: \" + id);\n" + + " return name;\n" + + " }\n" + + "}\n" + + ""); + } + + private void prepareCase(String prefix) throws Exception { + InputStream resource = this.getClass().getResourceAsStream("/test-projects/test-request-mapping-live-hover/src/main/java/example/RestApi.java"); + String content = IOUtils.toString(resource); + + content = content.replace("class RestApi {", "class RestApi {\n\n" + prefix); + editor = new Editor(harness, content, LanguageId.JAVA); + } + + private void assertOneSnippet(String expected) throws Exception { + List completions = editor.getCompletions(); + assertEquals(completions.size(), 1); + Editor clonedEditor = editor.clone(); + clonedEditor.apply(completions.get(0)); + assertEquals(expected, clonedEditor.getText()); + } + +} diff --git a/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/value/test/ValueSpelExpressionValidationTest.java b/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/value/test/ValueSpelExpressionValidationTest.java index 649a62e25..fa3eef6e7 100644 --- a/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/value/test/ValueSpelExpressionValidationTest.java +++ b/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/value/test/ValueSpelExpressionValidationTest.java @@ -143,7 +143,7 @@ public class ValueSpelExpressionValidationTest { docUri = directory.toPath().resolve("src/main/java/org/test/TestValueCompletion.java").toUri().toString(); problemCollector = new TestProblemCollector(); - reconcileEngine = new BootJavaReconcileEngine(compilationUnitCache, projectFinder); + reconcileEngine = new BootJavaReconcileEngine(server, compilationUnitCache, projectFinder); } @After diff --git a/vscode-extensions/commons-vscode/src/launch-util.ts b/vscode-extensions/commons-vscode/src/launch-util.ts index 24524b68a..555286749 100644 --- a/vscode-extensions/commons-vscode/src/launch-util.ts +++ b/vscode-extensions/commons-vscode/src/launch-util.ts @@ -40,6 +40,7 @@ export interface ActivatorOptions { preferJdk?: boolean; highlightCodeLensSettingKey?: string; explodedLsJarData?: ExplodedLsJarData; + vmArgs?: string[]; } export interface ExplodedLsJarData { @@ -230,6 +231,10 @@ function prepareJvmArgs(options: ActivatorOptions, context: VSCode.ExtensionCont const jvmHeap = getUserDefinedJvmHeap(options.workspaceOptions, options.jvmHeap); const jvmArgs = getUserDefinedJvmArgs(options.workspaceOptions); + if (Array.isArray(options.vmArgs)) { + jvmArgs.push(...options.vmArgs); + } + let logfile : string = options.workspaceOptions.get("logfile") || "/dev/null"; //The logfile = '/dev/null' is handled specifically by the language server process so it works on all OSs. options.clientOptions.outputChannel.appendLine('Redirecting server logs to ' + logfile); diff --git a/vscode-extensions/vscode-spring-boot/lib/Main.ts b/vscode-extensions/vscode-spring-boot/lib/Main.ts index a056086a9..20520a450 100644 --- a/vscode-extensions/vscode-spring-boot/lib/Main.ts +++ b/vscode-extensions/vscode-spring-boot/lib/Main.ts @@ -6,8 +6,8 @@ import { workspace } from 'vscode'; import * as commons from '@pivotal-tools/commons-vscode'; import * as liveHoverUi from './live-hover-connect-ui'; +import * as rewrite from './rewrite'; -import {LanguageClient} from "vscode-languageclient/node"; import { startDebugSupport } from './debug-config-provider'; import { ApiManager } from "./apiManager"; import { ExtensionAPI } from "./api"; @@ -103,7 +103,22 @@ export function activate(context: VSCode.ExtensionContext): Thenable { liveHoverUi.activate(client, options, context); + rewrite.activate(client, options, context); return new ApiManager(client).api; }); } diff --git a/vscode-extensions/vscode-spring-boot/lib/rewrite.ts b/vscode-extensions/vscode-spring-boot/lib/rewrite.ts new file mode 100644 index 000000000..5241a05a9 --- /dev/null +++ b/vscode-extensions/vscode-spring-boot/lib/rewrite.ts @@ -0,0 +1,88 @@ +import { ActivatorOptions } from "@pivotal-tools/commons-vscode"; +import { LanguageClient } from "vscode-languageclient/node"; +import * as VSCode from 'vscode'; +import * as path from "path"; + +interface RewriteCommandInfo { + id: string; + label: string; + description: string +} + +interface RewriteCommandQuickPickItem extends VSCode.QuickPickItem { + id: string; +} + +function getWorkspaceFolderName(file: VSCode.Uri): string { + if (file) { + const wf: VSCode.WorkspaceFolder = VSCode.workspace.getWorkspaceFolder(file); + if (wf) { + return wf.name; + } + } + return ""; +} + +function getRelativePathToWorkspaceFolder(file: VSCode.Uri): string { + if (file) { + const wf: VSCode.WorkspaceFolder = VSCode.workspace.getWorkspaceFolder(file); + if (wf) { + return path.relative(wf.uri.fsPath, file.fsPath); + } + } + return ""; +} + +async function getTargetPomXml(): Promise { + if (VSCode.window.activeTextEditor) { + const activeUri = VSCode.window.activeTextEditor.document.uri; + if ("pom.xml" === path.basename(activeUri.path).toLowerCase()) { + return activeUri; + } + } + + const candidates: VSCode.Uri[] = await VSCode.workspace.findFiles("**/pom.xml"); + if (candidates.length > 0) { + if (candidates.length === 1) { + return candidates[0]; + } else { + return await VSCode.window.showQuickPick( + candidates.map((c: VSCode.Uri) => ({ value: c, label: getRelativePathToWorkspaceFolder(c), description: getWorkspaceFolderName(c) })), + { placeHolder: "Select the target project." }, + ).then(res => res && res.value); + } + } + return undefined; +} + + +async function liveHoverConnectHandler(uri: VSCode.Uri) { + if (!uri) { + uri = await getTargetPomXml(); + } + const cmds: RewriteCommandInfo[] = await VSCode.commands.executeCommand('sts/rewrite/list', uri.toString(true)); + const choices: RewriteCommandQuickPickItem[] = cmds.map(d => { + return { + id: d.id, + label: d.label, + description: d.description, + }; + }); + if (choices) { + const picked = await VSCode.window.showQuickPick(choices); + if (picked) { + VSCode.commands.executeCommand(`sts/rewrite/recipe/${picked.id}`, uri.toString(true)) + } + } +} + +/** Called when extension is activated */ +export function activate( + client: LanguageClient, + options: ActivatorOptions, + context: VSCode.ExtensionContext +) { + context.subscriptions.push( + VSCode.commands.registerCommand('vscode-spring-boot.rewrite.list', liveHoverConnectHandler) + ); +} \ No newline at end of file diff --git a/vscode-extensions/vscode-spring-boot/package.json b/vscode-extensions/vscode-spring-boot/package.json index ab8d37986..7d78b37f3 100644 --- a/vscode-extensions/vscode-spring-boot/package.json +++ b/vscode-extensions/vscode-spring-boot/package.json @@ -30,7 +30,8 @@ "onLanguage:spring-boot-properties-yaml", "onLanguage:java", "onLanguage:xml", - "onDebugResolve:java" + "onDebugResolve:java", + "onCommand:vscode-spring-boot.rewrite.list" ], "contributes": { "javaExtensions": [ @@ -65,16 +66,44 @@ "configuration": "./properties-support/language-configuration.json" } ], + "menus": { + "editor/context": [ + { + "when": "resourceFilename == pom.xml", + "command": "vscode-spring-boot.rewrite.list", + "group": "SpringBoot" + } + ], + "explorer/context": [ + { + "when": "resourceFilename == pom.xml && config.boot-java.rewrite.globa-commands.on == true", + "command": "vscode-spring-boot.rewrite.list", + "group": "SpringBoot" + } + ] + }, "commands": [ { "command": "vscode-spring-boot.live-hover.connect", - "title": "Manage Live Spring Boot Process Connections" + "title": "Manage Live Spring Boot Process Connections", + "category": "Spring Boot" + }, + { + "enablement": "config.boot-java.rewrite.globa-commands.on == true", + "command": "vscode-spring-boot.rewrite.list", + "category": "Spring Boot", + "title": "Rewrite Refactorings..." } ], "configuration": { "type": "object", "title": "Boot-Java Configuration", "properties": { + "boot-java.rewrite.globa-commands.on": { + "type": "boolean", + "default": false, + "description": "Experimental support for Rewrite recipes refactoring the whole maven projects via commands" + }, "boot-java.live-information.automatic-connection.on": { "type": "boolean", "default": true,