Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 1f238ff1e279a994f60749eb0750a8c09f837989 (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
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
/*******************************************************************************
 * Copyright (c) 2008-2010 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.tests.common;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;

import junit.framework.TestCase;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;

import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.component.repository.ComponentDescriptor;
import org.codehaus.plexus.util.IOUtil;

import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.model.Model;
import org.apache.maven.wagon.Wagon;

import org.eclipse.m2e.core.MavenPlugin;
import org.eclipse.m2e.core.core.IMavenConstants;
import org.eclipse.m2e.core.embedder.IMavenConfiguration;
import org.eclipse.m2e.core.embedder.MavenModelManager;
import org.eclipse.m2e.core.internal.MavenPluginActivator;
import org.eclipse.m2e.core.internal.embedder.MavenImpl;
import org.eclipse.m2e.core.internal.lifecyclemapping.LifecycleMappingFactory;
import org.eclipse.m2e.core.internal.project.registry.ProjectRegistryRefreshJob;
import org.eclipse.m2e.core.project.IMavenProjectFacade;
import org.eclipse.m2e.core.project.IMavenProjectImportResult;
import org.eclipse.m2e.core.project.MavenProjectInfo;
import org.eclipse.m2e.core.project.ProjectImportConfiguration;
import org.eclipse.m2e.core.project.ResolverConfiguration;
import org.eclipse.m2e.jdt.MavenJdtPlugin;
import org.eclipse.m2e.jdt.internal.BuildPathManager;

@SuppressWarnings( "restriction" )
public abstract class AbstractMavenProjectTestCase extends TestCase {
  
  public static final int DELETE_RETRY_COUNT = 10;
  public static final long DELETE_RETRY_DELAY = 6000L;

  protected static final IProgressMonitor monitor = new NullProgressMonitor();
  
  protected IWorkspace workspace;
  protected File repo;
  
  protected ProjectRegistryRefreshJob projectRefreshJob;
  protected Job downloadSourcesJob;

  protected IMavenConfiguration mavenConfiguration;

  private String oldUserSettingsFile;

  @SuppressWarnings("unchecked")
  protected void setUp() throws Exception {
    System.out.println("TEST-SETUP: " + getName());

    super.setUp();

    workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceDescription description = workspace.getDescription();
    description.setAutoBuilding(false);
    workspace.setDescription(description);

    // lets not assume we've got subversion in the target platform 
    Hashtable<String, String> options = JavaCore.getOptions();
    options.put(JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, ".svn/");
    JavaCore.setOptions(options);

    projectRefreshJob = MavenPluginActivator.getDefault().getProjectManagerRefreshJob();
    projectRefreshJob.sleep();

    downloadSourcesJob = ((BuildPathManager) MavenJdtPlugin.getDefault().getBuildpathManager()).getDownloadSourcesJob();
    downloadSourcesJob.sleep();

    mavenConfiguration = MavenPlugin.getMavenConfiguration();

    oldUserSettingsFile = mavenConfiguration.getUserSettingsFile();
    File settings = new File("settings.xml").getCanonicalFile();
    if (settings.canRead()) {
      String userSettingsFile = settings.getAbsolutePath();
      System.out.println("Setting user settings file: " + userSettingsFile);
      mavenConfiguration.setUserSettingsFile(userSettingsFile);
    }

    ArtifactRepository localRepository = MavenPlugin.getMaven().getLocalRepository();
    if(localRepository != null) {
      repo =  new File(localRepository.getBasedir());
    } else {
      fail("Cannot determine local repository path");
    }

    // make sure all tests use default metadata by default
    LifecycleMappingFactory.setUseDefaultLifecycleMappingMetadataSource(true);
    LifecycleMappingFactory.setDefaultLifecycleMappingMetadataSource(null);

    WorkspaceHelpers.cleanWorkspace();
  }

  protected void tearDown() throws Exception {
    try {
      waitForJobsToComplete();
      WorkspaceHelpers.cleanWorkspace();

      // Restore the user settings file location
      System.out.println("Restoring user settings file: " + oldUserSettingsFile);
      mavenConfiguration.setUserSettingsFile(oldUserSettingsFile);

      projectRefreshJob.wakeUp();
      IWorkspaceDescription description = workspace.getDescription();
      description.setAutoBuilding(true);
      workspace.setDescription(description);
    } finally {
      super.tearDown();
    }
  }

  protected void deleteProject(String projectName) throws CoreException, InterruptedException {
    IProject project = workspace.getRoot().getProject(projectName);

    deleteProject(project);
  }

  protected void deleteProject(IProject project) throws InterruptedException, CoreException {
    Exception cause = null;
    for (int  i = 0; i < DELETE_RETRY_COUNT; i++) {
      try {
        doDeleteProject(project);
      } catch (InterruptedException e) {
        throw e;
      } catch (OperationCanceledException e) {
        throw e;
      } catch (Exception e) {
        cause = e;
        Thread.sleep(DELETE_RETRY_DELAY);
        continue;
      }

      // all clear
      return;
    }

    // must be a timeout
    throw new CoreException(new Status(IStatus.ERROR, IMavenConstants.PLUGIN_ID, "Could not delete project", cause));
  }

  private void doDeleteProject(final IProject project) throws CoreException, InterruptedException {
    waitForJobsToComplete(monitor);

    workspace.run(new IWorkspaceRunnable() {
      public void run(IProgressMonitor monitor) throws CoreException {
        if(project.exists()) {
          deleteMember(".classpath", project, monitor);
          deleteMember(".project", project, monitor);
          project.delete(false, true, monitor);
        }
      }
  
      private void deleteMember(String name, final IProject project, IProgressMonitor monitor) throws CoreException {
        IResource member = project.findMember(name);
        if(member != null && member.exists()) {
          member.delete(true, monitor);
        }
      }
    }, new NullProgressMonitor());
  }

  protected IProject createProject(String projectName, final String pomResource) throws CoreException {
    final IProject project = workspace.getRoot().getProject(projectName);
  
    workspace.run(new IWorkspaceRunnable() {
      public void run(IProgressMonitor monitor) throws CoreException {
        project.create(monitor);
  
        if(!project.isOpen()) {
          project.open(monitor);
        }
  
        IFile pomFile = project.getFile("pom.xml");
        if(!pomFile.exists()) {
          InputStream is = null;
          try {
            is = new FileInputStream(pomResource);
            pomFile.create(is, true, monitor);
          } catch(FileNotFoundException ex) {
            throw new CoreException(new Status(IStatus.ERROR, "", 0, ex.toString(), ex));
          } finally {
            IOUtil.close(is);
          }
        }
      }
    }, null);
  
    return project;
  }

  protected IProject createExisting(String projectName, String projectLocation) throws IOException, CoreException {
    File dir = new File(workspace.getRoot().getLocation().toFile(), projectName);
    copyDir(new File(projectLocation), dir);

    final IProject project = workspace.getRoot().getProject(projectName);

    workspace.run(new IWorkspaceRunnable() {
      public void run(IProgressMonitor monitor) throws CoreException {
        if (!project.exists()) {
          IProjectDescription projectDescription = workspace.newProjectDescription(project.getName());
          projectDescription.setLocation(null); 
          project.create(projectDescription, monitor);
          project.open(IResource.NONE, monitor);
        } else {
          project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
        }
      }
    }, null);
    return project;
  }

  /**
   * Import a test project into the Eclipse workspace
   * 
   * @param pomLocation - a relative location of the pom file for the project to import
   * @return created project
   */
  protected IProject importProject(String pomLocation) throws IOException, CoreException {
    return importProject(pomLocation, new ResolverConfiguration());
  }

  /**
   * Import a test project into the Eclipse workspace
   * 
   * @param pomLocation - a relative location of the pom file for the project to import
   * @param configuration - a resolver configuration to be used to configure imported project 
   * @return created project
   */
  protected IProject importProject(String pomLocation, ResolverConfiguration configuration) throws IOException, CoreException {
    File pomFile = new File(pomLocation);
    return importProjects(pomFile.getParentFile().getCanonicalPath(), new String[] {pomFile.getName()}, configuration)[0];
  }

  /**
   * Import test projects into the Eclipse workspace
   * 
   * @param basedir - a base directory for all projects to import
   * @param pomNames - a relative locations of the pom files for the projects to import
   * @param configuration - a resolver configuration to be used to configure imported projects 
   * @return created projects
   */
  protected IProject[] importProjects(String basedir, String[] pomNames, ResolverConfiguration configuration) throws IOException, CoreException {
    return importProjects(basedir, pomNames, configuration, false);
  }

  protected IProject[] importProjects(String basedir, String[] pomNames, ResolverConfiguration configuration, boolean skipSanityCheck) throws IOException, CoreException {
    MavenModelManager mavenModelManager = MavenPlugin.getMavenModelManager();
    IWorkspaceRoot root = workspace.getRoot();
    
    File src = new File(basedir);
    File dst = new File(root.getLocation().toFile(), src.getName());
    copyDir(src, dst);

    final ArrayList<MavenProjectInfo> projectInfos = new ArrayList<MavenProjectInfo>();
    for(String pomName : pomNames) {
      File pomFile = new File(dst, pomName);
      Model model = mavenModelManager.readMavenModel(pomFile);
      MavenProjectInfo projectInfo = new MavenProjectInfo(pomName, pomFile, model, null);
      setBasedirRename(projectInfo);
      projectInfos.add(projectInfo);
    }

    final ProjectImportConfiguration importConfiguration = new ProjectImportConfiguration(configuration);
    
    final ArrayList<IMavenProjectImportResult> importResults = new ArrayList<IMavenProjectImportResult>();

    workspace.run(new IWorkspaceRunnable() {
      public void run(IProgressMonitor monitor) throws CoreException {
        importResults.addAll(MavenPlugin.getProjectConfigurationManager().importProjects(projectInfos,
            importConfiguration, monitor));
      }
    }, MavenPlugin.getProjectConfigurationManager().getRule(), IWorkspace.AVOID_UPDATE, monitor);

    IProject[] projects = new IProject[projectInfos.size()];
    for (int i = 0; i < projectInfos.size(); i++) {
      IMavenProjectImportResult importResult = importResults.get(i);
      assertSame(projectInfos.get(i), importResult.getMavenProjectInfo());
      projects[i] = importResult.getProject();
      assertNotNull("Failed to import project " + projectInfos, projects[i]);
      
      /*
       * Sanity check: make sure they were all imported
       */
      if(!skipSanityCheck) {
        Model model = projectInfos.get(0).getModel();
        IMavenProjectFacade facade = MavenPlugin.getMavenProjectRegistry().create(projects[i], monitor);
        if(facade == null) {
          fail("Project " + model.getGroupId() + "-" + model.getArtifactId() + "-" + model.getVersion()
              + " was not imported. Errors: "
              + WorkspaceHelpers.toString(WorkspaceHelpers.findErrorMarkers(projects[i])));
        }
      }
    }

    return projects;
  }

  private void setBasedirRename(MavenProjectInfo projectInfo) throws IOException {
    File workspaceRoot = workspace.getRoot().getLocation().toFile();
    File basedir = projectInfo.getPomFile().getParentFile().getCanonicalFile();

    projectInfo.setBasedirRename(basedir.getParentFile().equals(workspaceRoot)? MavenProjectInfo.RENAME_REQUIRED: MavenProjectInfo.RENAME_NO);
  }

  protected IProject importProject(String projectName, String projectLocation, ResolverConfiguration configuration) throws IOException, CoreException {
    ProjectImportConfiguration importConfiguration = new ProjectImportConfiguration(configuration);
    importConfiguration.setProjectNameTemplate(projectName);
    return importProject(projectName, projectLocation, importConfiguration);
  }

  protected IProject importProject(String projectName, String projectLocation, final ProjectImportConfiguration importConfiguration) throws IOException, CoreException {
    File dir = new File(workspace.getRoot().getLocation().toFile(), projectName);
    copyDir(new File(projectLocation), dir);

    File pomFile = new File(dir, IMavenConstants.POM_FILE_NAME);
    Model model = MavenPlugin.getMavenModelManager().readMavenModel(pomFile);
    final MavenProjectInfo projectInfo = new MavenProjectInfo(projectName, pomFile, model, null);
    setBasedirRename(projectInfo);

    workspace.run(new IWorkspaceRunnable() {
      public void run(IProgressMonitor monitor) throws CoreException {
        MavenPlugin.getProjectConfigurationManager().importProjects(Collections.singleton(projectInfo),
            importConfiguration, monitor);
        IProject project = workspace.getRoot().getProject(importConfiguration.getProjectName(projectInfo.getModel()));
        assertNotNull("Failed to import project " + projectInfo, project);
      }
    }, MavenPlugin.getProjectConfigurationManager().getRule(), IWorkspace.AVOID_UPDATE, monitor);

    return workspace.getRoot().getProject(projectName);
  }

  protected void waitForJobsToComplete() throws InterruptedException, CoreException {
    waitForJobsToComplete(monitor);
  }

  public static void waitForJobsToComplete(IProgressMonitor monitor) throws InterruptedException, CoreException {
    JobHelpers.waitForJobsToComplete(monitor);
  }

  protected IClasspathEntry[] getMavenContainerEntries(IProject project) throws JavaModelException {
    IJavaProject javaProject = JavaCore.create(project);
    IClasspathContainer container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
    return container.getClasspathEntries();
  }

  protected static String toString(IMarker[] markers) {
    return WorkspaceHelpers.toString(markers);
  }

  protected static String toString(List<IMarker> markers) {
    return WorkspaceHelpers.toString(markers);
  }

  protected void copyContent(IProject project, String from, String to) throws Exception {
    copyContent(project, project.getFile(from).getContents(), to);
  }

  protected void copyContent(IProject project, File from, String to) throws Exception {
    copyContent(project, new FileInputStream(from), to);
  }

  /**
   * closes contents stream
   */
  private void copyContent(IProject project, InputStream contents, String to) throws CoreException, IOException,
      InterruptedException {
    try {
      IFile file = project.getFile(to);
      if (!file.exists()) {
        file.create(contents, IResource.FORCE, monitor);
      } else {
        file.setContents(contents, IResource.FORCE, monitor);
      }
    } finally {
      contents.close();
    }
    waitForJobsToComplete();
  }

  public static void copyDir(File src, File dst) throws IOException {
    FileHelpers.copyDir(src, dst);
  }

  public static void copyDir(File src, File dst, FileFilter filter) throws IOException {
    FileHelpers.copyDir(src, dst, filter);
  }

  protected static List<IMarker> findErrorMarkers(IProject project) throws CoreException {
    return WorkspaceHelpers.findErrorMarkers(project);
  }

  protected static List<IMarker> findMarkers(IProject project, int targetSeverity) throws CoreException {
    return WorkspaceHelpers.findMarkers(project, targetSeverity);
  }

  protected static void assertNoErrors(IProject project) throws CoreException {
    WorkspaceHelpers.assertNoErrors(project);
  }

  protected void injectFilexWagon() throws Exception {
    PlexusContainer container = ((MavenImpl) MavenPlugin.getMaven()).getPlexusContainer();
    if(container.getContainerRealm().getResource(FilexWagon.class.getName().replace('.', '/') + ".class") == null) {
      container.getContainerRealm().importFrom(FilexWagon.class.getClassLoader(), FilexWagon.class.getName());
      ComponentDescriptor<Wagon> descriptor = new ComponentDescriptor<Wagon>();
      descriptor.setRealm(container.getContainerRealm());
      descriptor.setRoleClass(Wagon.class);
      descriptor.setImplementationClass(FilexWagon.class);
      descriptor.setRoleHint("filex");
      descriptor.setInstantiationStrategy("singleton");
      container.addComponentDescriptor(descriptor);
    }
  }
}

Back to the top