-
Notifications
You must be signed in to change notification settings - Fork 109
/
ProjectRegistryManager.java
1200 lines (1052 loc) · 50.1 KB
/
ProjectRegistryManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Copyright (c) 2008-2022 Sonatype, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Sonatype, Inc. - initial API and implementation
* Christoph Läubrich - M2Eclipse gets stuck in endless update loop
*******************************************************************************/
package org.eclipse.m2e.core.internal.project.registry;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ISaveContext;
import org.eclipse.core.resources.ISaveParticipant;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.osgi.util.NLS;
import org.codehaus.plexus.util.dag.CycleDetectedException;
import org.apache.maven.AbstractMavenLifecycleParticipant;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.MavenArtifactRepository;
import org.apache.maven.execution.DefaultMavenExecutionResult;
import org.apache.maven.execution.MavenExecutionRequest;
import org.apache.maven.execution.MavenExecutionResult;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.model.building.ModelProblem;
import org.apache.maven.model.building.ModelProblem.Severity;
import org.apache.maven.project.DuplicateProjectException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.project.ProjectBuildingRequest;
import org.apache.maven.project.ProjectSorter;
import org.eclipse.m2e.core.embedder.ArtifactKey;
import org.eclipse.m2e.core.embedder.ILocalRepositoryListener;
import org.eclipse.m2e.core.embedder.IMaven;
import org.eclipse.m2e.core.embedder.IMavenConfiguration;
import org.eclipse.m2e.core.embedder.IMavenExecutionContext;
import org.eclipse.m2e.core.internal.ExtensionReader;
import org.eclipse.m2e.core.internal.IMavenConstants;
import org.eclipse.m2e.core.internal.IMavenToolbox;
import org.eclipse.m2e.core.internal.Messages;
import org.eclipse.m2e.core.internal.URLConnectionCaches;
import org.eclipse.m2e.core.internal.embedder.MavenExecutionContext;
import org.eclipse.m2e.core.internal.embedder.MavenProperties;
import org.eclipse.m2e.core.internal.embedder.PlexusContainerManager;
import org.eclipse.m2e.core.internal.lifecyclemapping.LifecycleMappingFactory;
import org.eclipse.m2e.core.internal.lifecyclemapping.LifecycleMappingResult;
import org.eclipse.m2e.core.internal.lifecyclemapping.model.PluginExecutionMetadata;
import org.eclipse.m2e.core.internal.markers.IMavenMarkerManager;
import org.eclipse.m2e.core.internal.markers.MarkerUtils;
import org.eclipse.m2e.core.internal.project.ResolverConfigurationIO;
import org.eclipse.m2e.core.lifecyclemapping.model.IPluginExecutionMetadata;
import org.eclipse.m2e.core.project.IMavenProjectChangedListener;
import org.eclipse.m2e.core.project.IMavenProjectFacade;
import org.eclipse.m2e.core.project.IProjectConfiguration;
import org.eclipse.m2e.core.project.MavenProjectChangedEvent;
import org.eclipse.m2e.core.project.ResolverConfiguration;
import org.eclipse.m2e.core.project.configurator.ILifecycleMapping;
import org.eclipse.m2e.core.project.configurator.MojoExecutionKey;
/**
* This class keeps track of all maven projects present in the workspace and provides mapping between Maven and the
* workspace.
*/
@Component(service = ProjectRegistryManager.class)
public class ProjectRegistryManager implements ISaveParticipant {
static final Logger log = LoggerFactory.getLogger(ProjectRegistryManager.class);
static final String ARTIFACT_TYPE_POM = "pom"; //$NON-NLS-1$
static final String ARTIFACT_TYPE_JAR = "jar"; //$NON-NLS-1$
public static final String ARTIFACT_TYPE_JAVA_SOURCE = "java-source"; //$NON-NLS-1$
public static final String ARTIFACT_TYPE_JAVADOC = "javadoc"; //$NON-NLS-1$
public static final String LIFECYCLE_DEFAULT = "deploy";
public static final String LIFECYCLE_CLEAN = "clean";
public static final String LIFECYCLE_SITE = "site";
/**
* Path of project metadata files, relative to the project. These files are used to determine if project dependencies
* need to be updated.
*/
public static final List<IPath> METADATA_PATH = List.of( //
IPath.fromOSString("pom.xml"), // //$NON-NLS-1$
IPath.fromOSString(".settings/" + IMavenConstants.PLUGIN_ID + ".prefs")); // dirty trick! //$NON-NLS-1$ //$NON-NLS-2$
private ProjectRegistry projectRegistry;
@Reference
IMaven maven;
@Reference
IMavenMarkerManager markerManager;
@Reference
private IMavenConfiguration configuration;
@Reference
private PlexusContainerManager containerManager;
@Reference
private ProjectRegistryReader stateReader;
@Reference
private MavenProjectCache mavenProjectCache;
@Reference
private ILog eclipseLog;
private final Set<IMavenProjectChangedListener> projectChangeListeners = new LinkedHashSet<>();
private volatile Thread syncRefreshThread;
/**
* @noreference For tests only
*/
Consumer<Map<IMavenProjectFacade, MavenProject>> addContextProjectListener;
public ProjectRegistryManager() {
}
@Activate
void init() {
//TODO this should really happen in the background!
ProjectRegistry state;
if(configuration.isUpdateProjectsOnStartup()) {
state = null;
} else {
state = stateReader.readWorkspaceState(this);
}
this.projectRegistry = (state != null && state.isValid()) ? state : new ProjectRegistry();
}
/**
* Creates or returns cached MavenProjectFacade for the given project. This method will not block if called from
* IMavenProjectChangedListener#mavenProjectChanged
*/
public MavenProjectFacade create(IProject project, IProgressMonitor monitor) {
return create(getPom(project), false, monitor);
}
/**
* Returns MavenProjectFacade corresponding to the pom. This method first looks in the project cache, then attempts to
* load the pom if the pom is not found in the cache. In the latter case, workspace resolution is assumed to be
* enabled for the pom but the pom will not be added to the cache.
*/
public MavenProjectFacade create(IFile pom, boolean load, IProgressMonitor monitor) {
if(pom == null) {
return null;
}
MavenProjectFacade projectFacade = projectRegistry.getProjectFacade(pom);
if(projectFacade == null && load) {
IProjectConfiguration config = ResolverConfigurationIO.readResolverConfiguration(pom.getProject());
MavenExecutionResult executionResult = readProjectsWithDependencies(pom, config, monitor).iterator().next();
MavenProject mavenProject = executionResult.getProject();
if(mavenProject != null && mavenProject.getArtifact() != null) {
projectFacade = new MavenProjectFacade(this, pom, mavenProject, config);
} else {
List<Throwable> exceptions = executionResult.getExceptions();
if(exceptions != null) {
for(Throwable ex : exceptions) {
log.error("Failed to read Maven project: " + ex.getMessage(), ex);
}
}
}
}
return projectFacade;
}
IFile getPom(IProject project) {
if(project == null || !project.isAccessible()) {
// XXX sensible handling
return null;
}
IPath location = project.getLocation();
if(location == null) {
return project.getFile(IMavenConstants.POM_FILE_NAME);
}
File baseDir = location.toFile();
Optional<File> pom = IMavenToolbox.of(containerManager.getComponentLookup(baseDir)).locatePom(baseDir);
return pom.map(pomFile -> {
IFile file = project.getFile(pomFile.getName());
try {
//the file might be created by the locate call so make sure we refresh it here...
file.refreshLocal(IResource.DEPTH_ZERO, null);
} catch(CoreException ex) {
//if this does not work, there might be an error, but this is not handled here...
}
return file;
}).orElse(null);
}
/**
* Removes specified poms from the cache. Adds dependent poms to pomSet but does not directly refresh dependent poms.
* Recursively removes all nested modules if appropriate.
*
* @return a {@link Set} of {@link IFile} affected poms
*/
public Set<IFile> remove(MutableProjectRegistry state, Set<IFile> poms, boolean force) {
Set<IFile> pomSet = new LinkedHashSet<>();
for(IFile pom : poms) {
MavenProjectFacade facade = state.getProjectFacade(pom);
if(force || facade == null || facade.isStale()) {
pomSet.addAll(remove(state, pom));
}
}
return pomSet;
}
/**
* Removes the pom from the cache. Adds dependent poms to pomSet but does not directly refresh dependent poms.
* Recursively removes all nested modules if appropriate.
*
* @return a {@link Set} of {@link IFile} affected poms
*/
public Set<IFile> remove(MutableProjectRegistry state, IFile pom) {
MavenProjectFacade facade = state.getProjectFacade(pom);
ArtifactKey mavenProject = facade != null ? facade.getArtifactKey() : null;
flushCaches(facade, false);
if(mavenProject == null) {
state.removeProject(pom, null);
return Collections.emptySet();
}
Set<IFile> pomSet = new LinkedHashSet<>();
pomSet.addAll(state.getDependents(MavenCapability.createMavenArtifact(mavenProject), false));
pomSet.addAll(state.getDependents(MavenCapability.createMavenParent(mavenProject), false)); // TODO check packaging
state.removeProject(pom, mavenProject);
pomSet.addAll(refreshWorkspaceModules(state, mavenProject));
pomSet.remove(pom);
return pomSet;
}
private boolean isForceDependencyUpdate() throws CoreException {
IMavenExecutionContext context = MavenExecutionContext.getThreadContext();
return context != null && context.getExecutionRequest().isUpdateSnapshots();
}
/**
* This method acquires workspace root's lock and sends project change events. It is meant for synchronous registry
* updates.
*
* @since 1.4
*/
public Map<IFile, IStatus> refresh(Collection<IFile> pomFiles, IProgressMonitor monitor) throws CoreException {
SubMonitor progress = SubMonitor.convert(monitor, Messages.ProjectRegistryManager_task_refreshing, 100);
ISchedulingRule rule = ResourcesPlugin.getWorkspace().getRoot();
Job.getJobManager().beginRule(rule, progress);
syncRefreshThread = Thread.currentThread();
try (MutableProjectRegistry newState = newMutableProjectRegistry()) {
Map<IFile, IStatus> result = refresh(newState, pomFiles, progress.newChild(95));
applyMutableProjectRegistry(newState, progress.newChild(5));
return result;
} finally {
syncRefreshThread = null;
Job.getJobManager().endRule(rule);
}
}
Map<IFile, IStatus> refresh(MutableProjectRegistry newState, Collection<IFile> pomFiles, IProgressMonitor monitor)
throws CoreException {
long start = System.currentTimeMillis();
log.debug("Refreshing ({} files): {}", pomFiles.size(), pomFiles); //$NON-NLS-1$
// 442524 safety guard
URLConnectionCaches.assertDisabled();
DependencyResolutionContext context = new DependencyResolutionContext(pomFiles);
// safety net -- do not force refresh of the same installed/resolved artifact more than once
Set<ArtifactKey> installedArtifacts = new HashSet<>();
ILocalRepositoryListener listener = (repositoryBasedir, baseArtifact, artifact, artifactFile) -> {
if(artifactFile == null) {
// resolution error
return;
}
// TODO remove=false?
Set<IFile> refresh = new LinkedHashSet<>();
if(installedArtifacts.add(artifact)) {
refresh.addAll(newState.getVersionedDependents(MavenCapability.createMavenParent(artifact), true));
refresh.addAll(newState.getVersionedDependents(MavenCapability.createMavenArtifact(artifact), true));
refresh.addAll(newState.getVersionedDependents(MavenCapability.createMavenArtifactImport(artifact), true));
}
if(installedArtifacts.add(baseArtifact)) {
refresh.addAll(newState.getVersionedDependents(MavenCapability.createMavenParent(baseArtifact), true));
refresh.addAll(newState.getVersionedDependents(MavenCapability.createMavenArtifact(baseArtifact), true));
refresh.addAll(newState.getVersionedDependents(MavenCapability.createMavenArtifactImport(baseArtifact), true));
}
if(!refresh.isEmpty()) {
log.debug("Automatic refresh. artifact={}/{}. projects={}", baseArtifact, artifact, refresh);
context.forcePomFiles(refresh);
}
};
maven.addLocalRepositoryListener(listener);
try {
refresh(newState, context, monitor);
Map<IFile, IStatus> statusResult = new ConcurrentHashMap<>();
for(IFile file : pomFiles) {
statusResult.put(file, context.getStatus(file));
}
return statusResult;
} finally {
maven.removeLocalRepositoryListener(listener);
log.debug("Refresh takes {} ms", (System.currentTimeMillis() - start)); //$NON-NLS-1$
}
}
private void refresh(MutableProjectRegistry newState, DependencyResolutionContext context, IProgressMonitor monitor)
throws CoreException {
Set<IFile> allProcessedPoms = new LinkedHashSet<>();
Set<IFile> allNewFacades = new HashSet<>();
Map<IFile, Set<Capability>> originalCapabilities = new HashMap<>();
Map<IFile, Set<RequiredCapability>> originalRequirements = new HashMap<>();
// phase 1: build projects without dependencies and populate workspace with known projects
while(!context.isEmpty()) { // context may be augmented, so we need to keep processing
List<IFile> pomsForUpdate = calculateFacadesForUpdate(newState, context, allProcessedPoms::add,
allNewFacades::contains, monitor);
context.clearErrors(pomsForUpdate);
Map<IFile, MavenProjectFacade> newFacades = readMavenProjectFacades(pomsForUpdate, newState, context, monitor);
for(Entry<IFile, MavenProjectFacade> entry : newFacades.entrySet()) {
IFile pom = entry.getKey();
MavenProjectFacade newFacade = entry.getValue();
newState.setProject(pom, newFacade);
if(newFacade != null) {
// refresh new child modules
MavenCapability mavenParentCapability = MavenCapability.createMavenParent(newFacade.getArtifactKey());
for(IFile file : newState.getVersionedDependents(mavenParentCapability, true)) {
if(!newFacades.containsKey(file)) {
context.forcePomFile(file);
}
}
// refresh projects that import dependencyManagement from this one
MavenCapability mavenArtifactImportCapability = MavenCapability
.createMavenArtifactImport(newFacade.getArtifactKey());
for(IFile file : newState.getVersionedDependents(mavenArtifactImportCapability, true)) {
if(!newFacades.containsKey(file)) {
context.forcePomFile(file);
}
}
Set<Capability> capabilities = new LinkedHashSet<>();
capabilities.add(mavenParentCapability);
capabilities.add(MavenCapability.createMavenArtifact(newFacade.getArtifactKey()));
Set<Capability> oldCapabilities = newState.setCapabilities(pom, capabilities);
originalCapabilities.putIfAbsent(pom, oldCapabilities);
MavenProject mavenProject = getMavenProject(newFacade);
Set<RequiredCapability> requirements = new LinkedHashSet<>();
DefaultMavenDependencyResolver.addProjectStructureRequirements(requirements, mavenProject);
Set<RequiredCapability> oldRequirements = newState.setRequirements(pom, requirements);
originalRequirements.putIfAbsent(pom, oldRequirements);
}
}
allNewFacades.addAll(newFacades.keySet());
List<IFile> erroneousPoms = new ArrayList<>(pomsForUpdate);
erroneousPoms.removeAll(newFacades.keySet());
erroneousPoms.forEach(pom -> newState.setProject(pom, null));
if(!newFacades.isEmpty()) { // progress did happen
// push files that could't be read back into context for a second pass.
// This can help if some read files are parent of other ones in the same
// request -> the child wouldn't be read immediately, but would be in a
// 2nd pass once parent was read.
HashSet<IFile> pomFiles = new HashSet<>(erroneousPoms);
context.forcePomFiles(pomFiles);
}
}
context.forcePomFiles(allProcessedPoms);
// phase 2: resolve project dependencies
ProjectProcessingTracker tracker = new ProjectProcessingTracker(context);
do {
while(!context.isEmpty()) {
if(monitor.isCanceled()) {
throw new OperationCanceledException();
}
if(newState.isStale() || (syncRefreshThread != null && syncRefreshThread != Thread.currentThread())) {
throw new StaleMutableProjectRegistryException();
}
IFile pom = context.pop();
if(tracker.shouldProcess(pom)) {
MavenProjectFacade newFacade = null;
if(pom.isAccessible() && pom.getProject().hasNature(IMavenConstants.NATURE_ID)) {
newFacade = newState.getProjectFacade(pom);
}
if(newFacade != null) {
MavenProject mavenProject = getMavenProject(newFacade);
if(!allProcessedPoms.contains(newFacade.getPom())) {
// facade from workspace state that has not been refreshed yet
newFacade = readMavenProjectFacades(Collections.singletonList(pom), newState, context, monitor).get(pom);
} else {
// recreate facade instance to trigger project changed event
// this is only necessary for facades that are refreshed because their dependencies changed
// but this is relatively cheap, so all facades are recreated here
putMavenProject(newFacade, null);
newFacade = new MavenProjectFacade(newFacade);
putMavenProject(newFacade, mavenProject);
}
mavenProjectCache.updateMavenProject(newFacade, mavenProject);
}
if(newFacade != null) {
MavenProjectFacade facade = newFacade;
IProjectConfiguration resolverConfiguration = facade.getConfiguration();
createExecutionContext(newState, pom, resolverConfiguration).execute(getMavenProject(newFacade),
(executionContext, pm) -> {
refreshPhase2(newState, context, originalCapabilities, originalRequirements, pom, facade, pm);
return null;
}, monitor);
} else {
refreshPhase2(newState, context, originalCapabilities, originalRequirements, pom, newFacade, monitor);
}
monitor.worked(1);
}
}
} while(tracker.needsImprovement());
}
private List<IFile> calculateFacadesForUpdate(MutableProjectRegistry registry, DependencyResolutionContext context,
Consumer<IFile> processingListener, Predicate<IFile> alreadyProcessed, IProgressMonitor monitor)
throws CoreException {
List<IFile> toReadPomFiles = new ArrayList<>();
while(!context.isEmpty()) { // Group build of all current context
if(monitor.isCanceled()) {
throw new OperationCanceledException();
}
if(registry.isStale() || (syncRefreshThread != null && syncRefreshThread != Thread.currentThread())) {
throw new StaleMutableProjectRegistryException();
}
IFile pom = context.pop();
if(alreadyProcessed.test(pom)) {
// pom was already in context and successfully read
continue;
}
processingListener.accept(pom);
monitor.subTask(NLS.bind(Messages.ProjectRegistryManager_task_project, pom.getProject().getName()));
MavenProjectFacade oldFacade = registry.getProjectFacade(pom);
context.forcePomFiles(flushCaches(oldFacade, isForceDependencyUpdate()));
if(oldFacade != null) {
putMavenProject(oldFacade, null); // maintain maven project cache
}
if(pom.isAccessible() && pom.getProject().hasNature(IMavenConstants.NATURE_ID)) {
toReadPomFiles.add(pom);
if(oldFacade != null) {
// refresh old child modules
MavenCapability mavenParentCapability = MavenCapability.createMavenParent(oldFacade.getArtifactKey());
context.forcePomFiles(registry.getVersionedDependents(mavenParentCapability, true));
// refresh projects that import dependencyManagement from this one
MavenCapability mavenArtifactImportCapability = MavenCapability
.createMavenArtifactImport(oldFacade.getArtifactKey());
context.forcePomFiles(registry.getVersionedDependents(mavenArtifactImportCapability, true));
}
} else {
registry.setProject(pom, null); // discard closed/deleted pom in workspace
// refresh children of deleted/closed parent
if(oldFacade != null) {
MavenCapability mavenParentCapability = MavenCapability.createMavenParent(oldFacade.getArtifactKey());
context.forcePomFiles(registry.getDependents(mavenParentCapability, true));
MavenCapability mavenArtifactImportCapability = MavenCapability
.createMavenArtifactImport(oldFacade.getArtifactKey());
context.forcePomFiles(registry.getVersionedDependents(mavenArtifactImportCapability, true));
}
}
}
return toReadPomFiles;
}
void refreshPhase2(MutableProjectRegistry newState, DependencyResolutionContext context,
Map<IFile, Set<Capability>> originalCapabilities, Map<IFile, Set<RequiredCapability>> originalRequirements,
IFile pom, MavenProjectFacade newFacade, IProgressMonitor monitor) throws CoreException {
Set<Capability> capabilities = null;
Set<RequiredCapability> requirements = null;
if(newFacade != null) {
monitor.subTask(NLS.bind(Messages.ProjectRegistryManager_task_project, newFacade.getProject().getName()));
setupLifecycleMapping(monitor, newFacade);
capabilities = new LinkedHashSet<>();
requirements = new LinkedHashSet<>();
Capability mavenParentCapability = MavenCapability.createMavenParent(newFacade.getArtifactKey());
// maven projects always have these capabilities
capabilities.add(MavenCapability.createMavenArtifact(newFacade.getArtifactKey()));
capabilities.add(mavenParentCapability); // TODO consider packaging
// maven projects always have these requirements
DefaultMavenDependencyResolver.addProjectStructureRequirements(requirements, getMavenProject(newFacade));
AbstractMavenDependencyResolver resolver = getMavenDependencyResolver(newFacade, monitor);
resolver.setContextProjectRegistry(newState);
try {
resolver.resolveProjectDependencies(newFacade, capabilities, requirements, monitor);
} finally {
resolver.setContextProjectRegistry(null);
}
newState.setProject(pom, newFacade);
newFacade.setMavenProjectArtifacts(getMavenProject(newFacade));
} else {
if(pom.isAccessible() && pom.getProject().hasNature(IMavenConstants.NATURE_ID)) {
try (InputStream is = pom.getContents()) {
// MNGECLIPSE-605 embedder is not able to resolve the project due to missing configuration in the parent
Model model = IMavenToolbox.of(maven).readModel(is);
if(model != null && model.getParent() != null) {
Parent parent = model.getParent();
if(parent.getGroupId() != null && parent.getArtifactId() != null && parent.getVersion() != null) {
ArtifactKey parentKey = new ArtifactKey(parent.getGroupId(), parent.getArtifactId(), parent.getVersion(),
null);
requirements = new HashSet<>();
requirements.add(MavenRequiredCapability.createMavenParent(parentKey));
}
}
} catch(Exception e) {
// we've tried our best, there is nothing else we can do
log.error(e.getMessage(), e);
}
}
}
Set<Capability> oldCapabilities = newState.setCapabilities(pom, capabilities);
if(originalCapabilities.containsKey(pom)) {
oldCapabilities = originalCapabilities.get(pom);
}
// if our capabilities changed, recalculate everyone who depends on new/changed/removed capabilities
Set<Capability> changedCapabilities = diff(oldCapabilities, capabilities);
// refresh versioned dependents if only parent capability has changed
boolean versionedCapabilitiesOnly = true;
for(Capability capability : changedCapabilities) {
if(MavenCapability.NS_MAVEN_ARTIFACT.equals(capability.getVersionlessKey().namespace())) {
versionedCapabilitiesOnly = false;
break;
}
}
for(Capability capability : changedCapabilities) {
context.forcePomFiles(versionedCapabilitiesOnly ? newState.getVersionedDependents(capability, true)
: newState.getDependents(capability, true));
}
Set<RequiredCapability> oldRequirements = newState.setRequirements(pom, requirements);
if(originalRequirements.containsKey(pom)) {
oldRequirements = originalRequirements.get(pom);
}
// if our dependencies changed, recalculate everyone who depends on us
// this is needed to deal with transitive dependency resolution in maven
if(oldCapabilities != null && hasDiff(oldRequirements, requirements)) {
for(Capability capability : oldCapabilities) {
context.forcePomFiles(newState.getVersionedDependents(capability, true));
}
}
}
private void setupLifecycleMapping(IProgressMonitor monitor, MavenProjectFacade newFacade) throws CoreException {
LifecycleMappingResult mappingResult = LifecycleMappingFactory.calculateLifecycleMapping(getMavenProject(newFacade),
newFacade.getMojoExecutions(), newFacade.getConfiguration().getLifecycleMappingId(), monitor);
newFacade.setLifecycleMappingId(mappingResult.getLifecycleMappingId());
Map<MojoExecutionKey, List<IPluginExecutionMetadata>> mojoExecutionMapping = mappingResult
.getMojoExecutionMapping();
if(mojoExecutionMapping != null) {
detachMappingSources(mojoExecutionMapping);
}
newFacade.setMojoExecutionMapping(mojoExecutionMapping);
// XXX reconcile with corresponding LifecycleMappingFactory methods
newFacade.setSessionProperty(MavenProjectFacade.PROP_LIFECYCLE_MAPPING, mappingResult.getLifecycleMapping());
LifecycleMappingFactory.setProjectConfigurators(newFacade, mappingResult);
markerManager.deleteMarkers(newFacade.getPom(), IMavenConstants.MARKER_LIFECYCLEMAPPING_ID);
if(mappingResult.hasProblems()) {
markerManager.addErrorMarkers(newFacade.getPom(), IMavenConstants.MARKER_LIFECYCLEMAPPING_ID,
mappingResult.getProblems());
}
}
private void detachMappingSources(Map<MojoExecutionKey, List<IPluginExecutionMetadata>> mapping) {
for(List<IPluginExecutionMetadata> executions : mapping.values()) {
if(executions != null) {
ListIterator<IPluginExecutionMetadata> iterator = executions.listIterator();
while(iterator.hasNext()) {
IPluginExecutionMetadata metadata = iterator.next();
if(metadata instanceof PluginExecutionMetadata execution) {
execution = execution.clone();
execution.setSource(null);
iterator.set(execution);
}
}
}
}
}
private static <T> Set<T> diff(Set<T> a, Set<T> b) {
if(a == null || a.isEmpty()) {
if(b == null || b.isEmpty()) {
return Collections.emptySet();
}
return b;
}
if(b == null || b.isEmpty()) {
return a;
}
Map<T, Long> m = Stream.concat(a.stream(), b.stream())
.collect(Collectors.groupingBy(e -> e, Collectors.counting()));
m.values().removeIf(c -> c > 1);
return m.keySet();
}
static <T> boolean hasDiff(Set<T> a, Set<T> b) {
if(a == null || a.isEmpty()) {
return b != null && !b.isEmpty();
}
if(b == null || b.isEmpty()) {
return true;
}
if(a.size() != b.size()) {
return true;
}
Iterator<T> oldIter = a.iterator();
Iterator<T> iter = b.iterator();
while(oldIter.hasNext()) {
T oldRequirement = oldIter.next();
T requirement = iter.next();
if(!oldRequirement.equals(requirement)) {
return true;
}
}
return false;
}
private AbstractMavenDependencyResolver getMavenDependencyResolver(MavenProjectFacade newFacade,
IProgressMonitor monitor) {
ILifecycleMapping lifecycleMapping = LifecycleMappingFactory.getLifecycleMapping(newFacade);
if(lifecycleMapping instanceof ILifecycleMapping2 lifecycleMapping2) {
AbstractMavenDependencyResolver resolver = lifecycleMapping2.getDependencyResolver(monitor);
resolver.setManager(this);
return resolver;
}
return new DefaultMavenDependencyResolver(this, markerManager);
}
private Map<IFile, MavenProjectFacade> readMavenProjectFacades(Collection<IFile> poms, MutableProjectRegistry state,
DependencyResolutionContext resolutionContext, IProgressMonitor monitor) throws CoreException {
if(poms.isEmpty()) {
return Collections.emptyMap();
}
SubMonitor subMonitor = SubMonitor.convert(monitor, poms.size());
for(IFile pom : poms) {
markerManager.deleteMarkers(pom, IMavenConstants.MARKER_POM_LOADING_ID);
}
Map<IFile, IProjectConfiguration> resolverConfigurations = new HashMap<>(poms.size(), 1.f);
Map<IProjectConfiguration, Collection<IFile>> groupsToImport = poms.stream().collect(Collectors.groupingBy(pom -> {
subMonitor.checkCanceled();
IProjectConfiguration resolverConfiguration = ResolverConfigurationIO.readResolverConfiguration(pom.getProject());
resolverConfigurations.put(pom, resolverConfiguration);
return resolverConfiguration;
}, LinkedHashMap::new, Collectors.toCollection(LinkedHashSet::new)));
Map<IFile, MavenProjectFacade> result = new LinkedHashMap<>(poms.size(), 1.f);
for(Entry<IProjectConfiguration, Collection<IFile>> entry : groupsToImport.entrySet()) {
IProjectConfiguration resolverConfiguration = entry.getKey();
Collection<IFile> fileList = entry.getValue();
File moduleProjectDirectory = resolverConfiguration.getMultiModuleProjectDirectory();
MavenExecutionContext context = new MavenExecutionContext(
containerManager.getComponentLookup(moduleProjectDirectory), moduleProjectDirectory, moduleProjectDirectory,
null);
configureExecutionRequest(context.getExecutionRequest(), state,
fileList.size() == 1 ? fileList.iterator().next() : null, resolverConfiguration);
try {
context.execute((ctx, mon) -> {
Map<IFile, File> pomFiles = fileList.stream().filter(IFile::isAccessible)
.collect(Collectors.toMap(Function.identity(), ProjectRegistryManager::toJavaIoFile));
ProjectBuildingRequest buildingRequest = ctx.newProjectBuildingRequest();
Map<File, MavenExecutionResult> mavenResults = IMavenToolbox.of(ctx).readMavenProjects(pomFiles.values(),
buildingRequest);
Map<IFile, MavenProjectFacade> facades = new HashMap<>(mavenResults.size(), 1.f);
Map<MavenProject, MavenProjectFacade> facadeMap = new HashMap<>();
for(var fileEntry : pomFiles.entrySet()) {
IFile pom = fileEntry.getKey();
File file = fileEntry.getValue();
if(!pom.isAccessible()) {
continue;
}
MavenExecutionResult mavenResult = mavenResults.get(file);
MavenProject mavenProject = mavenResult.getProject();
MarkerUtils.addEditorHintMarkers(markerManager, pom, mavenProject, IMavenConstants.MARKER_POM_LOADING_ID);
markerManager.addMarkers(pom, IMavenConstants.MARKER_POM_LOADING_ID, mavenResult);
if(mavenProject != null && mavenProject.getArtifact() != null) {
MavenProjectFacade mavenProjectFacade = new MavenProjectFacade(ProjectRegistryManager.this, pom,
mavenProject, resolverConfiguration);
putMavenProject(mavenProjectFacade, mavenProject); // maintain maven project cache
facadeMap.put(mavenProject, mavenProjectFacade);
}
}
Set<AbstractMavenLifecycleParticipant> executed = new HashSet<>();
List<MavenProject> projects = facadeMap.keySet().stream().toList();
executeParticipants(ctx, projects, executed, buildingRequest);
facadeMap.values().forEach(facade -> {
try {
facade.createExecutionContext().execute((projectContext, y) -> {
executeParticipants(projectContext, projects, executed, buildingRequest);
return null;
}, null);
} catch(CoreException ex) {
}
});
for(var mp : getSortedProjects(facadeMap.keySet())) {
MavenProjectFacade facade = facadeMap.get(mp);
result.put(facade.getPom(), facade);
}
return facades;
}, subMonitor.split(1));
} catch(CoreException e) {
for(IFile file : fileList) {
resolutionContext.setStatus(file, e.getStatus());
}
}
}
return result;
}
private void executeParticipants(IMavenExecutionContext ctx, List<MavenProject> projects,
Set<AbstractMavenLifecycleParticipant> executed, ProjectBuildingRequest buildingRequest) throws CoreException {
Collection<AbstractMavenLifecycleParticipant> participants = ctx.getComponentLookup()
.lookupCollection(AbstractMavenLifecycleParticipant.class);
for(AbstractMavenLifecycleParticipant participant : participants) {
if(executed.add(participant)) {
MavenSession session = ctx.getSession();
MavenSession clone = session.clone();
clone.setProjects(projects);
//FIXME without this call there are sometime NPE see https://github.com/eclipse-m2e/m2e-core/issues/118#issuecomment-1607118196
clone.getProjectBuildingRequest();
try {
participant.afterProjectsRead(clone);
} catch(Exception ex) {
eclipseLog.error(
"Executing AbstractMavenLifecycleParticipant " + participant.getClass().getName() + " failed",
ex);
}
}
}
}
private Collection<MavenProject> getSortedProjects(Collection<MavenProject> projects) {
if(projects.size() <= 1) {
return projects;
}
try {
//sort project according to their declared dependencies...
ProjectSorter sorter = new ProjectSorter(projects);
return sorter.getSortedProjects();
} catch(CycleDetectedException | DuplicateProjectException ex) {
return projects;
}
}
/**
* @return Returns the markerManager.
*/
IMavenMarkerManager getMarkerManager() {
return this.markerManager;
}
public IFile getModulePom(IFile pom, String moduleName) {
return pom.getParent().getFile(IPath.fromOSString(moduleName).append(IMavenConstants.POM_FILE_NAME));
}
private Set<IFile> refreshWorkspaceModules(MutableProjectRegistry state, ArtifactKey mavenProject) {
if(mavenProject == null) {
return Collections.emptySet();
}
return state.removeWorkspaceModules(mavenProject);
}
@Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC)
public void addMavenProjectChangedListener(IMavenProjectChangedListener listener) {
synchronized(projectChangeListeners) {
projectChangeListeners.add(listener);
}
}
public void removeMavenProjectChangedListener(IMavenProjectChangedListener listener) {
if(listener != null) {
synchronized(projectChangeListeners) {
projectChangeListeners.remove(listener);
}
}
}
public void notifyProjectChangeListeners(List<MavenProjectChangedEvent> events, IProgressMonitor monitor) {
if(!events.isEmpty()) {
List<IMavenProjectChangedListener> listeners = new ArrayList<>();
synchronized(this.projectChangeListeners) {
listeners.addAll(this.projectChangeListeners);
}
listeners.addAll(ExtensionReader.readProjectChangedEventListenerExtentions());
for(IMavenProjectChangedListener listener : listeners) {
listener.mavenProjectChanged(events, monitor);
}
}
}
public MavenProjectFacade getMavenProject(String groupId, String artifactId, String version) {
return projectRegistry.getProjectFacade(groupId, artifactId, version);
}
private MavenProject readProjectWithDependencies(IMavenProjectFacade facade) {
IFile pomFile = facade.getPom();
IProjectConfiguration resolverConfiguration = facade.getConfiguration();
Collection<MavenExecutionResult> results = readProjectsWithDependencies(pomFile, resolverConfiguration, null);
if(results.size() != 1) {
throw new IllegalStateException("Results should contain one entry.");
}
MavenExecutionResult result = results.iterator().next();
MavenProject mavenProject = result.getProject();
if(mavenProject != null && !hasError(result)) {
return mavenProject;
}
MultiStatus status = new MultiStatus(IMavenConstants.PLUGIN_ID, 0, Messages.MavenProjectFacade_error);
for(Throwable e : result.getExceptions()) {
status.add(Status.error(e.getMessage(), e));
}
throw new IllegalStateException(new CoreException(status).fillInStackTrace());
}
private static boolean hasError(MavenExecutionResult mavenExecutionResult) {
return mavenExecutionResult.getExceptions().stream().anyMatch(ex -> !(ex instanceof ProjectBuildingException))
|| mavenExecutionResult.getExceptions().stream()//
.map(ProjectBuildingException.class::cast)//
.flatMap(ex -> ex.getResults().stream())//
.flatMap(result -> result.getProblems().stream())//
.map(ModelProblem::getSeverity)//
.anyMatch(severity -> severity != Severity.WARNING);
}
private Collection<MavenExecutionResult> readProjectsWithDependencies(IFile pomFile,
IProjectConfiguration resolverConfiguration, IProgressMonitor monitor) {
try {
Map<File, MavenExecutionResult> resultMap = Map.of();
File multiModuleProjectDirectory = resolverConfiguration.getMultiModuleProjectDirectory();
MavenExecutionContext context = new MavenExecutionContext(
containerManager.getComponentLookup(multiModuleProjectDirectory), pomFile.getLocation().toFile(),
multiModuleProjectDirectory, null);
configureExecutionRequest(context.getExecutionRequest(), projectRegistry, pomFile, resolverConfiguration);
resultMap = context.execute((ctx, mon) -> {
ProjectBuildingRequest request = context.newProjectBuildingRequest();
request.setResolveDependencies(true);
List<File> pomFiles = Stream.of(toJavaIoFile(pomFile)).filter(Objects::nonNull).toList();
return IMavenToolbox.of(ctx).readMavenProjects(pomFiles, request);
}, monitor);
return resultMap.values();
} catch(CoreException ex) {
return List.of(new DefaultMavenExecutionResult().addException(ex));
}
}
public List<MavenProjectFacade> getProjects() {
return projectRegistry.getProjects();
}
public IMavenProjectFacade getProject(IProject project) {
return projectRegistry.getProjectFacade(getPom(project));
}
/**
* Context
*/
static class Context {
final IProjectRegistry state;
final IProjectConfiguration resolverConfiguration;
final IFile pom;
Context(IProjectRegistry state, IProjectConfiguration resolverConfiguration, IFile pom) {
this.state = state;
this.resolverConfiguration = resolverConfiguration;
this.pom = pom;
}
}
private MavenExecutionRequest configureExecutionRequest(MavenExecutionRequest request, IProjectRegistry state,
IFile pom, IProjectConfiguration resolverConfiguration) throws CoreException {
if(pom != null) {
request.setPom(ProjectRegistryManager.toJavaIoFile(pom));
}
request.addActiveProfiles(resolverConfiguration.getActiveProfileList());
request.addInactiveProfiles(resolverConfiguration.getInactiveProfileList());
Properties userProperties = request.getUserProperties();
//User properties (from maven.config or alike) first
userProperties.putAll(resolverConfiguration.getUserProperties());
//then use explicit project configuration to overrule anything else...
Map<String, String> addProperties = resolverConfiguration.getConfigurationProperties();
if(addProperties != null && !addProperties.isEmpty()) {
userProperties.putAll(addProperties);
}
// eclipse workspace repository implements both workspace dependency resolution
// and inter-module dependency resolution for multi-module projects.
request.setWorkspaceReader(getWorkspaceReader(state, pom, resolverConfiguration));
if(pom != null && pom.getLocation() != null) {
request.setMultiModuleProjectDirectory(
MavenProperties.computeMultiModuleProjectDirectory(pom.getLocation().toFile()));
}