Rewrite integration for Spring Boot server and vscode client

This commit is contained in:
BoykoAlex
2022-02-03 12:35:58 -05:00
parent ff01f60a36
commit 580350564a
47 changed files with 3285 additions and 118 deletions

Binary file not shown.

View File

@@ -1 +1,18 @@
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip
# 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

View File

@@ -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<LanguageId, LanguageServerComponents> componentsByLanguageId = new HashMap<>();
@@ -55,6 +59,7 @@ public class CompositeLanguageServerComponents implements LanguageServerComponen
private final Map<LanguageId, LanguageServerComponents> 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<Either<Command, CodeAction>> 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<CodeActionHandler> getCodeActionProvider() {
return Optional.of(codeActionHandler);
}
}

View File

@@ -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<LanguageId> getInterestingLanguages();
default Optional<IReconcileEngine> getReconcileEngine() { return Optional.empty(); }
HoverHandler getHoverProvider();
default Optional<CodeActionHandler> getCodeActionProvider() { return Optional.empty(); }
}

View File

@@ -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<T> {
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<T> {
}
return true;
}
private List<Diagnostic> appliesToDiagnostics(CodeActionContext context) {
return context.getDiagnostics().stream()
.filter(diag -> this.diagMsg == null || this.diagMsg.equals(diag.getMessage()))
.collect(Collectors.toList());
}
}

View File

@@ -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<QuickfixEdit> handle(QuickfixResolveParams params) {
QuickfixHandler handler = registry.get(params.getType());

View File

@@ -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<Either<Command, CodeAction>> handle(CancelChecker cancelToken, CodeActionCapabilities capabilities, TextDocument doc, IRegion region);
}

View File

@@ -0,0 +1,9 @@
package org.springframework.ide.vscode.commons.languageserver.util;
import org.eclipse.lsp4j.CodeAction;
public interface CodeActionResolver {
void resolve(CodeAction codeAction);
}

View File

@@ -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);
}

View File

@@ -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<ApplyWorkspaceEditResponse> applyEdit = Mono.fromFuture(client.applyEdit(new ApplyWorkspaceEditParams(edit.workspaceEdit)));
Mono<ApplyWorkspaceEditResponse> 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() {

View File

@@ -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<Either<Command, CodeAction>> computeCodeActions(CancelChecker cancelToken, CodeActionCapabilities capabilities, TrackedDocument doc, CodeActionParams params) {
List<Either<Command,CodeAction>> list = doc.getQuickfixes().stream()
.filter((fix) -> fix.appliesTo(params.getRange(), params.getContext()))
.map(f -> f.getCodeAction(params.getContext()))
.map(command -> Either.<Command, CodeAction>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<List<Either<Command, CodeAction>>> codeAction(CodeActionParams params) {
@@ -423,17 +462,16 @@ public class SimpleTextDocumentService implements TextDocumentService, DocumentE
TrackedDocument doc = documents.get(params.getTextDocument().getUri());
if (doc != null) {
ImmutableList<Either<Command,CodeAction>> list = doc.getQuickfixes().stream()
.filter((fix) -> fix.appliesTo(params.getRange(), params.getContext()))
.map(Quickfix::getCodeAction)
.map(command -> Either.<Command, CodeAction>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<List<? extends CodeLens>> codeLens(CodeLensParams params) {
CodeLensHandler handler = this.codeLensHandler;
@@ -461,6 +499,22 @@ public class SimpleTextDocumentService implements TextDocumentService, DocumentE
}
}
@Override
public CompletableFuture<CodeAction> resolveCodeAction(CodeAction ca) {
return CompletableFutures.computeAsync(messageWorkerThreadPool, cancelToken -> {
if (appContext!=null) {
Map<String, CodeActionResolver> 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;

View File

@@ -28,7 +28,7 @@
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4-runtime</artifactId>
<version>4.5.3</version>
<version>4.9.3</version>
</dependency>
</dependencies>

View File

@@ -106,6 +106,11 @@
<reactor-netty>0.7.5.RELEASE</reactor-netty>
<commons-io-version>2.4</commons-io-version>
<commons-codec-version>1.13</commons-codec-version>
<!-- Rewrite specific properties -->
<rewrite-version>7.21.3</rewrite-version>
<rewrite-spring-version>4.19.3</rewrite-spring-version>
<rewrite-jackson.version>2.13.2</rewrite-jackson.version>
<signing.skip>true</signing.skip>
<signing.alias>vmware</signing.alias>

166
headless-services/mvnw vendored
View File

@@ -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 "$@"

View File

@@ -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%

View File

@@ -38,6 +38,17 @@
<enabled>true</enabled>
</releases>
</repository>
<repository>
<id>rewrite-snapshots</id>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<dependencies>
@@ -93,6 +104,64 @@
<artifactId>org.eclipse.jdt.core</artifactId>
<version>${jdt.core.version}</version>
</dependency>
<dependency>
<groupId>org.openrewrite</groupId>
<artifactId>rewrite-properties</artifactId>
<version>${rewrite-version}</version>
</dependency>
<dependency>
<groupId>org.openrewrite</groupId>
<artifactId>rewrite-maven</artifactId>
<version>${rewrite-version}</version>
</dependency>
<dependency>
<groupId>org.openrewrite</groupId>
<artifactId>rewrite-yaml</artifactId>
<version>${rewrite-version}</version>
</dependency>
<dependency>
<groupId>org.openrewrite</groupId>
<artifactId>rewrite-java</artifactId>
<version>${rewrite-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${rewrite-jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${rewrite-jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${rewrite-jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
<version>${rewrite-jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>${rewrite-jackson.version}</version>
</dependency>
<dependency>
<groupId>org.openrewrite.recipe</groupId>
<artifactId>rewrite-spring</artifactId>
<version>${rewrite-spring-version}</version>
</dependency>
<dependency>
<groupId>org.openrewrite</groupId>
<artifactId>rewrite-java-11</artifactId>
<version>${rewrite-version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>

View File

@@ -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> 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);
}
}

View File

@@ -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");

View File

@@ -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));
}
}

View File

@@ -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<CodeActionHandler> getCodeActionProvider() {
return Optional.ofNullable(codeActionProvider);
}
}

View File

@@ -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;

View File

@@ -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;
}

View File

@@ -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);
}

View File

@@ -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<ITypeBinding> 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;
}
}

View File

@@ -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<JavaCodeAction> javaCodeActions;
public BootJavaCodeActionProvider(JavaProjectFinder projectFinder, CompilationUnitCache cuCache, Collection<JavaCodeAction> javaCodeActions) {
this.projectFinder = projectFinder;
this.cuCache = cuCache;
this.javaCodeActions = javaCodeActions;
}
@Override
public List<Either<Command, CodeAction>> handle(CancelChecker cancelToken, CodeActionCapabilities capabilities, TextDocument doc, IRegion region) {
Optional<IJavaProject> 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<Either<Command, CodeAction>> codeActions = new ArrayList<>();
for (JavaCodeAction jca : javaCodeActions) {
List<Either<Command, CodeAction>> cas = jca.getCodeActions(capabilities, doc, region, project.get(), cu, found);
if (cas != null) {
codeActions.addAll(cas);
}
}
return codeActions;
});
}
return Collections.emptyList();
}
}

View File

@@ -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);
}
}
}

View File

@@ -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<Either<Command, CodeAction>> getCodeActions(CodeActionCapabilities capabilities, TextDocument doc, IRegion region, IJavaProject project, CompilationUnit cu, ASTNode node);
}

View File

@@ -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<?, ExecutionContext> getVisitor() {
return new JavaVisitor<ExecutionContext>() {
@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<ExecutionContext> {
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<MethodDeclaration> constructors = ORAstUtils.getMethods(c).stream().filter(m -> m.isConstructor()).collect(Collectors.toList());
if (constructors.isEmpty()) {
doAfterVisit(new AddConstructorVisitor(c.getSimpleName(), fieldName, type));
} else {
Optional<MethodDeclaration> 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<ExecutionContext> {
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<Statement> 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<ExecutionContext> {
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;
}
}
}

View File

@@ -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.
* <PRE>
* 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.
*
* </PRE>
* @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<SourceFile> parse(Path projectDirectory, List<Path> dependencies) {
List<Xml.Document> 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<SourceFile> sourceFiles = new ArrayList<>();
for (Xml.Document maven : mavens) {
List<Marker> projectProvenance = getJavaProvenance(maven, projectDirectory);
sourceFiles.add(addProjectProvenance(maven, projectProvenance));
// List<Path> 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<Path> 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<Marker> 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<Path> resources, Path projectDirectory, List<SourceFile> sourceFiles, List<Marker> projectProvenance, JavaSourceSet sourceSet) {
List<Marker> 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 extends SourceFile> S addProjectProvenance(S s, List<Marker> projectProvenance) {
for (Marker marker : projectProvenance) {
s = s.withMarkers(s.getMarkers().addIfAbsent(marker));
}
return s;
}
private <S extends SourceFile> UnaryOperator<S> addProvenance(List<Marker> projectProvenance) {
return s -> {
s = addProjectProvenance(s, projectProvenance);
return s;
};
}
// private List<Path> downloadArtifacts(Set<Dependency> dependencies) {
// return dependencies.stream()
// .filter(d -> d.getRepository() != null)
// .map(artifactDownloader::downloadArtifact)
// .filter(Objects::nonNull)
// .collect(Collectors.toList());
// }
public static List<Xml.Document> sort(List<Xml.Document> mavens) {
// the value is the set of maven projects that depend on the key
Map<Xml.Document, Set<Xml.Document>> 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<Xml.Document> sorted = new ArrayList<>(mavens.size());
next:
while (!byDependedOn.isEmpty()) {
for (Map.Entry<Xml.Document, Set<Xml.Document>> mavenAndDependencies : byDependedOn.entrySet()) {
if (mavenAndDependencies.getValue().isEmpty()) {
Xml.Document maven = mavenAndDependencies.getKey();
byDependedOn.remove(maven);
sorted.add(maven);
for (Set<Xml.Document> dependencies : byDependedOn.values()) {
dependencies.remove(maven);
}
continue next;
}
}
}
return sorted;
}
private static List<Path> getSources(Path srcDir, ExecutionContext ctx, String... fileTypes) {
if (!srcDir.toFile().exists()) {
return List.of();
}
BiPredicate<Path, java.nio.file.attribute.BasicFileAttributes> 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<Path> 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<Path> 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<Path> 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<Path> 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<Path> 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");
}
}

View File

@@ -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> T getFirstAnsector(Class<T> 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 extends Tree> T withId(UUID id) {
// this.uuid = id;
// return (T) this;
// }
// }
//
// private static class AncestersMarker implements Marker {
//
// private UUID uuid;
// private List<J> ancesters = List.of();
//
// public AncestersMarker(List<J> ancesters) {
// this.uuid = Tree.randomId();
// this.ancesters = ancesters;
// }
//
// @Override
// public UUID getId() {
// return uuid;
// }
//
// @SuppressWarnings("unchecked")
// public <T> T getFirstAnsector(Class<T> 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<?, ExecutionContext> 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<J> 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<J> siblings = p.pollMessage(parentId, new ArrayList<J>());
// siblings.add(newJ);
// p.putMessage(parentId, siblings);
// }
// return newJ;
// }
// return (J) tree;
// }
// };
// }
//
// }
//
// public static J findAstNodeAt(CompilationUnit cu, int offset) {
// AtomicReference<J> f = new AtomicReference<>();
// new JavaIsoVisitor<AtomicReference<J>>() {
// public J visit(Tree tree, AtomicReference<J> 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> T findNode(J node, Class<T> 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<CompilationUnit> parse(JavaParser parser, Iterable<Path> sourceFiles) {
InMemoryExecutionContext ctx = new InMemoryExecutionContext(e -> log.error("", e));
ctx.putMessage(JavaParser.SKIP_SOURCE_SET_TYPE_GENERATION, true);
List<CompilationUnit> cus = parser.parse(sourceFiles, null, ctx);
return cus;
// List<Result> 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<CompilationUnit> parseInputs(JavaParser parser, Iterable<Parser.Input> inputs) {
InMemoryExecutionContext ctx = new InMemoryExecutionContext(e -> log.error("", e));
ctx.putMessage(JavaParser.SKIP_SOURCE_SET_TYPE_GENERATION, true);
List<CompilationUnit> cus = parser.parseInputs(inputs, null, ctx);
return cus;
// List<Result> 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<J.VariableDeclarations> 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<J.MethodDeclaration> 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<?, ExecutionContext> getVisitor(Recipe r) {
try {
Method m = Recipe.class.getDeclaredMethod("getVisitor");
m.setAccessible(true);
return (TreeVisitor<?, ExecutionContext>) m.invoke(r);
} catch (Exception e) {
return null;
}
}
@SuppressWarnings("unchecked")
private static List<TreeVisitor<J, ExecutionContext>> getAfterVisitors(TreeVisitor<J, ExecutionContext> visitor) {
try {
Method m = TreeVisitor.class.getDeclaredMethod("getAfterVisit");
m.setAccessible(true);
return (List<TreeVisitor<J, ExecutionContext>>) m.invoke(visitor);
} catch (Exception e) {
return Collections.emptyList();
}
}
private static void makeVisitorNonTopLevel(JavaVisitor<ExecutionContext> 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<J> condition) {
return new NodeRecipe((JavaVisitor<ExecutionContext>) getVisitor(r), condition);
}
private static class NodeRecipe extends Recipe {
private JavaVisitor<ExecutionContext> visitor;
private Predicate<J> condition;
public NodeRecipe(JavaVisitor<ExecutionContext> visitor, Predicate<J> condition) {
this.visitor = visitor;
this.condition = condition;
}
@Override
public String getDisplayName() {
return "";
}
@Override
protected TreeVisitor<?, ExecutionContext> 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<J, ExecutionContext> v : getAfterVisitors(visitor)) {
doAfterVisit(v);
}
}
return t;
}
};
}
}
}

View File

@@ -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<URI, CompilationUnit> uriToCu;
private final Cache<IJavaProject, Set<URI>> projectToDocs;
private final Cache<IJavaProject, JavaParser> 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<URI, CompilationUnit>() {
@Override
public void onRemoval(RemovalNotification<URI, CompilationUnit> 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<Path> 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<String> getClasspathEntries(IJavaProject project) throws Exception {
if (project == null) {
return Collections.emptySet();
} else {
IClasspath classpath = project.getClasspath();
Stream<File> 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<IJavaProject> 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<URI> 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> T withCompilationUnit(IJavaProject project, URI uri, Function<CompilationUnit, T> 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<CompilationUnit> 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);
}
}

View File

@@ -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<DocumentEdits> 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<TextDocumentEdit> 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<TextEdit> 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<TextDocumentEdit> 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<WorkspaceEdit> createWorkspaceEdit(Path absoluteProjectDir, SimpleTextDocumentService documents, List<Result> 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);
}
}

View File

@@ -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<String, Recipe> recipes;
final private List<Recipe> globalCommandRecipes;
final private JavaProjectFinder projectFinder;
final public CompletableFuture<Void> loaded;
private static final Set<String> 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<Recipe> getRecipe(String name) {
return Optional.ofNullable(recipes.get(name));
}
private void registerCommands() {
log.info("Registering commands for rewrite recipes...");
Builder<Object> 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<WorkspaceEdit> 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<SourceFile> sources = projectParser.parse(absoluteProjectDir, getClasspathEntries(project));
server.getProgressService().progressEvent(r.getName(),
r.getDisplayName() + ": computing changes...");
List<Result> results = r.run(sources, new InMemoryExecutionContext(e -> log.error("", e)));
return ORDocUtils.createWorkspaceEdit(absoluteProjectDir, server.getTextDocumentService(), results);
}
private List<RecipeDescriptor> listProjectRefactoringCommands(String uri) {
if (uri != null) {
Optional<IJavaProject> projectOpt = projectFinder.find(new TextDocumentIdentifier(uri));
if (projectOpt.isPresent()) {
List<RecipeDescriptor> 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<Path> getClasspathEntries(IJavaProject project) {
if (project == null) {
return List.of();
} else {
IClasspath classpath = project.getClasspath();
Stream<File> 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;
}
}
}

View File

@@ -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<String, Function<List<?>, WorkspaceEdit>> refactoringsMap = new ConcurrentHashMap<>();
public void addRefactoring(String id, Function<List<?>, 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<List<?>, 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;
}
}
}

View File

@@ -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<Result> results = r.run(List.of(cu));
if (!results.isEmpty() && results.get(0).getAfter() != null) {
Optional<TextDocumentEdit> 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<String> properties = resolveSupport.getProperties();
return properties != null && properties.contains(property);
}
}
return false;
}
}

View File

@@ -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<IJavaProject> 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<Either<Command, CodeAction>> 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<Annotation> 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();
}
}

View File

@@ -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<IJavaProject> 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<Either<Command, CodeAction>> 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.<Command, CodeAction>forRight(ca))).orElse(Collections.emptyList());
}
}

View File

@@ -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<MethodDeclaration> 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<IJavaProject> 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<Either<Command, CodeAction>> 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.<Command, CodeAction>forRight(ca))).orElse(Collections.emptyList());
}
}

View File

@@ -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<IJavaProject> 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<Result> 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<TextDocumentEdit> 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;
});
}
}

View File

@@ -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);
}

View File

@@ -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;
}
}

View File

@@ -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<CompletionItem> completions = editor.getCompletions();
assertEquals(completions.size(), 1);
Editor clonedEditor = editor.clone();
clonedEditor.apply(completions.get(0));
assertEquals(expected, clonedEditor.getText());
}
}

View File

@@ -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

View File

@@ -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);

View File

@@ -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<ExtensionAP
enableJdtClasspath: VSCode.extensions.getExtension('redhat.java')?.exports?.serverMode === 'Standard'
})
},
highlightCodeLensSettingKey: 'boot-java.highlight-codelens.on'
highlightCodeLensSettingKey: 'boot-java.highlight-codelens.on',
vmArgs: [
'--add-modules=ALL-SYSTEM',
'--add-exports',
'jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED',
'--add-exports',
'jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED',
'--add-exports',
'jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED',
'--add-exports',
'jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED',
'--add-exports',
'jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED',
'--add-exports',
'jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED'
]
};
// Register launch config contributior to java debug launch to be able to connect to JMX
@@ -111,6 +126,7 @@ export function activate(context: VSCode.ExtensionContext): Thenable<ExtensionAP
return commons.activate(options, context).then(client => {
liveHoverUi.activate(client, options, context);
rewrite.activate(client, options, context);
return new ApiManager(client).api;
});
}

View File

@@ -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<VSCode.Uri> {
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)
);
}

View File

@@ -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,