Explain spel expressions and queries with copilot

This commit is contained in:
vudayani
2024-08-14 18:33:54 +05:30
committed by Martin Lippert
parent 992a7c7428
commit 578ca3ec4e
15 changed files with 20412 additions and 9 deletions

View File

@@ -40,6 +40,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.QueryCodeLensProvider;
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;
@@ -173,7 +174,7 @@ public class BootJavaLanguageServerComponents implements LanguageServerComponent
Duration.ofSeconds(5),
sourceLinks);
codeLensHandler = createCodeLensEngine(springSymbolIndex);
codeLensHandler = createCodeLensEngine(springSymbolIndex, projectFinder, server);
highlightsEngine = createDocumentHighlightEngine(springSymbolIndex);
documents.onDocumentHighlight(highlightsEngine);
@@ -304,9 +305,10 @@ public class BootJavaLanguageServerComponents implements LanguageServerComponent
return new BootJavaReferencesHandler(this, cuCache, projectFinder, providers);
}
protected BootJavaCodeLensEngine createCodeLensEngine(SpringSymbolIndex index) {
protected BootJavaCodeLensEngine createCodeLensEngine(SpringSymbolIndex index, JavaProjectFinder projectFinder, SimpleLanguageServer server) {
Collection<CodeLensProvider> codeLensProvider = new ArrayList<>();
codeLensProvider.add(new WebfluxHandlerCodeLensProvider(index));
codeLensProvider.add(new QueryCodeLensProvider(projectFinder, server));
return new BootJavaCodeLensEngine(this, codeLensProvider);
}

View File

@@ -0,0 +1,182 @@
/*******************************************************************************
* Copyright (c) 2017, 2024 Broadcom, 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:
* Broadcom, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.vscode.boot.java.handlers;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
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.Expression;
import org.eclipse.jdt.core.dom.MemberValuePair;
import org.eclipse.jdt.core.dom.NormalAnnotation;
import org.eclipse.jdt.core.dom.SingleMemberAnnotation;
import org.eclipse.lsp4j.CodeLens;
import org.eclipse.lsp4j.Command;
import org.eclipse.lsp4j.jsonrpc.CancelChecker;
import org.springframework.ide.vscode.boot.java.spel.AnnotationParamSpelExtractor;
import org.springframework.ide.vscode.boot.java.spel.AnnotationParamSpelExtractor.Snippet;
import org.springframework.ide.vscode.commons.java.IJavaProject;
import org.springframework.ide.vscode.commons.java.SpringProjectUtil;
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.BadLocationException;
import org.springframework.ide.vscode.commons.util.text.TextDocument;
import com.google.common.collect.ImmutableList;
import com.google.gson.JsonPrimitive;
/**
* @author Udayani V
*/
public class QueryCodeLensProvider implements CodeLensProvider {
public static final String CMD_ENABLE_COPILOT_FEATURES = "sts/enable/copilot/features";
public static final String EXPLAIN_SPEL_TITLE = "Explain Spel Expression using Copilot";
public static final String EXPLAIN_QUERY_TITLE = "Explain Query using Copilot";
private static final String QUERY = "Query";
private static final String FQN_QUERY = "org.springframework.data.jpa.repository." + QUERY;
private static final String SPEL_EXPRESSION_QUERY_PROMPT = "Explain the following SpEL Expression in detail: \n";
private static final String JPQL_QUERY_PROMPT = "Explain the following JPQL query in detail. If the query contains any SpEL expressions, explain those parts as well: \n";
private static final String HQL_QUERY_PROMPT = "Explain the following HQL query in detail. If the query contains any SpEL expressions, explain those parts as well: \n";
private static final String DEFAULT_QUERY_PROMPT = "Explain the following query in detail: \n";
private static final String CMD = "vscode-spring-boot.query.explain";
private final AnnotationParamSpelExtractor[] spelExtractors = AnnotationParamSpelExtractor.SPEL_EXTRACTORS;
private final JavaProjectFinder projectFinder;
private static boolean showCodeLenses;
public QueryCodeLensProvider(JavaProjectFinder projectFinder, SimpleLanguageServer server) {
this.projectFinder = projectFinder;
server.onCommand(CMD_ENABLE_COPILOT_FEATURES, params -> {
if (params.getArguments().get(0) instanceof JsonPrimitive) {
QueryCodeLensProvider.showCodeLenses = ((JsonPrimitive)params.getArguments().get(0)).getAsBoolean();
}
return CompletableFuture.completedFuture(showCodeLenses);
});
}
@Override
public void provideCodeLenses(CancelChecker cancelToken, TextDocument document, CompilationUnit cu,
List<CodeLens> resultAccumulator) {
if(!showCodeLenses) {
return;
}
cu.accept(new ASTVisitor() {
@Override
public boolean visit(SingleMemberAnnotation node) {
Arrays.stream(spelExtractors).map(e -> e.getSpelRegion(node)).filter(o -> o.isPresent())
.map(o -> o.get()).forEach(snippet -> {
provideCodeLensForSpelExpression(cancelToken, node, document, snippet, resultAccumulator);
});
if (isQueryAnnotation(node)) {
String queryPrompt = determineQueryPrompt(document);
provideCodeLensForQuery(cancelToken, node, document, node.getValue(), queryPrompt, resultAccumulator);
}
return super.visit(node);
}
@Override
public boolean visit(NormalAnnotation node) {
Arrays.stream(spelExtractors).map(e -> e.getSpelRegion(node)).filter(o -> o.isPresent())
.map(o -> o.get()).forEach(snippet -> {
provideCodeLensForSpelExpression(cancelToken, node, document, snippet, resultAccumulator);
});
if (isQueryAnnotation(node)) {
String queryPrompt = determineQueryPrompt(document);
for (Object value : node.values()) {
if (value instanceof MemberValuePair) {
MemberValuePair pair = (MemberValuePair) value;
if ("value".equals(pair.getName().getIdentifier())) {
provideCodeLensForQuery(cancelToken, node, document, pair.getValue(), queryPrompt, resultAccumulator);
break;
}
}
}
}
return super.visit(node);
}
});
}
protected void provideCodeLensForSpelExpression(CancelChecker cancelToken, Annotation node, TextDocument document, Snippet snippet,
List<CodeLens> resultAccumulator) {
cancelToken.checkCanceled();
if (snippet != null) {
try {
CodeLens codeLens = new CodeLens();
codeLens.setRange(document.toRange(snippet.offset(), snippet.text().length()));
Command cmd = new Command();
cmd.setTitle(EXPLAIN_SPEL_TITLE);
cmd.setCommand(CMD);
cmd.setArguments(ImmutableList.of(SPEL_EXPRESSION_QUERY_PROMPT + snippet.text()));
codeLens.setCommand(cmd);
resultAccumulator.add(codeLens);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
protected void provideCodeLensForQuery(CancelChecker cancelToken, Annotation node, TextDocument document,
Expression valueExp, String query, List<CodeLens> resultAccumulator) {
cancelToken.checkCanceled();
if (valueExp != null) {
try {
CodeLens codeLens = new CodeLens();
codeLens.setRange(document.toRange(valueExp.getStartPosition(), valueExp.getLength()));
Command cmd = new Command();
cmd.setTitle(EXPLAIN_QUERY_TITLE);
cmd.setCommand(CMD);
cmd.setArguments(ImmutableList.of(query + valueExp.toString()));
codeLens.setCommand(cmd);
resultAccumulator.add(codeLens);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
private static boolean isQueryAnnotation(Annotation a) {
return FQN_QUERY.equals(a.getTypeName().getFullyQualifiedName())
|| QUERY.equals(a.getTypeName().getFullyQualifiedName());
}
private String determineQueryPrompt(TextDocument document) {
Optional<IJavaProject> optProject = projectFinder.find(document.getId());
if (optProject.isPresent()) {
IJavaProject jp = optProject.get();
return SpringProjectUtil.hasDependencyStartingWith(jp, "hibernate-core", null) ? HQL_QUERY_PROMPT : JPQL_QUERY_PROMPT;
}
return DEFAULT_QUERY_PROMPT;
}
}

View File

@@ -21,7 +21,7 @@ import org.eclipse.jdt.core.dom.StringLiteral;
import org.springframework.ide.vscode.boot.java.Annotations;
import org.springframework.ide.vscode.boot.java.annotations.AnnotationHierarchies;
final class AnnotationParamSpelExtractor {
public final class AnnotationParamSpelExtractor {
private static final String SPRING_CACHEABLE = "org.springframework.cache.annotation.Cacheable";
private static final String SPRING_CACHE_EVICT = "org.springframework.cache.annotation.CacheEvict";
@@ -35,7 +35,7 @@ final class AnnotationParamSpelExtractor {
private static final String SPRING_CONDITIONAL_ON_EXPRESSION = "org.springframework.boot.autoconfigure.condition.ConditionalOnExpression";
final static AnnotationParamSpelExtractor[] SPEL_EXTRACTORS = new AnnotationParamSpelExtractor[] {
public final static AnnotationParamSpelExtractor[] SPEL_EXTRACTORS = new AnnotationParamSpelExtractor[] {
new AnnotationParamSpelExtractor(Annotations.VALUE, null, "#{", "}"),
new AnnotationParamSpelExtractor(Annotations.VALUE, "value", "#{", "}"),
@@ -62,7 +62,7 @@ final class AnnotationParamSpelExtractor {
};
record Snippet(String text, int offset) {}
public record Snippet(String text, int offset) {}
private final String annotationType;
private final String paramName;
@@ -77,7 +77,7 @@ final class AnnotationParamSpelExtractor {
this.paramValuePostfix = paramValuePostfix;
}
Optional<Snippet> getSpelRegion(NormalAnnotation a) {
public Optional<Snippet> getSpelRegion(NormalAnnotation a) {
if (paramName == null) {
return Optional.empty();
}
@@ -104,7 +104,7 @@ final class AnnotationParamSpelExtractor {
return Optional.empty();
}
Optional<Snippet> getSpelRegion(SingleMemberAnnotation a) {
public Optional<Snippet> getSpelRegion(SingleMemberAnnotation a) {
if (this.paramName != null) {
return Optional.empty();
}

View File

@@ -0,0 +1,174 @@
/*******************************************************************************
* Copyright (c) 2017, 2024 Broadcom, 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:
* Broadcom, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.vscode.boot.java.handlers.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.io.File;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.eclipse.lsp4j.CodeLens;
import org.eclipse.lsp4j.Command;
import org.eclipse.lsp4j.ExecuteCommandParams;
import org.eclipse.lsp4j.Range;
import org.eclipse.lsp4j.TextDocumentIdentifier;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.ide.vscode.boot.app.SpringSymbolIndex;
import org.springframework.ide.vscode.boot.bootiful.BootLanguageServerTest;
import org.springframework.ide.vscode.boot.bootiful.SymbolProviderTestConf;
import org.springframework.ide.vscode.boot.java.handlers.QueryCodeLensProvider;
import org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFinder;
import org.springframework.ide.vscode.commons.languageserver.util.ExecuteCommandHandler;
import org.springframework.ide.vscode.commons.languageserver.util.SimpleLanguageServer;
import org.springframework.ide.vscode.commons.util.text.LanguageId;
import org.springframework.ide.vscode.languageserver.testharness.TextDocumentInfo;
import org.springframework.ide.vscode.project.harness.BootLanguageServerHarness;
import org.springframework.ide.vscode.project.harness.ProjectsHarness;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.google.gson.JsonPrimitive;
/**
* @author Udayani V
*/
@SuppressWarnings("deprecation")
@ExtendWith(SpringExtension.class)
@BootLanguageServerTest
@Import(SymbolProviderTestConf.class)
public class QueryCodeLensProviderTest {
@Autowired
private BootLanguageServerHarness harness;
@Autowired
private JavaProjectFinder projectFinder;
@Autowired
private SpringSymbolIndex indexer;
private SimpleLanguageServer server;
private ArgumentCaptor<ExecuteCommandHandler> commandHandlerCaptor;
private QueryCodeLensProvider queryCodeLensProvider;
private File directory;
@BeforeEach
public void setup() throws Exception {
harness.intialize(null);
directory = new File(ProjectsHarness.class.getResource("/test-projects/test-spel-query-codelense/").toURI());
String projectDir = directory.toURI().toString();
server = mock(SimpleLanguageServer.class);
commandHandlerCaptor = ArgumentCaptor.forClass(ExecuteCommandHandler.class);
queryCodeLensProvider = new QueryCodeLensProvider(projectFinder, server);
// trigger project creation
projectFinder.find(new TextDocumentIdentifier(projectDir)).get();
CompletableFuture<Void> initProject = indexer.waitOperation();
initProject.get(5, TimeUnit.SECONDS);
verify(server).onCommand(eq(QueryCodeLensProvider.CMD_ENABLE_COPILOT_FEATURES), commandHandlerCaptor.capture());
}
@Test
public void testShowCodeLensesTrueForQuery() throws Exception {
setCommandParamsHandler(true);
String docUri = directory.toPath().resolve("src/main/java/org/test/OwnerRepository.java").toUri().toString();
TextDocumentInfo doc = harness.getOrReadFile(new File(new URI(docUri)), LanguageId.JAVA.getId());
TextDocumentInfo openedDoc = harness.openDocument(doc);
List<? extends CodeLens> codeLenses = harness.getCodeLenses(openedDoc);
assertEquals(3, codeLenses.size());
assertTrue(containsCodeLens(codeLenses.get(0), QueryCodeLensProvider.EXPLAIN_QUERY_TITLE, 9, 8, 9, 108));
assertTrue(containsCodeLens(codeLenses.get(1), QueryCodeLensProvider.EXPLAIN_QUERY_TITLE, 13, 8, 13, 39));
assertTrue(containsCodeLens(codeLenses.get(2), QueryCodeLensProvider.EXPLAIN_QUERY_TITLE, 17, 14, 17, 92));
}
@Test
public void testShowCodeLensesTrueForSpel() throws Exception {
// Simulate the command execution with true parameter
setCommandParamsHandler(true);
String docUri = directory.toPath().resolve("src/main/java/org/test/SpelController.java").toUri().toString();
TextDocumentInfo doc = harness.getOrReadFile(new File(new URI(docUri)), LanguageId.JAVA.getId());
TextDocumentInfo openedDoc = harness.openDocument(doc);
List<? extends CodeLens> codeLenses = harness.getCodeLenses(openedDoc);
assertEquals(2, codeLenses.size());
assertTrue(containsCodeLens(codeLenses.get(0), QueryCodeLensProvider.EXPLAIN_SPEL_TITLE, 13, 17, 13, 111));
assertTrue(containsCodeLens(codeLenses.get(1), QueryCodeLensProvider.EXPLAIN_SPEL_TITLE, 16, 11, 16, 142));
}
@Test
public void testShowCodeLensesFalseForQuery() throws Exception {
setCommandParamsHandler(false);
String docUri = directory.toPath().resolve("src/main/java/org/test/OwnerRepository.java").toUri().toString();
TextDocumentInfo doc = harness.getOrReadFile(new File(new URI(docUri)), LanguageId.JAVA.getId());
TextDocumentInfo openedDoc = harness.openDocument(doc);
List<? extends CodeLens> codeLenses = harness.getCodeLenses(openedDoc);
assertEquals(0, codeLenses.size());
}
@Test
public void testShowCodeLensesFalseForSpel() throws Exception {
setCommandParamsHandler(false);
String docUri = directory.toPath().resolve("src/main/java/org/test/SpelController.java").toUri().toString();
TextDocumentInfo doc = harness.getOrReadFile(new File(new URI(docUri)), LanguageId.JAVA.getId());
TextDocumentInfo openedDoc = harness.openDocument(doc);
List<? extends CodeLens> codeLenses = harness.getCodeLenses(openedDoc);
assertEquals(0, codeLenses.size());
}
private void setCommandParamsHandler(boolean value) throws InterruptedException, ExecutionException {
ExecuteCommandHandler handler = commandHandlerCaptor.getValue();
ExecuteCommandParams params = new ExecuteCommandParams();
params.setArguments(Collections.singletonList(new JsonPrimitive(value)));
handler.handle(params).get();
}
private boolean containsCodeLens(CodeLens codeLenses, String commandTitle, int startLine, int startPosition,
int endLine, int endPosition) {
Command command = codeLenses.getCommand();
Range range = codeLenses.getRange();
if (command.getTitle().equals(commandTitle) && range.getStart().getLine() == startLine
&& range.getStart().getCharacter() == startPosition && range.getEnd().getLine() == endLine
&& range.getEnd().getCharacter() == endPosition) {
return true;
}
return false;
}
}

View File

@@ -0,0 +1,233 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# 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
#
# https://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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
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
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, 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
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
fi
# 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)
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
wdir=$(cd "$wdir/.."; pwd)
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} "$@"

View File

@@ -0,0 +1,145 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@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
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@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_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
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@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'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
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"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
set MAVEN_CMD_LINE_ARGS=%*
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar""
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
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"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

View File

@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>test-spring-data-symbols</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<source>8</source>
<detectJavaApiLink>false</detectJavaApiLink>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,20 @@
package org.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.test.model.Employee;
@SpringBootApplication
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}

View File

@@ -0,0 +1,138 @@
package org.test;
import java.util.ArrayList;
import java.util.List;
import org.springframework.core.style.ToStringCreator;
import org.springframework.samples.petclinic.model.Person;
import org.springframework.util.Assert;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.NotBlank;
@Entity
@Table(name = "owners")
@NamedQuery(
name = "Owner.findByLastName",
query = "SELECT o FROM Owner o WHERE o.lastName = :lastName"
)
public class Owner extends Person {
@Column(name = "address")
@NotBlank
private String address;
@Column(name = "city")
@NotBlank
private String city;
@Column(name = "telephone")
@NotBlank
@Pattern(regexp = "\\d{10}", message = "Telephone must be a 10-digit number")
private String telephone;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "owner_id")
@OrderBy("name")
private List<Pet> pets = new ArrayList<>();
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getTelephone() {
return this.telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public List<Pet> getPets() {
return this.pets;
}
public void addPet(Pet pet) {
if (pet.isNew()) {
getPets().add(pet);
}
}
/**
* Return the Pet with the given name, or null if none found for this Owner.
* @param name to test
* @return a pet if pet name is already in use
*/
public Pet getPet(String name) {
return getPet(name, false);
}
/**
* Return the Pet with the given id, or null if none found for this Owner.
* @param id to test
* @return a pet if pet id is already in use
*/
public Pet getPet(Integer id) {
for (Pet pet : getPets()) {
if (!pet.isNew()) {
Integer compId = pet.getId();
if (compId.equals(id)) {
return pet;
}
}
}
return null;
}
/**
* Return the Pet with the given name, or null if none found for this Owner.
* @param name to test
* @return a pet if pet name is already in use
*/
public Pet getPet(String name, boolean ignoreNew) {
name = name.toLowerCase();
for (Pet pet : getPets()) {
String compName = pet.getName();
if (compName != null && compName.equalsIgnoreCase(name)) {
if (!ignoreNew || !pet.isNew()) {
return pet;
}
}
}
return null;
}
@Override
public String toString() {
return new ToStringCreator(this).append("id", this.getId())
.append("new", this.isNew())
.append("lastName", this.getLastName())
.append("firstName", this.getFirstName())
.append("address", this.address)
.append("city", this.city)
.append("telephone", this.telephone)
.toString();
}
}

View File

@@ -0,0 +1,21 @@
package org.test;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface OwnerRepository extends Repository<Owner, Integer> {
@Query("SELECT DISTINCT owner FROM Owner owner left join owner.pets WHERE owner.lastName LIKE :lastName% ")
@Transactional(readOnly = true)
Page<Owner> findByLastName(@Param("lastName") String lastName, Pageable pageable);
@Query("SELECT owner FROM Owner owner")
@Transactional(readOnly = true)
Page<Owner> findAll(Pageable pageable);
@Query(value="SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.id =:id")
@Transactional(readOnly = true)
Owner findById(@Param("id") Integer id);
}

View File

@@ -0,0 +1,43 @@
package org.test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class SpelController {
@Value("${app.version}")
private String appVersion;
@Value(value="#{'${app.version}' matches '\\\\d+\\\\.\\\\d+\\\\.\\\\d+' ? '${app.version}' : 'Invalid Version'}")
private String version;
@Value("#{T(org.springframework.samples.petclinic.owner.SpelController).isValidVersion('${app.version}') ? 'Valid Version' :'Invalid Version'}")
private String versionValidity;
@GetMapping("/version")
@ResponseBody
public String getAppVersionInfo() {
return "Version: " + appVersion + ", Version Validity: " + version;
}
@GetMapping("/validateVersion")
@ResponseBody
public String validateVersion() {
return "Version: " + appVersion + ", Version Validity: " + versionValidity;
}
public static boolean isValidVersion(String version) {
if (version.matches("\\d+\\.\\d+\\.\\d+")) {
String[] parts = version.split("\\.");
int major = Integer.parseInt(parts[0]);
int minor = Integer.parseInt(parts[1]);
int patch = Integer.parseInt(parts[2]);
return (major > 3) || (major == 3 && (minor > 0 || (minor == 0 && patch >= 0)));
}
return false;
}
}

View File

@@ -21,6 +21,7 @@ import {registerJavaDataService} from "@pivotal-tools/commons-vscode/lib/java-da
import * as setLogLevelUi from './set-log-levels-ui';
import { startTestJarSupport } from "./test-jar-launch";
import { startPropertiesConversionSupport } from "./convert-props-yaml";
import { activateCopilotFeatures } from "./copilot";
const PROPERTIES_LANGUAGE_ID = "spring-boot-properties";
const YAML_LANGUAGE_ID = "spring-boot-properties-yaml";
@@ -147,6 +148,8 @@ export function activate(context: ExtensionContext): Thenable<ExtensionAPI> {
registerClasspathService(client);
registerJavaDataService(client);
activateCopilotFeatures(context);
// Force classpath listener to be enabled. Boot LS can only be launched iff classpath is available and there Spring-Boot on the classpath somewhere.
commands.executeCommand('sts.vscode-spring-boot.enableClasspathListening', true);

View File

@@ -0,0 +1,111 @@
import { commands, ExtensionContext, extensions, lm, LanguageModelChatSelector, window, workspace, LogOutputChannel, version } from "vscode";
import { SemVer } from "semver";
export const REQUIRED_EXTENSION = 'github.copilot-chat';
const DEFAULT_MODEL_SELECTOR: LanguageModelChatSelector = { vendor: 'copilot', family: 'gpt-4' };
export const logger: LogOutputChannel = window.createOutputChannel("Spring tools copilot", { log: true });
export async function activateCopilotFeatures(context: ExtensionContext): Promise<void> {
if(!isLlmApiAvailable("1.90.0-insider")) { // lm API is available since 1.90.0-insider
return;
}
workspace.onDidChangeConfiguration(event => {
if (event.affectsConfiguration('boot-java.highlight-copilot-codelens.on')) {
promptReloadWindow();
}
});
logger.info("vscode.lm is ready.");
await ensureExtensionInstalledAndActivated();
await updateConfigurationBasedOnCopilotAccess();
// Add listener to handle installation/uninstallation of the required extension
extensions.onDidChange(async () => {
await ensureExtensionInstalledAndActivated();
await updateConfigurationBasedOnCopilotAccess();
});
explainQueryWithCopilot();
}
function isLlmApiAvailable(v: string): boolean {
return new SemVer(version).compare(new SemVer(v)) >= 0;
}
async function ensureExtensionInstalledAndActivated() {
if (!isExtensionInstalled(REQUIRED_EXTENSION)) {
logger.error(`Required extension ${REQUIRED_EXTENSION} is not installed.`);
return;
}
if (!isExtensionActivated(REQUIRED_EXTENSION)) {
logger.error(`Required extension ${REQUIRED_EXTENSION} is not activated.`);
await waitUntilExtensionActivated(REQUIRED_EXTENSION);
}
}
function isExtensionInstalled(extensionId: string): boolean {
return !!extensions.getExtension(extensionId);
}
function isExtensionActivated(extensionId: string): boolean {
return !!extensions.getExtension(extensionId)?.isActive;
}
async function waitUntilExtensionActivated(extensionId: string, interval: number = 3500) {
logger.info(`Waiting for extension ${extensionId} to be activated...`);
return new Promise<void>((resolve) => {
const id = setInterval(() => {
if (extensions.getExtension(extensionId)?.isActive) {
clearInterval(id);
resolve();
}
}, interval);
});
}
async function updateConfigurationBasedOnCopilotAccess() {
if (!isExtensionInstalled(REQUIRED_EXTENSION) || !isExtensionActivated(REQUIRED_EXTENSION)) {
await updateConfiguration(false);
return;
}
const model = (await lm.selectChatModels(DEFAULT_MODEL_SELECTOR))?.[0];
if (!model) {
const models = await lm.selectChatModels();
logger.error(`No suitable model, available models: [${models.map(m => m.name).join(', ')}]. Please make sure you have installed the latest "GitHub Copilot Chat" (v0.16.0 or later) and all \`lm\` API is enabled.`);
await updateConfiguration(false);
} else {
await updateConfiguration(true);
}
}
async function updateConfiguration(value: boolean) {
const configValue = workspace.getConfiguration().get('boot-java.highlight-copilot-codelens.on');
if(value && configValue === true) {
commands.executeCommand('sts/enable/copilot/features', value);
}
}
async function explainQueryWithCopilot() {
commands.registerCommand('vscode-spring-boot.query.explain', async (userPrompt) => {
console.log('spel.explain: ' + userPrompt);
console.log('messages: ' + userPrompt);
await commands.executeCommand('workbench.action.chat.open', { query: userPrompt });
})
}
async function promptReloadWindow() {
const reload = await window.showInformationMessage(
'Configuration updated. Please reload VS Code to apply changes.',
'Reload'
);
if (reload === 'Reload') {
await commands.executeCommand('workbench.action.reloadWindow');
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -16,7 +16,9 @@
},
"categories": [
"Programming Languages",
"Linters"
"Linters",
"AI",
"Chat"
],
"keywords": [
"java-properties",
@@ -241,6 +243,11 @@
"enablement": "vscode-spring-boot.active-app-state == 'connected'",
"icon": "$(refresh)",
"category": "Spring Boot"
},
{
"command": "vscode-spring-boot.query.explain",
"title": "Explain Spel Expressions and Queries",
"category": "Spring Boot"
}
],
"configuration": [
@@ -379,6 +386,11 @@
],
"scope": "window",
"description": "Defines which browser to use when opening Spring Boot apps web pages."
},
"boot-java.highlight-copilot-codelens.on": {
"type": "boolean",
"default": false,
"description": "Explain SpEL Expressions and queries using Copilot"
}
}
},
@@ -1252,7 +1264,7 @@
},
"devDependencies": {
"@types/node": "^18.8.0",
"@types/vscode": "1.75.0",
"@types/semver": "^7.5.8",
"@vscode/vsce": "^2.22.0",
"typescript": "^4.8.0"
},