diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/SpringSymbolIndexerConfig.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/SpringSymbolIndexerConfig.java index 25c71eb5d..949752254 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/SpringSymbolIndexerConfig.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/SpringSymbolIndexerConfig.java @@ -19,6 +19,7 @@ import org.springframework.ide.vscode.boot.java.beans.BeansSymbolProvider; import org.springframework.ide.vscode.boot.java.beans.ComponentSymbolProvider; import org.springframework.ide.vscode.boot.java.beans.FeignClientSymbolProvider; import org.springframework.ide.vscode.boot.java.data.DataRepositorySymbolProvider; +import org.springframework.ide.vscode.boot.java.events.EventListenerSymbolProvider; import org.springframework.ide.vscode.boot.java.handlers.SymbolProvider; import org.springframework.ide.vscode.boot.java.requestmapping.RequestMappingSymbolProvider; import org.springframework.ide.vscode.boot.java.utils.RestrictedDefaultSymbolProvider; @@ -35,6 +36,7 @@ public class SpringSymbolIndexerConfig { ComponentSymbolProvider componentSymbolProvider = new ComponentSymbolProvider(); RestrictedDefaultSymbolProvider restrictedDefaultSymbolProvider = new RestrictedDefaultSymbolProvider(); DataRepositorySymbolProvider dataRepositorySymbolProvider = new DataRepositorySymbolProvider(); + EventListenerSymbolProvider eventListenerSymbolProvider = new EventListenerSymbolProvider(); providers.put(Annotations.SPRING_REQUEST_MAPPING, requestMappingSymbolProvider); providers.put(Annotations.SPRING_GET_MAPPING, requestMappingSymbolProvider); @@ -70,6 +72,7 @@ public class SpringSymbolIndexerConfig { providers.put(Annotations.CONDITIONAL_ON_SINGLE_CANDIDATE, restrictedDefaultSymbolProvider); providers.put(Annotations.REPOSITORY, dataRepositorySymbolProvider); + providers.put(Annotations.EVENT_LISTENER, eventListenerSymbolProvider); providers.put(Annotations.FEIGN_CLIENT, new FeignClientSymbolProvider()); diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/Annotations.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/Annotations.java index b2aa8884b..43ee68598 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/Annotations.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/Annotations.java @@ -89,6 +89,8 @@ public class Annotations { public static final Set NAMED_ANNOTATIONS = Set.of(Annotations.NAMED_JAKARTA, Annotations.NAMED_JAVAX); public static final String SCHEDULED = "org.springframework.scheduling.annotation.Scheduled"; + public static final String EVENT_LISTENER = "org.springframework.context.event.EventListener"; + public static final String APPLICATION_LISTENER = "org.springframework.context.ApplicationListener"; public static final Map AOP_ANNOTATIONS = Map.of( "org.aspectj.lang.annotation.Pointcut", "Pointcut", diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/beans/BeanUtils.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/beans/BeanUtils.java index bc6b75498..8e04c7d84 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/beans/BeanUtils.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/beans/BeanUtils.java @@ -77,5 +77,10 @@ public class BeanUtils { } return typeName; } + + public static String getBeanName(TypeDeclaration typeDeclaration) { + String beanName = typeDeclaration.getName().toString(); + return BeanUtils.getBeanNameFromType(beanName); + } } diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/beans/BeansSymbolProvider.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/beans/BeansSymbolProvider.java index 9ffdeb21d..5309b53fd 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/beans/BeansSymbolProvider.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/beans/BeansSymbolProvider.java @@ -53,7 +53,6 @@ import org.springframework.ide.vscode.commons.util.text.TextDocument; import com.google.common.collect.ImmutableList; import reactor.util.function.Tuple2; -import reactor.util.function.Tuple3; import reactor.util.function.Tuples; /** @@ -134,12 +133,12 @@ public class BeansSymbolProvider extends AbstractSymbolProvider { @Override protected void addSymbolsPass1(TypeDeclaration typeDeclaration, SpringIndexerJavaContext context, TextDocument doc) { // this checks function beans that are defined as implementations of Function interfaces - Tuple3 functionBean = FunctionUtils.getFunctionBean(typeDeclaration, doc); + ITypeBinding functionBean = FunctionUtils.getFunctionBean(typeDeclaration, doc); if (functionBean != null) { try { - String beanName = functionBean.getT1(); - ITypeBinding beanType = functionBean.getT2(); - Location beanLocation = new Location(doc.getUri(), doc.toRange(functionBean.getT3())); + String beanName = BeanUtils.getBeanName(typeDeclaration); + ITypeBinding beanType = functionBean; + Location beanLocation = new Location(doc.getUri(), doc.toRange(ASTUtils.nodeRegion(doc, typeDeclaration.getName()))); WorkspaceSymbol symbol = new WorkspaceSymbol( beanLabel(true, beanName, beanType.getName(), null), diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/beans/ComponentSymbolProvider.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/beans/ComponentSymbolProvider.java index 2ef353afd..788984b0a 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/beans/ComponentSymbolProvider.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/beans/ComponentSymbolProvider.java @@ -18,17 +18,18 @@ import java.util.stream.Collectors; import java.util.stream.Stream; 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.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.lsp4j.Location; import org.eclipse.lsp4j.SymbolKind; import org.eclipse.lsp4j.WorkspaceSymbol; import org.eclipse.lsp4j.jsonrpc.messages.Either; -import org.eclipse.lsp4j.jsonrpc.messages.Tuple; -import org.eclipse.lsp4j.jsonrpc.messages.Tuple.Two; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ide.vscode.boot.java.Annotations; +import org.springframework.ide.vscode.boot.java.events.EventListenerIndexElement; import org.springframework.ide.vscode.boot.java.handlers.AbstractSymbolProvider; import org.springframework.ide.vscode.boot.java.handlers.EnhancedSymbolInformation; import org.springframework.ide.vscode.boot.java.utils.ASTUtils; @@ -39,6 +40,7 @@ import org.springframework.ide.vscode.commons.protocol.spring.AnnotationMetadata import org.springframework.ide.vscode.commons.protocol.spring.Bean; import org.springframework.ide.vscode.commons.protocol.spring.InjectionPoint; import org.springframework.ide.vscode.commons.util.BadLocationException; +import org.springframework.ide.vscode.commons.util.text.DocumentRegion; import org.springframework.ide.vscode.commons.util.text.TextDocument; /** @@ -53,12 +55,7 @@ public class ComponentSymbolProvider extends AbstractSymbolProvider { protected void addSymbolsPass1(Annotation node, ITypeBinding annotationType, Collection metaAnnotations, SpringIndexerJavaContext context, TextDocument doc) { try { if (node != null && node.getParent() != null && node.getParent() instanceof TypeDeclaration) { - Two result = createSymbol(node, annotationType, metaAnnotations, doc); - - EnhancedSymbolInformation enhancedSymbol = result.getFirst(); - Bean beanDefinition = result.getSecond(); - context.getGeneratedSymbols().add(new CachedSymbol(context.getDocURI(), context.getLastModified(), enhancedSymbol)); - context.getBeans().add(new CachedBean(context.getDocURI(), beanDefinition)); + createSymbol(node, annotationType, metaAnnotations, context, doc); } else if (Annotations.NAMED_ANNOTATIONS.contains(annotationType.getQualifiedName())) { WorkspaceSymbol symbol = DefaultSymbolProvider.provideDefaultSymbol(node, doc); @@ -71,7 +68,7 @@ public class ComponentSymbolProvider extends AbstractSymbolProvider { } } - protected Tuple.Two createSymbol(Annotation node, ITypeBinding annotationType, Collection metaAnnotations, TextDocument doc) throws BadLocationException { + protected void createSymbol(Annotation node, ITypeBinding annotationType, Collection metaAnnotations, SpringIndexerJavaContext context, TextDocument doc) throws BadLocationException { String annotationTypeName = annotationType.getName(); Collection metaAnnotationNames = metaAnnotations.stream() @@ -81,7 +78,7 @@ public class ComponentSymbolProvider extends AbstractSymbolProvider { TypeDeclaration type = (TypeDeclaration) node.getParent(); String beanName = BeanUtils.getBeanNameFromComponentAnnotation(node, type); - ITypeBinding beanType = getBeanType(type); + ITypeBinding beanType = type.resolveBinding(); Location location = new Location(doc.getUri(), doc.toRange(node.getStartPosition(), node.getLength())); @@ -107,8 +104,49 @@ public class ComponentSymbolProvider extends AbstractSymbolProvider { .toArray(AnnotationMetadata[]::new); Bean beanDefinition = new Bean(beanName, beanType.getQualifiedName(), location, injectionPoints, supertypes, annotations, isConfiguration); + + // event listener - create child element, if necessary + ITypeBinding inTypeHierarchy = ASTUtils.findInTypeHierarchy(type, doc, beanType, Set.of(Annotations.APPLICATION_LISTENER)); + if (inTypeHierarchy != null) { - return Tuple.two(new EnhancedSymbolInformation(symbol), beanDefinition); + MethodDeclaration handleEventMethod = findHandleEventMethod(type); + if (handleEventMethod != null) { + + IMethodBinding methodBinding = handleEventMethod.resolveBinding(); + ITypeBinding[] parameterTypes = methodBinding.getParameterTypes(); + if (parameterTypes != null && parameterTypes.length == 1) { + + ITypeBinding eventType = parameterTypes[0]; + String eventTypeFq = eventType.getQualifiedName(); + + DocumentRegion nodeRegion = ASTUtils.nodeRegion(doc, handleEventMethod.getName()); + Location handleMethodLocation = new Location(doc.getUri(), nodeRegion.asRange()); + + Collection annotationsOnHandleEventMethod = ASTUtils.getAnnotations(handleEventMethod); + AnnotationMetadata[] handleEventMethodAnnotations = ASTUtils.getAnnotationsMetadata(annotationsOnHandleEventMethod, doc); + + EventListenerIndexElement eventElement = new EventListenerIndexElement(eventTypeFq, handleMethodLocation, handleEventMethodAnnotations); + beanDefinition.addChild(eventElement); + } + } + } + + context.getGeneratedSymbols().add(new CachedSymbol(context.getDocURI(), context.getLastModified(), new EnhancedSymbolInformation(symbol))); + context.getBeans().add(new CachedBean(context.getDocURI(), beanDefinition)); + } + + private MethodDeclaration findHandleEventMethod(TypeDeclaration type) { + MethodDeclaration[] methods = type.getMethods(); + + for (MethodDeclaration method : methods) { + IMethodBinding binding = method.resolveBinding(); + String name = binding.getName(); + + if (name != null && name.equals("onApplicationEvent")) { + return method; + } + } + return null; } protected String beanLabel(String searchPrefix, String annotationTypeName, Collection metaAnnotationNames, String beanName, String beanType) { @@ -137,9 +175,5 @@ public class ComponentSymbolProvider extends AbstractSymbolProvider { symbolLabel.append(beanType); return symbolLabel.toString(); } - - private ITypeBinding getBeanType(TypeDeclaration type) { - return type.resolveBinding(); - } } diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/events/EventListenerIndexElement.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/events/EventListenerIndexElement.java new file mode 100644 index 000000000..a881e050a --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/events/EventListenerIndexElement.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (c) 2025 Broadcom + * 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 - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.events; + +import org.eclipse.lsp4j.Location; +import org.springframework.ide.vscode.commons.protocol.spring.AbstractSpringIndexElement; +import org.springframework.ide.vscode.commons.protocol.spring.AnnotationMetadata; + +/** + * @author Martin Lippert + */ +public class EventListenerIndexElement extends AbstractSpringIndexElement { + + private final String eventType; + private final Location location; + private final AnnotationMetadata[] annotations; + + public EventListenerIndexElement(String eventType, Location location, AnnotationMetadata[] annotations) { + this.eventType = eventType; + this.location = location; + this.annotations = annotations; + } + + public String getEventType() { + return eventType; + } + + public AnnotationMetadata[] getAnnotations() { + return annotations; + } + + public Location getLocation() { + return location; + } + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/events/EventListenerSymbolProvider.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/events/EventListenerSymbolProvider.java new file mode 100644 index 000000000..5c8428766 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/events/EventListenerSymbolProvider.java @@ -0,0 +1,126 @@ +/******************************************************************************* + * Copyright (c) 2025 Broadcom + * 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 - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.events; +import java.util.Collection; +import java.util.List; + +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.Annotation; +import org.eclipse.jdt.core.dom.ITypeBinding; +import org.eclipse.jdt.core.dom.IVariableBinding; +import org.eclipse.jdt.core.dom.MethodDeclaration; +import org.eclipse.jdt.core.dom.SingleVariableDeclaration; +import org.eclipse.lsp4j.Location; +import org.eclipse.lsp4j.SymbolKind; +import org.eclipse.lsp4j.WorkspaceSymbol; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.ide.vscode.boot.java.beans.CachedBean; +import org.springframework.ide.vscode.boot.java.handlers.AbstractSymbolProvider; +import org.springframework.ide.vscode.boot.java.handlers.EnhancedSymbolInformation; +import org.springframework.ide.vscode.boot.java.utils.ASTUtils; +import org.springframework.ide.vscode.boot.java.utils.CachedSymbol; +import org.springframework.ide.vscode.boot.java.utils.SpringIndexerJavaContext; +import org.springframework.ide.vscode.commons.protocol.spring.AnnotationMetadata; +import org.springframework.ide.vscode.commons.util.BadLocationException; +import org.springframework.ide.vscode.commons.util.text.DocumentRegion; +import org.springframework.ide.vscode.commons.util.text.TextDocument; + +/** + * @author Martin Lippert + */ +public class EventListenerSymbolProvider extends AbstractSymbolProvider { + + private static final Logger log = LoggerFactory.getLogger(EventListenerSymbolProvider.class); + + @Override + protected void addSymbolsPass1(Annotation node, ITypeBinding typeBinding, Collection metaAnnotations, SpringIndexerJavaContext context, TextDocument doc) { + if (node == null) return; + + ASTNode parent = node.getParent(); + if (parent == null || !(parent instanceof MethodDeclaration)) return; + + MethodDeclaration method = (MethodDeclaration) parent; + + + // symbol + try { + String symbolLabel = createEventListenerSymbolLabel(node, method); + WorkspaceSymbol symbol = new WorkspaceSymbol(symbolLabel, SymbolKind.Interface, + Either.forLeft(new Location(doc.getUri(), doc.toRange(node.getStartPosition(), node.getLength())))); + + EnhancedSymbolInformation enhancedSymbol = new EnhancedSymbolInformation(symbol); + context.getGeneratedSymbols().add(new CachedSymbol(context.getDocURI(), context.getLastModified(), enhancedSymbol)); + + + // index element for event listener + Collection annotationsOnMethod = ASTUtils.getAnnotations(method); + AnnotationMetadata[] annotations = ASTUtils.getAnnotationsMetadata(annotationsOnMethod, doc); + + List beans = context.getBeans(); + if (beans.size() > 0 ) { + + CachedBean cachedBean = beans.get(beans.size() - 1); + if (cachedBean.getDocURI().equals(doc.getUri())) { + + ITypeBinding eventType = getEventType(node, method); + DocumentRegion nodeRegion = ASTUtils.nodeRegion(doc, method.getName()); + Location location = new Location(doc.getUri(), nodeRegion.asRange()); + + cachedBean.getBean().addChild(new EventListenerIndexElement(eventType != null ? eventType.getQualifiedName() : "", location, annotations)); + } + } + } catch (BadLocationException e) { + log.error("", e); + } + } + + private String createEventListenerSymbolLabel(Annotation node, MethodDeclaration method) { + // event listener annotation type + String annotationTypeName = getAnnotationTypeName(node); + ITypeBinding eventType = getEventType(node, method); + + if (annotationTypeName != null) { + return "@" + annotationTypeName + (eventType != null ? " (" + eventType.getName() + ")" : ""); + } + else { + return node.toString(); + } + } + + private ITypeBinding getEventType(Annotation node, MethodDeclaration method) { + List parameters = method.parameters(); + if (parameters != null && parameters.size() == 1) { + SingleVariableDeclaration param = (SingleVariableDeclaration) parameters.get(0); + + IVariableBinding paramBinding = param.resolveBinding(); + if (paramBinding != null) { + ITypeBinding paramType = paramBinding.getType(); + return paramType != null ? paramType : null; + } + } + + return null; + } + + private String getAnnotationTypeName(Annotation node) { + ITypeBinding typeBinding = node.resolveTypeBinding(); + if (typeBinding != null) { + return typeBinding.getName(); + } + else { + return null; + } + } + + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/spel/AnnotationParamSpelExtractor.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/spel/AnnotationParamSpelExtractor.java index 038a73d13..7c16486ca 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/spel/AnnotationParamSpelExtractor.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/spel/AnnotationParamSpelExtractor.java @@ -28,8 +28,6 @@ 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"; - private static final String SPRING_EVENT_LISTENER = "org.springframework.context.event.EventListener"; - private static final String SPRING_PRE_AUTHORIZE = "org.springframework.security.access.prepost.PreAuthorize"; private static final String SPRING_PRE_FILTER = "org.springframework.security.access.prepost.PreFilter"; private static final String SPRING_POST_AUTHORIZE = "org.springframework.security.access.prepost.PostAuthorize"; @@ -48,7 +46,7 @@ public final class AnnotationParamSpelExtractor { new AnnotationParamSpelExtractor(SPRING_CACHE_EVICT, "key", "", ""), new AnnotationParamSpelExtractor(SPRING_CACHE_EVICT, "condition", "", ""), - new AnnotationParamSpelExtractor(SPRING_EVENT_LISTENER, "condition", "", ""), + new AnnotationParamSpelExtractor(Annotations.EVENT_LISTENER, "condition", "", ""), new AnnotationParamSpelExtractor(SPRING_PRE_AUTHORIZE, null, "", ""), new AnnotationParamSpelExtractor(SPRING_PRE_AUTHORIZE, "value", "", ""), diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/utils/ASTUtils.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/utils/ASTUtils.java index c0d484f5e..3a99f2b04 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/utils/ASTUtils.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/utils/ASTUtils.java @@ -35,6 +35,7 @@ import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.MemberValuePair; import org.eclipse.jdt.core.dom.MethodDeclaration; +import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.NormalAnnotation; import org.eclipse.jdt.core.dom.QualifiedName; @@ -341,6 +342,52 @@ public class ASTUtils { return null; } + public static boolean isAbstractClass(TypeDeclaration typeDeclaration) { + List modifiers = typeDeclaration.modifiers(); + for (Object object : modifiers) { + if (object instanceof Modifier) { + if (((Modifier) object).isAbstract()) { + return true; + } + } + } + + return false; + } + + public static ITypeBinding findInTypeHierarchy(TypeDeclaration typeDeclaration, TextDocument doc, ITypeBinding resolvedType, Set typesToCheck) { + ITypeBinding[] interfaces = resolvedType.getInterfaces(); + + for (ITypeBinding resolvedInterface : interfaces) { + String simplifiedType = null; + + if (resolvedInterface.isParameterizedType()) { + simplifiedType = resolvedInterface.getBinaryName(); + } + else { + simplifiedType = resolvedType.getQualifiedName(); + } + + if (typesToCheck.contains(simplifiedType)) { + return resolvedInterface; + } + else { + ITypeBinding result = findInTypeHierarchy(typeDeclaration, doc, resolvedInterface, typesToCheck); + if (result != null) { + return result; + } + } + } + + ITypeBinding superclass = resolvedType.getSuperclass(); + if (superclass != null) { + return findInTypeHierarchy(typeDeclaration, doc, superclass, typesToCheck); + } + else { + return null; + } + } + public static Optional getImportsEdit(CompilationUnit cu, Collection imprts, IDocument doc) { ImportRewrite rewrite = ImportRewrite.create(cu, true); diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/utils/FunctionUtils.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/utils/FunctionUtils.java index d73437d7f..46b3aa5dd 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/utils/FunctionUtils.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/utils/FunctionUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2018 Pivotal, Inc. + * Copyright (c) 2018, 2025 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,21 +10,15 @@ *******************************************************************************/ package org.springframework.ide.vscode.boot.java.utils; -import java.util.List; +import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import org.eclipse.jdt.core.dom.ITypeBinding; -import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.TypeDeclaration; -import org.springframework.ide.vscode.boot.java.beans.BeanUtils; -import org.springframework.ide.vscode.commons.util.text.DocumentRegion; import org.springframework.ide.vscode.commons.util.text.TextDocument; -import reactor.util.function.Tuple3; -import reactor.util.function.Tuples; - /** * @author Martin Lippert */ @@ -33,71 +27,18 @@ public class FunctionUtils { public static final String FUNCTION_FUNCTION_TYPE = Function.class.getName(); public static final String FUNCTION_CONSUMER_TYPE = Consumer.class.getName(); public static final String FUNCTION_SUPPLIER_TYPE = Supplier.class.getName(); + + public static final Set FUNCTION_TYPES = Set.of(FUNCTION_FUNCTION_TYPE, FUNCTION_CONSUMER_TYPE, FUNCTION_SUPPLIER_TYPE); - public static Tuple3 getFunctionBean(TypeDeclaration typeDeclaration, TextDocument doc) { + public static ITypeBinding getFunctionBean(TypeDeclaration typeDeclaration, TextDocument doc) { ITypeBinding resolvedType = typeDeclaration.resolveBinding(); - if (resolvedType != null && !resolvedType.isInterface() && !isAbstractClass(typeDeclaration, resolvedType)) { - return getFunctionBean(typeDeclaration, doc, resolvedType); + if (resolvedType != null && !resolvedType.isInterface() && !ASTUtils.isAbstractClass(typeDeclaration)) { + return ASTUtils.findInTypeHierarchy(typeDeclaration, doc, resolvedType, FUNCTION_TYPES); } else { return null; } } - private static Tuple3 getFunctionBean(TypeDeclaration typeDeclaration, TextDocument doc, - ITypeBinding resolvedType) { - - ITypeBinding[] interfaces = resolvedType.getInterfaces(); - for (ITypeBinding resolvedInterface : interfaces) { - String simplifiedType = null; - if (resolvedInterface.isParameterizedType()) { - simplifiedType = resolvedInterface.getBinaryName(); - } - else { - simplifiedType = resolvedType.getQualifiedName(); - } - - if (FUNCTION_FUNCTION_TYPE.equals(simplifiedType) || FUNCTION_CONSUMER_TYPE.equals(simplifiedType) - || FUNCTION_SUPPLIER_TYPE.equals(simplifiedType)) { - String beanName = getBeanName(typeDeclaration); - DocumentRegion region = ASTUtils.nodeRegion(doc, typeDeclaration.getName()); - - return Tuples.of(beanName, resolvedInterface, region); - } - else { - Tuple3 result = getFunctionBean(typeDeclaration, doc, resolvedInterface); - if (result != null) { - return result; - } - } - } - - ITypeBinding superclass = resolvedType.getSuperclass(); - if (superclass != null) { - return getFunctionBean(typeDeclaration, doc, superclass); - } - else { - return null; - } - } - - protected static String getBeanName(TypeDeclaration typeDeclaration) { - String beanName = typeDeclaration.getName().toString(); - return BeanUtils.getBeanNameFromType(beanName); - } - - protected static boolean isAbstractClass(TypeDeclaration typeDeclaration, ITypeBinding resolvedType) { - List modifiers = typeDeclaration.modifiers(); - for (Object object : modifiers) { - if (object instanceof Modifier) { - if (((Modifier) object).isAbstract()) { - return true; - } - } - } - - return false; - } - } diff --git a/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/beans/test/SpringIndexerEventsTest.java b/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/beans/test/SpringIndexerEventsTest.java new file mode 100644 index 000000000..7b45055fd --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/beans/test/SpringIndexerEventsTest.java @@ -0,0 +1,137 @@ +/******************************************************************************* + * Copyright (c) 2025 Broadcom + * 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 - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.beans.test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.File; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import org.eclipse.lsp4j.Location; +import org.eclipse.lsp4j.Position; +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.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.index.SpringMetamodelIndex; +import org.springframework.ide.vscode.boot.java.events.EventListenerIndexElement; +import org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFinder; +import org.springframework.ide.vscode.commons.protocol.spring.Bean; +import org.springframework.ide.vscode.commons.protocol.spring.SpringIndexElement; +import org.springframework.ide.vscode.project.harness.BootLanguageServerHarness; +import org.springframework.ide.vscode.project.harness.ProjectsHarness; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +/** + * @author Martin Lippert + */ +@ExtendWith(SpringExtension.class) +@BootLanguageServerTest +@Import(SymbolProviderTestConf.class) +public class SpringIndexerEventsTest { + + @Autowired private BootLanguageServerHarness harness; + @Autowired private JavaProjectFinder projectFinder; + @Autowired private SpringSymbolIndex indexer; + @Autowired private SpringMetamodelIndex springIndex; + + private File directory; + + @BeforeEach + public void setup() throws Exception { + harness.intialize(null); + + directory = new File(ProjectsHarness.class.getResource("/test-projects/test-events-indexing/").toURI()); + + String projectDir = directory.toURI().toString(); + + // trigger project creation + projectFinder.find(new TextDocumentIdentifier(projectDir)).get(); + + CompletableFuture initProject = indexer.waitOperation(); + initProject.get(5, TimeUnit.SECONDS); + } + + @Test + void testAnnotationBasedEventListenerSymbol() throws Exception { + String docUri = directory.toPath().resolve("src/main/java/com/example/events/demo/EventListenerPerAnnotation.java").toUri().toString(); + + SpringIndexerHarness.assertDocumentSymbols(indexer, docUri, + SpringIndexerHarness.symbol("@Component", "@+ 'eventListenerPerAnnotation' (@Component) EventListenerPerAnnotation"), + SpringIndexerHarness.symbol("@EventListener", "@EventListener (ApplicationEvent)")); + } + + @Test + void testEventListenerSymbolForEventListenerInterfaceImplementation() throws Exception { + String docUri = directory.toPath().resolve("src/main/java/com/example/events/demo/EventListenerPerInterface.java").toUri().toString(); + + SpringIndexerHarness.assertDocumentSymbols(indexer, docUri, + SpringIndexerHarness.symbol("@Component", "@+ 'eventListenerPerInterface' (@Component) EventListenerPerInterface")); + } + + @Test + void testAnnotationBasedEventListenerIndexElements() throws Exception { + String docUri = directory.toPath().resolve("src/main/java/com/example/events/demo/EventListenerPerAnnotation.java").toUri().toString(); + + Bean[] beans = springIndex.getBeansOfDocument(docUri); + assertEquals(1, beans.length); + + Bean listenerComponentBean = Arrays.stream(beans).filter(bean -> bean.getName().equals("eventListenerPerAnnotation")).findFirst().get(); + assertEquals("com.example.events.demo.EventListenerPerAnnotation", listenerComponentBean.getType()); + + List children = listenerComponentBean.getChildren(); + assertEquals(1, children.size()); + assertTrue(children.get(0) instanceof EventListenerIndexElement); + + EventListenerIndexElement listenerElement = (EventListenerIndexElement) children.get(0); + assertEquals("org.springframework.context.ApplicationEvent", listenerElement.getEventType()); + + Location location = listenerElement.getLocation(); + assertNotNull(location); + assertEquals(docUri, location.getUri()); + assertEquals(new Range(new Position(10, 13), new Position(10, 24)), location.getRange()); + } + + @Test + void testEventListenerIndexElementForEventListenerInterfaceImplementation() throws Exception { + String docUri = directory.toPath().resolve("src/main/java/com/example/events/demo/EventListenerPerInterface.java").toUri().toString(); + + Bean[] beans = springIndex.getBeansOfDocument(docUri); + assertEquals(1, beans.length); + + Bean listenerComponentBean = Arrays.stream(beans).filter(bean -> bean.getName().equals("eventListenerPerInterface")).findFirst().get(); + assertEquals("com.example.events.demo.EventListenerPerInterface", listenerComponentBean.getType()); + + List children = listenerComponentBean.getChildren(); + assertEquals(1, children.size()); + assertTrue(children.get(0) instanceof EventListenerIndexElement); + + EventListenerIndexElement listenerElement = (EventListenerIndexElement) children.get(0); + assertEquals("org.springframework.context.ApplicationEvent", listenerElement.getEventType()); + + Location location = listenerElement.getLocation(); + assertNotNull(location); + assertEquals(docUri, location.getUri()); + assertEquals(new Range(new Position(10, 13), new Position(10, 31)), location.getRange()); + } + +} diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/.gitattributes b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/.gitattributes new file mode 100644 index 000000000..3b41682ac --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/.gitignore b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/.gitignore new file mode 100644 index 000000000..549e00a2a --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/.mvn/wrapper/maven-wrapper.properties b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..d58dfb70b --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# 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. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/mvnw b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/mvnw new file mode 100755 index 000000000..19529ddf8 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/mvnw @@ -0,0 +1,259 @@ +#!/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 +# +# 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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + 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" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/mvnw.cmd b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/mvnw.cmd new file mode 100644 index 000000000..249bdf382 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@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 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 +@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 Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/pom.xml b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/pom.xml new file mode 100644 index 000000000..b4e9debc6 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.2 + + + com.example.qualifier + test-events-indexing + 0.0.1-SNAPSHOT + test-events-indexing + Demo project for Spring Boot + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/CustomEvent.java b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/CustomEvent.java new file mode 100644 index 000000000..3f8a2d496 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/CustomEvent.java @@ -0,0 +1,4 @@ +package com.example.events.demo; + +public class CustomEvent { +} diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/CustomEventPublisher.java b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/CustomEventPublisher.java new file mode 100644 index 000000000..70f6841d6 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/CustomEventPublisher.java @@ -0,0 +1,19 @@ +package com.example.events.demo; + +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Component; + +@Component +public class CustomEventPublisher { + + private ApplicationEventPublisher publisher; + + public CustomEventPublisher(ApplicationEventPublisher publisher) { + this.publisher = publisher; + } + + public void foo() { + this.publisher.publishEvent(new CustomEvent()); + } + +} diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/EventListenerPerAnnotation.java b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/EventListenerPerAnnotation.java new file mode 100644 index 000000000..96bb82918 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/EventListenerPerAnnotation.java @@ -0,0 +1,15 @@ +package com.example.events.demo; + +import org.springframework.context.ApplicationEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +@Component +public class EventListenerPerAnnotation { + + @EventListener + public void handleEvent(ApplicationEvent event) { + System.out.println(event); + } + +} diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/EventListenerPerAnnotationWithAttributes.java b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/EventListenerPerAnnotationWithAttributes.java new file mode 100644 index 000000000..9c5cde3a8 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/EventListenerPerAnnotationWithAttributes.java @@ -0,0 +1,16 @@ +package com.example.events.demo; + +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.ApplicationEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +@Component +public class EventListenerPerAnnotationWithAttributes { + + @EventListener({ApplicationReadyEvent.class}) + public void handleEvent(ApplicationEvent event) { + System.out.println("Specialized application ready listener: " + event); + } + +} diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/EventListenerPerInterface.java b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/EventListenerPerInterface.java new file mode 100644 index 000000000..8c6e835d4 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/EventListenerPerInterface.java @@ -0,0 +1,15 @@ +package com.example.events.demo; + +import org.springframework.context.ApplicationEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.stereotype.Component; + +@Component +public class EventListenerPerInterface implements ApplicationListener { + + @Override + public void onApplicationEvent(ApplicationEvent event) { + System.out.println("Event received via listener implementation: " + event); + } + +} diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/EventListenerPerInterfaceAndBeanMethod.java b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/EventListenerPerInterfaceAndBeanMethod.java new file mode 100644 index 000000000..fa0c0e7fd --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/EventListenerPerInterfaceAndBeanMethod.java @@ -0,0 +1,13 @@ +package com.example.events.demo; + +import org.springframework.context.ApplicationEvent; +import org.springframework.context.ApplicationListener; + +public class EventListenerPerInterfaceAndBeanMethod implements ApplicationListener { + + @Override + public void onApplicationEvent(ApplicationEvent event) { + System.out.println("Event received via listener implementation and bean method: " + event); + } + +} diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/TestEventsIndexingApplication.java b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/TestEventsIndexingApplication.java new file mode 100644 index 000000000..b29571d38 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/test-events-indexing/src/main/java/com/example/events/demo/TestEventsIndexingApplication.java @@ -0,0 +1,19 @@ +package com.example.events.demo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class TestEventsIndexingApplication { + + public static void main(String[] args) { + SpringApplication.run(TestEventsIndexingApplication.class, args); + } + + @Bean + public EventListenerPerInterfaceAndBeanMethod listenerBean() { + return new EventListenerPerInterfaceAndBeanMethod(); + } + +}