Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 33d1134563a63828e4a34d167326e0eefac39ba5 (plain) (blame)
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
/*******************************************************************************
 * Copyright (c) 2011 Sonatype, 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
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *      Sonatype, Inc. - initial API and implementation
 *******************************************************************************/

package org.eclipse.m2e.refactoring.exclude;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.graph.DependencyNode;
import org.eclipse.aether.graph.DependencyVisitor;
import org.eclipse.aether.util.artifact.JavaScopes;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
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.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.CompositeChange;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.osgi.util.NLS;

import org.apache.maven.model.Dependency;
import org.apache.maven.model.Exclusion;
import org.apache.maven.project.MavenProject;

import org.eclipse.m2e.core.MavenPlugin;
import org.eclipse.m2e.core.embedder.ArtifactKey;
import org.eclipse.m2e.core.embedder.ICallable;
import org.eclipse.m2e.core.embedder.IMavenExecutionContext;
import org.eclipse.m2e.core.project.IMavenProjectFacade;
import org.eclipse.m2e.core.ui.internal.editing.AddDependencyOperation;
import org.eclipse.m2e.core.ui.internal.editing.AddExclusionOperation;
import org.eclipse.m2e.core.ui.internal.editing.PomEdits.CompoundOperation;
import org.eclipse.m2e.core.ui.internal.editing.PomEdits.Operation;
import org.eclipse.m2e.core.ui.internal.editing.PomHelper;
import org.eclipse.m2e.core.ui.internal.editing.RemoveDependencyOperation;
import org.eclipse.m2e.core.ui.internal.util.ParentHierarchyEntry;
import org.eclipse.m2e.refactoring.Messages;


@SuppressWarnings("restriction")
public class ExcludeArtifactRefactoring extends Refactoring {
  private static final String PLUGIN_ID = "org.eclipse.m2e.refactoring"; //$NON-NLS-1$

  /**
   * Dependencies to exclude
   */
  final ArtifactKey[] excludes;

//  private IFile pomFile;

  /**
   * Workspace Model to exclude dependencies from
   */
  private ParentHierarchyEntry exclusionPoint;

  private List<ParentHierarchyEntry> hierarchy;

  public ExcludeArtifactRefactoring(ArtifactKey[] keys) {
    this.excludes = keys;
  }

  public void setExclusionPoint(ParentHierarchyEntry exclusionPoint) {
    this.exclusionPoint = exclusionPoint;
  }

  public void setHierarchy(List<ParentHierarchyEntry> hierarchy) {
    this.hierarchy = hierarchy;
    this.exclusionPoint = hierarchy != null ? hierarchy.get(0) : null;
  }

  @Override
  public String getName() {
    StringBuilder sb = new StringBuilder();
    for(ArtifactKey key : excludes) {
      sb.append(key.toString()).append(',');
    }
    sb.deleteCharAt(sb.length() - 1);
    return NLS.bind(Messages.MavenExcludeWizard_title, sb.toString());
  }

  @Override
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws OperationCanceledException {
    return new RefactoringStatus();
  }

  private List<Change> changes;

  @Override
  public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException {
    return MavenPlugin.getMaven().execute(new ICallable<RefactoringStatus>() {
      public RefactoringStatus call(IMavenExecutionContext context, IProgressMonitor monitor) throws CoreException {
        return checkFinalConditions0(monitor);
      }
    }, pm);
  }

  RefactoringStatus checkFinalConditions0(IProgressMonitor pm) throws CoreException, OperationCanceledException {
    if(hierarchy == null || exclusionPoint == null) {
      return RefactoringStatus.createFatalErrorStatus(Messages.ExcludeArtifactRefactoring_unableToLocateProject);
    }

    changes = new ArrayList<Change>();
    Set<ArtifactKey> locatedKeys = new HashSet<ArtifactKey>();
    List<IStatus> statuses = new ArrayList<IStatus>();
    SubMonitor monitor = SubMonitor.convert(pm, 3);

    List<Operation> exclusionOp = new ArrayList<Operation>();
    // Exclusion point
    for(Entry<Dependency, Set<ArtifactKey>> entry : getDependencyExcludes(exclusionPoint, monitor.newChild(1))
        .entrySet()) {
      locatedKeys.addAll(entry.getValue());
      Dependency dependency = entry.getKey();
      if(contains(entry.getValue(), dependency)) {
        exclusionOp.add(new RemoveDependencyOperation(dependency));
      } else {
        for(ArtifactKey key : entry.getValue()) {
          if(!hasExclusion(exclusionPoint, dependency, key)) {
            exclusionOp.add(new AddExclusionOperation(dependency, key));
          }
        }
      }
    }

    // Below exclusion point - pull up dependency to exclusion point
    for(ParentHierarchyEntry project : getWorkspaceDescendants()) {
      List<Operation> operations = new ArrayList<Operation>();
      for(Entry<Dependency, Set<ArtifactKey>> entry : getDependencyExcludes(project, monitor.newChild(1)).entrySet()) {
        locatedKeys.addAll(entry.getValue());
        Dependency dependency = entry.getKey();
        operations.add(new RemoveDependencyOperation(dependency));
        if(!contains(entry.getValue(), dependency)) {
          if(!hasDependency(exclusionPoint, dependency)) {
            exclusionOp.add(new AddDependencyOperation(dependency));
          }
          for(ArtifactKey key : entry.getValue()) {
            if(!hasExclusion(exclusionPoint, dependency, key)) {
              exclusionOp.add(new AddExclusionOperation(dependency, key));
            }
          }
        }
      }
      if(operations.size() > 0) {
        IFile pom = project.getResource();
        changes.add(PomHelper.createChange(pom,
            new CompoundOperation(operations.toArray(new Operation[operations.size()])), getName(pom)));
      }
    }

    // Above exclusion - Add dep to exclusionPoint
    for(ParentHierarchyEntry project : getWorkspaceAncestors()) {
      for(Entry<Dependency, Set<ArtifactKey>> entry : getDependencyExcludes(project, monitor.newChild(1)).entrySet()) {
        locatedKeys.addAll(entry.getValue());
        Dependency dependency = entry.getKey();
        if(contains(entry.getValue(), dependency)) {
          IFile pom = project.getResource();
          if(pom != null) {
            statuses.add(new Status(IStatus.INFO, PLUGIN_ID, NLS.bind(
                Messages.ExcludeArtifactRefactoring_removeDependencyFrom, toString(dependency), pom.getFullPath())));
            changes.add(PomHelper.createChange(pom, new RemoveDependencyOperation(dependency), getName(pom)));
          }
        } else {
          exclusionOp.add(new AddDependencyOperation(dependency));
          for(ArtifactKey key : entry.getValue()) {
            if(!hasExclusion(exclusionPoint, dependency, key)) {
              exclusionOp.add(new AddExclusionOperation(dependency, key));
            }
          }
        }
      }
    }
    if(!exclusionOp.isEmpty()) {
      IFile pom = exclusionPoint.getResource();
      changes.add(PomHelper.createChange(pom,
          new CompoundOperation(exclusionOp.toArray(new Operation[exclusionOp.size()])), getName(pom)));
    }

    if(statuses.size() == 1) {
      return RefactoringStatus.create(statuses.get(0));
    } else if(statuses.size() > 1) {
      return RefactoringStatus.create(new MultiStatus(PLUGIN_ID, 0, statuses.toArray(new IStatus[statuses.size()]),
          Messages.ExcludeArtifactRefactoring_errorCreatingRefactoring, null));
    } else if(locatedKeys.isEmpty()) {
      return RefactoringStatus.createFatalErrorStatus(Messages.ExcludeArtifactRefactoring_noTargets);
    } else if(locatedKeys.size() != excludes.length) {
      StringBuilder sb = new StringBuilder();
      for(ArtifactKey key : excludes) {
        if(!locatedKeys.contains(key)) {
          sb.append(key.toString()).append(',');
        }
      }
      sb.deleteCharAt(sb.length() - 1);
      return RefactoringStatus.createErrorStatus(NLS.bind(Messages.ExcludeArtifactRefactoring_failedToLocateArtifact,
          sb.toString()));
    }
    return new RefactoringStatus();
  }

  private String getName(IFile file) {
    return new StringBuilder().append(file.getName()).append(" - ").append(file.getProject().getName()).toString(); //$NON-NLS-1$
  }

  /**
   * Map key is one of <dependency> element of specified (workspace) model. Map value is set of <excludes> element keys
   * to be added to the <dependency>.
   */
  private Map<Dependency, Set<ArtifactKey>> getDependencyExcludes(ParentHierarchyEntry model, IProgressMonitor monitor)
      throws CoreException {
    IMavenProjectFacade facade = model.getFacade();
    MavenProject project = model.getProject();
    DependencyNode root = MavenPlugin.getMavenModelManager().readDependencyTree(facade, project, JavaScopes.TEST,
        monitor);
    Visitor visitor = new Visitor(model);
    root.accept(visitor);
    return visitor.getSourceMap();
  }

  @Override
  public Change createChange(IProgressMonitor pm) throws OperationCanceledException {
    CompositeChange change = new CompositeChange(Messages.ExcludeArtifactRefactoring_changeTitle);
    change.addAll(changes.toArray(new Change[changes.size()]));
    return change;
  }

  private static boolean matches(Dependency d, ArtifactKey a) {
    return d.getArtifactId().equals(a.getArtifactId()) && d.getGroupId().equals(a.getGroupId());
  }

  private static boolean contains(Set<ArtifactKey> keys, Dependency d) {
    for(ArtifactKey key : keys) {
      if(matches(d, key)) {
        return true;
      }
    }
    return false;
  }

  private Collection<ParentHierarchyEntry> getHierarchy() {
    return hierarchy;
  }

  private Collection<ParentHierarchyEntry> getWorkspaceDescendants() {
    List<ParentHierarchyEntry> descendants = new ArrayList<ParentHierarchyEntry>();
    for(ParentHierarchyEntry project : getHierarchy()) {
      if(project == exclusionPoint) {
        break;
      }
      if(project.getFacade() != null) {
        descendants.add(project);
      }
    }
    return descendants;
  }

  private Collection<ParentHierarchyEntry> getWorkspaceAncestors() {
    List<ParentHierarchyEntry> ancestors = new ArrayList<ParentHierarchyEntry>();
    boolean add = false;
    for(ParentHierarchyEntry project : getHierarchy()) {
      if(project == exclusionPoint) {
        add = !add;
      } else if(add) {
        if(project.getFacade() != null) {
          ancestors.add(project);
        }
      }
    }
    return ancestors;
  }

  private static String toString(Dependency dependency) {
    return NLS.bind(
        "{0}:{1}:{2}", new String[] {dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion()}); //$NON-NLS-1$
  }

  private boolean hasDependency(ParentHierarchyEntry project, Dependency dependency) {
    List<Dependency> dependencies = project.getProject().getOriginalModel().getDependencies();
    if(dependencies == null) {
      return false;
    }
    for(Dependency dep : dependencies) {
      if(dep.getArtifactId().equals(dependency.getArtifactId()) && dep.getGroupId().equals(dependency.getGroupId())
          && (dep.getVersion() == null || dep.getVersion().equals(dependency.getVersion()))) {
        return true;
      }
    }
    return false;
  }

  private static boolean hasExclusion(ParentHierarchyEntry project, Dependency d, ArtifactKey exclusion) {
    List<Dependency> dependencies = project.getProject().getOriginalModel().getDependencies();
    if(dependencies == null) {
      return false;
    }
    Dependency dependency = null;
    for(Dependency dep : dependencies) {
      if(dep.getArtifactId().equals(d.getArtifactId()) && dep.getGroupId().equals(d.getGroupId())
          && (dep.getVersion() == null || dep.getVersion().equals(d.getVersion()))) {
        dependency = dep;
        break;
      }
    }
    if(dependency == null || dependency.getExclusions() == null) {
      return false;
    }
    for(Exclusion ex : dependency.getExclusions()) {
      if(ex.getArtifactId().equals(exclusion.getArtifactId()) && ex.getGroupId().equals(exclusion.getGroupId())) {
        return true;
      }
    }
    return false;
  }

  private class Visitor implements DependencyVisitor {
    private List<Dependency> dependencies;

    private Map<Dependency, Set<ArtifactKey>> sourceMap = new HashMap<Dependency, Set<ArtifactKey>>();

    Visitor(ParentHierarchyEntry project) {
      dependencies = new ArrayList<Dependency>();
      dependencies.addAll(project.getProject().getOriginalModel().getDependencies());
//      for(Profile profile : project.getActiveProfiles()) {
//        dependencies.addAll(profile.getDependencies());
//      }
    }

    Map<Dependency, Set<ArtifactKey>> getSourceMap() {
      return sourceMap;
    }

    private int depth;

    private DependencyNode topLevel;

    public boolean visitLeave(DependencyNode node) {
      depth-- ;
      return true;
    }

    public boolean visitEnter(DependencyNode node) {
      if(depth == 1) {
        topLevel = node;
      }
      depth++ ;

      if(node.getDependency() != null) {
        Artifact a = node.getDependency().getArtifact();
        for(ArtifactKey exclude : excludes) {
          if(a.getGroupId().equals(exclude.getGroupId()) && a.getArtifactId().equals(exclude.getArtifactId())) {
            if(topLevel != null) {
              // need to add exclusion to top-level dependency
              Dependency dependency = findDependency(topLevel);
              if(dependency != null) {
                put(dependency, exclude);
              }
            }
            return true;
          }
        }
      }
      return true;
    }

    private void put(Dependency dep, ArtifactKey key) {
      Set<ArtifactKey> keys = sourceMap.get(dep);
      if(keys == null) {
        keys = new HashSet<ArtifactKey>();
        sourceMap.put(dep, keys);
      }
      keys.add(key);
    }

    private Dependency findDependency(String groupId, String artifactId) {
      for(Dependency d : dependencies) {
        if(d.getGroupId().equals(groupId) && d.getArtifactId().equals(artifactId)) {
          return d;
        }
      }
      return null;
    }

    private Dependency findDependency(DependencyNode node) {
      Artifact artifact;
      if(node.getRelocations().isEmpty()) {
        artifact = node.getDependency().getArtifact();
      } else {
        artifact = node.getRelocations().get(0);
      }
      return findDependency(artifact.getGroupId(), artifact.getArtifactId());
    }
  }
}

Back to the top