Skip to content

Commit 75f4e40

Browse files
committed
Improved spring-boot version detection, searching for the effective version of the spring-boot-starter artifact.
Rearrange code in spring boot service to add always a pom change listener (refresh spring-boot version, adjust nbactions, etc.) Minor performance improvement when getting spring-boot version. Added check to prevent overwrite nbactions.xml if it is not necessary.
1 parent b62a6ec commit 75f4e40

File tree

2 files changed

+82
-53
lines changed

2 files changed

+82
-53
lines changed

src/main/java/com/github/alexfalappa/nbspringboot/Utils.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,14 @@
6868

6969
import static com.github.alexfalappa.nbspringboot.PrefConstants.PREF_VM_OPTS;
7070
import static com.github.alexfalappa.nbspringboot.PrefConstants.PREF_VM_OPTS_LAUNCH;
71+
import java.util.Objects;
72+
import java.util.Optional;
73+
import static java.util.logging.Level.FINE;
7174
import static java.util.logging.Level.WARNING;
7275
import static java.util.regex.Pattern.compile;
76+
import java.util.stream.Stream;
77+
import org.apache.maven.artifact.Artifact;
78+
import org.netbeans.modules.maven.NbMavenProjectImpl;
7379

7480
/**
7581
* Utility methods used in the plugin.
@@ -496,4 +502,27 @@ public static boolean dependencyArtifactIdContains(NbMavenProject nbMvn, String
496502
}
497503
return false;
498504
}
505+
506+
// find the 'spring-boot-starter' dependency (direct or transitive) and get its effective version
507+
public static Optional<String> getSpringBootVersion(Project project) {
508+
return Stream.of(project)
509+
.filter(Objects::nonNull)
510+
.filter(NbMavenProjectImpl.class::isInstance)
511+
.map(NbMavenProjectImpl.class::cast)
512+
// All dependencies that this project has, including transitive ones.
513+
.flatMap(p -> ((Set<Artifact>)p.getOriginalMavenProject().getArtifacts()).stream())
514+
.filter(Utils::isSpringBootStarterArtifact)
515+
.map(Artifact::getVersion)
516+
.peek(springBootVersion -> logger.log(FINE, "Spring Boot version {0} detected", springBootVersion))
517+
.findFirst();
518+
}
519+
520+
public static boolean isSpringBootProject(Project project){
521+
return getSpringBootVersion(project).isPresent();
522+
}
523+
524+
public static boolean isSpringBootStarterArtifact(Artifact artifact){
525+
return "org.springframework.boot".equals(artifact.getGroupId())
526+
&& "spring-boot-starter".equals(artifact.getArtifactId());
527+
}
499528
}

src/main/java/com/github/alexfalappa/nbspringboot/projects/service/impl/SpringBootServiceImpl.java

Lines changed: 53 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
import java.util.List;
2626
import java.util.Map;
2727
import java.util.Set;
28-
import java.util.logging.Level;
2928
import java.util.logging.Logger;
3029
import java.util.regex.Matcher;
3130
import java.util.regex.Pattern;
@@ -51,6 +50,7 @@
5150

5251
import static java.util.logging.Level.FINE;
5352
import static java.util.logging.Level.INFO;
53+
import static java.util.logging.Level.SEVERE;
5454
import static java.util.regex.Pattern.compile;
5555

5656
/**
@@ -79,36 +79,62 @@ public class SpringBootServiceImpl implements SpringBootService {
7979
private SimpleConfigurationMetadataRepository repo = new SimpleConfigurationMetadataRepository();
8080
private final Map<String, ConfigurationMetadataRepository> reposInJars = new HashMap<>();
8181
private NbMavenProjectImpl mvnPrj;
82+
private String springBootVersion;
8283
private ClassPath cpExec;
8384
private Map<String, ConfigurationMetadataProperty> cachedProperties;
84-
private Map<String, Boolean> cachedDepsPresence = new HashMap<>();
85+
private final Map<String, Boolean> cachedDepsPresence = new HashMap<>();
8586
private final Set<String> collectionProperties = new HashSet<>();
8687
private final Set<String> mapProperties = new HashSet<>();
8788
private final Map<String, HintProvider> providerMap = new HashMap<>();
8889

8990
public SpringBootServiceImpl(Project p) {
90-
if (p instanceof NbMavenProjectImpl) {
91-
this.mvnPrj = (NbMavenProjectImpl) p;
91+
final FileObject projectDirectory = p.getProjectDirectory();
92+
if(p instanceof NbMavenProjectImpl){
93+
logger.log(INFO, "Creating Spring Boot service for project {0}", FileUtil.getFileDisplayName(projectDirectory));
94+
this.mvnPrj = (NbMavenProjectImpl) p;
95+
96+
logger.fine("Checking maven project has a spring boot dependency");
97+
// check maven project is a spring-boot project
98+
this.springBootVersion = Utils.getSpringBootVersion(mvnPrj).orElse(null);
99+
// early exit if no spring boot dependency detected
100+
if (springBootVersion == null) {
101+
return;
102+
}
103+
104+
// listen for pom changes
105+
logger.info("Adding maven pom listener...");
106+
this.mvnPrj.getProjectWatcher().addPropertyChangeListener(new PropertyChangeListener() {
107+
@Override
108+
public void propertyChange(PropertyChangeEvent evt) {
109+
if (NbMavenProject.PROP_PROJECT.equals(evt.getPropertyName())) {
110+
logger.log(FINE, "Maven pom change ({0})", evt.getPropertyName());
111+
long start = System.currentTimeMillis();
112+
refresh();
113+
long elapsedMs = System.currentTimeMillis() - start;
114+
logger.log(FINE, "Spring Boot service refresh took {0}ms", elapsedMs);
115+
}
116+
}
117+
});
118+
} else {
119+
logger.log(SEVERE, "Error creating Spring Boot service for project {0}", FileUtil.getFileDisplayName(projectDirectory));
92120
}
93-
final FileObject projectDirectory = mvnPrj.getProjectDirectory();
94-
logger.log(Level.INFO, "Creating Spring Boot service for project {0}", FileUtil.getFileDisplayName(projectDirectory));
95121
}
96122

97123
@Override
98124
public void refresh() {
99125
logger.info("Refreshing Spring Boot service");
100126
// check maven project has a dependency starting with 'spring-boot'
101127
logger.fine("Checking maven project has a spring boot dependency");
102-
boolean springBootAvailable = Utils.dependencyArtifactIdContains(mvnPrj.getProjectWatcher(), "spring-boot");
128+
springBootVersion = Utils.getSpringBootVersion(mvnPrj).orElse(null);
103129
// clear and exit if no spring boot dependency detected
104-
if (!springBootAvailable) {
130+
if (springBootVersion == null) {
105131
reposInJars.clear();
106132
collectionProperties.clear();
107133
mapProperties.clear();
108134
// TODO delete nbactions.xml file from project dir ?
109135
return;
110136
}
111-
cachedDepsPresence.clear();
137+
cachedDepsPresence.clear();
112138
if (cpExec == null) {
113139
init();
114140
} else {
@@ -194,16 +220,10 @@ public List<ConfigurationMetadataProperty> queryPropertyMetadata(String filter)
194220

195221
@Override
196222
public boolean hasPomDependency(String artifactId) {
197-
if (cpExec == null) {
198-
init();
223+
if (!cachedDepsPresence.containsKey(artifactId)) {
224+
cachedDepsPresence.put(artifactId, Utils.dependencyArtifactIdContains(mvnPrj.getProjectWatcher(), artifactId));
199225
}
200-
if (cachedDepsPresence != null) {
201-
if (!cachedDepsPresence.containsKey(artifactId)) {
202-
cachedDepsPresence.put(artifactId, Utils.dependencyArtifactIdContains(mvnPrj.getProjectWatcher(), artifactId));
203-
}
204-
return cachedDepsPresence.get(artifactId);
205-
}
206-
return false;
226+
return cachedDepsPresence.get(artifactId);
207227
}
208228

209229
@Override
@@ -217,34 +237,9 @@ public String getPluginPropsPrefix() {
217237
}
218238

219239
private void init() {
220-
if (mvnPrj == null) {
221-
return;
222-
}
223-
logger.info("Initializing Spring Boot service");
224-
// check maven project has a dependency starting with 'spring-boot'
225-
boolean springBootAvailable = Utils.dependencyArtifactIdContains(mvnPrj.getProjectWatcher(), "spring-boot");
226-
logger.fine("Checking maven project has a spring boot dependency");
227-
// early exit if no spring boot dependency detected
228-
if (!springBootAvailable) {
229-
return;
230-
}
231-
logger.log(INFO, "Initializing SpringBootService for project {0}", new Object[]{mvnPrj.toString()});
232-
cachedDepsPresence.clear();
233240
// set up a reference to the execute classpath object
234241
cpExec = Utils.execClasspathForProj(mvnPrj);
235242
if (cpExec != null) {
236-
// listen for pom changes
237-
logger.info("Adding maven pom listener...");
238-
mvnPrj.getProjectWatcher().addPropertyChangeListener(new PropertyChangeListener() {
239-
@Override
240-
public void propertyChange(PropertyChangeEvent evt) {
241-
final String propertyName = String.valueOf(evt.getPropertyName());
242-
logger.log(FINE, "Maven pom change ({0})", propertyName);
243-
if (propertyName.equals("MavenProject")) {
244-
refresh();
245-
}
246-
}
247-
});
248243
// populate hint providers map
249244
FileObject resourcesFolder = Utils.resourcesFolderForProj(mvnPrj);
250245
providerMap.put("logger-name", new LoggerNameHintProvider(resourcesFolder));
@@ -305,21 +300,14 @@ private void updateConfigRepo() {
305300

306301
// tell if the project currently uses Spring Boot 2.x
307302
private boolean isBoot2() {
308-
boolean flag = false;
309-
if (mvnPrj != null) {
310-
// retrieve boot version from parent pom declaration if present
311-
// TODO also look into parent hierarchy
312-
// TODO also try to look in dependency management section (inclusion of spring boot BOM)
313-
String bootVer = mvnPrj.getOriginalMavenProject().getParentArtifact().getVersion();
314-
flag = bootVer.startsWith("2");
315-
}
316-
return flag;
303+
return springBootVersion != null && springBootVersion.startsWith("2");
317304
}
318305

319306
private void adjustNbActions() {
320307
final FileObject foPrjDir = mvnPrj.getProjectDirectory();
321308
FileObject foNbAct = foPrjDir.getFileObject("nbactions.xml");
322-
if (foNbAct != null) {
309+
// only adjust nbactions.xml if necessary
310+
if (foNbAct != null && isAdjustingNeeded(foNbAct)) {
323311
logger.fine("Adjusting nbactions.xml file");
324312
try (FileLock lock = foNbAct.lock()) {
325313
try (PrintWriter pw = new PrintWriter(foPrjDir.createAndOpen("nbactions.tmp"))) {
@@ -352,4 +340,16 @@ private void adjustNbActions() {
352340
}
353341
}
354342

343+
private boolean isAdjustingNeeded(FileObject nbActions){
344+
try {
345+
String wrongPluginPropsPrefix = isBoot2() ? "<run." : "<spring-boot.run.";
346+
String wrongRestartTriggerFile = isBoot2() ? ENV_RESTART_15 : ENV_RESTART_20;
347+
return nbActions.asLines().stream()
348+
.anyMatch(line -> line.contains(wrongPluginPropsPrefix) || line.contains(wrongRestartTriggerFile));
349+
} catch (IOException ex){
350+
Exceptions.printStackTrace(ex);
351+
return false;
352+
}
353+
}
354+
355355
}

0 commit comments

Comments
 (0)