Example usage for org.apache.maven.project MavenProject getClassRealm

List of usage examples for org.apache.maven.project MavenProject getClassRealm

Introduction

In this page you can find the example usage for org.apache.maven.project MavenProject getClassRealm.

Prototype

public ClassRealm getClassRealm() 

Source Link

Document

Gets the project's class realm.

Usage

From source file:com.jayway.maven.plugins.android.phase_prebuild.ClasspathModifierLifecycleParticipant.java

License:Open Source License

@Override
public void afterProjectsRead(MavenSession session) throws MavenExecutionException {
    log.debug("");
    log.debug("ClasspathModifierLifecycleParticipant#afterProjectsRead - start");
    log.debug("");

    log.debug("CurrentProject=" + session.getCurrentProject());
    final List<MavenProject> projects = session.getProjects();
    final DependencyResolver dependencyResolver = new DependencyResolver(log, dependencyGraphBuilder);
    final ArtifactResolverHelper artifactResolverHelper = new ArtifactResolverHelper(artifactResolver, log);

    for (MavenProject project : projects) {
        log.debug("");
        log.debug("project=" + project.getArtifact());

        if (!AndroidExtension.isAndroidPackaging(project.getPackaging())) {
            continue; // do not modify classpath if not an android project.
        }// ww  w .j a  va 2  s  . c  om

        final UnpackedLibHelper helper = new UnpackedLibHelper(artifactResolverHelper, project, log);

        final Set<Artifact> artifacts;

        // If there is an extension ClassRealm loaded for this project then use that
        // as the ContextClassLoader so that Wagon extensions can be used to resolves dependencies.
        final ClassLoader projectClassLoader = (project.getClassRealm() != null) ? project.getClassRealm()
                : Thread.currentThread().getContextClassLoader();

        final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(projectClassLoader);
            artifacts = dependencyResolver.getProjectDependenciesFor(project, session);
        } catch (DependencyGraphBuilderException e) {
            // Nothing to do. The resolution failure will be displayed by the standard resolution mechanism.
            continue;
        } finally {
            Thread.currentThread().setContextClassLoader(originalClassLoader);
        }

        log.debug("projects deps: : " + artifacts);
        for (Artifact artifact : artifacts) {
            final String type = artifact.getType();
            if (type.equals(AndroidExtension.AAR)) {
                // An AAR lib contains a classes jar that needs to be added to the classpath.
                // Create a placeholder classes.jar and add it to the compile classpath.
                // It will replaced with the real classes.jar by GenerateSourcesMojo.
                addClassesToClasspath(helper, project, artifact);
                // Add jar files in 'libs' into classpath.
                addLibsJarsToClassPath(helper, project, artifact);
            } else if (type.equals(AndroidExtension.APK)) {
                // The only time that an APK will likely be a dependency is when this an an APK test project.
                // So add a placeholder (we cannot resolve the actual dep pre build) to the compile classpath.
                // The placeholder will be replaced with the real APK jar later.
                addClassesToClasspath(helper, project, artifact);
            } else if (type.equals(AndroidExtension.APKLIB)) {
                // Add jar files in 'libs' into classpath.
                addLibsJarsToClassPath(helper, project, artifact);
            }
        }
    }
    log.debug("");
    log.debug("ClasspathModifierLifecycleParticipant#afterProjectsRead - finish");
}

From source file:com.simpligility.maven.plugins.android.phase_prebuild.ClasspathModifierLifecycleParticipant.java

License:Open Source License

@Override
public void afterProjectsRead(MavenSession session) throws MavenExecutionException {
    log.debug("");
    log.debug("ClasspathModifierLifecycleParticipant#afterProjectsRead - start");
    log.debug("");

    log.debug("CurrentProject=" + session.getCurrentProject());
    final List<MavenProject> projects = session.getProjects();
    final DependencyResolver dependencyResolver = new DependencyResolver(log, dependencyGraphBuilder);
    final ArtifactResolverHelper artifactResolverHelper = new ArtifactResolverHelper(artifactResolver, log);

    for (MavenProject project : projects) {
        log.debug("");
        log.debug("project=" + project.getArtifact());

        if (!AndroidExtension.isAndroidPackaging(project.getPackaging())) {
            continue; // do not modify classpath if not an android project.
        }/* w  w  w.ja v a 2  s .  c o  m*/

        final String unpackedLibsFolder = getMojoConfigurationParameter(project, UNPACKED_LIBS_FOLDER_PARAM,
                null);
        final UnpackedLibHelper helper = new UnpackedLibHelper(artifactResolverHelper, project, log,
                unpackedLibsFolder == null ? null : new File(unpackedLibsFolder));

        final Set<Artifact> artifacts;

        // If there is an extension ClassRealm loaded for this project then use that
        // as the ContextClassLoader so that Wagon extensions can be used to resolves dependencies.
        final ClassLoader projectClassLoader = (project.getClassRealm() != null) ? project.getClassRealm()
                : Thread.currentThread().getContextClassLoader();

        final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(projectClassLoader);
            artifacts = dependencyResolver.getProjectDependenciesFor(project, session);
        } catch (DependencyGraphBuilderException e) {
            // Nothing to do. The resolution failure will be displayed by the standard resolution mechanism.
            continue;
        } finally {
            Thread.currentThread().setContextClassLoader(originalClassLoader);
        }

        boolean includeFromAar = getMojoConfigurationParameter(project, INCLUDE_FROM_AAR_PARAM,
                INCLUDE_FROM_AAR_DEFAULT);
        boolean includeFromApklib = getMojoConfigurationParameter(project, INCLUDE_FROM_APKLIB_PARAM,
                INCLUDE_FROM_APKLIB_DEFAULT);
        boolean disableConflictingDependenciesWarning = getMojoConfigurationParameter(project,
                DISABLE_CONFLICTING_DEPENDENCIES_WARNING_PARAM,
                DISABLE_CONFLICTING_DEPENDENCIES_WARNING_DEFAULT);

        log.debug("projects deps: : " + artifacts);

        if (!disableConflictingDependenciesWarning) {
            ProvidedDependencyChecker checker = new ProvidedDependencyChecker();
            checker.checkProvidedDependencies(artifacts, log);
        }

        for (Artifact artifact : artifacts) {
            final String type = artifact.getType();
            if (type.equals(AndroidExtension.AAR)) {
                // An AAR lib contains a classes jar that needs to be added to the classpath.
                // Create a placeholder classes.jar and add it to the compile classpath.
                // It will replaced with the real classes.jar by GenerateSourcesMojo.
                addClassesToClasspath(helper, project, artifact);

                // An AAR may also contain zero or more internal libs in the libs folder.
                // If 'includeLibsJarsFromAar' config param is true then include them too.
                if (includeFromAar) {
                    // Add jar files in 'libs' into classpath.
                    addLibsJarsToClassPath(helper, project, artifact);
                }
            } else if (type.equals(AndroidExtension.APK)) {
                // The only time that an APK will likely be a dependency is when this an an APK test project.
                // So add a placeholder (we cannot resolve the actual dep pre build) to the compile classpath.
                // The placeholder will be replaced with the real APK jar later.
                addClassesToClasspath(helper, project, artifact);
            } else if (type.equals(AndroidExtension.APKLIB)) {
                if (includeFromApklib) {
                    // Add jar files in 'libs' into classpath.
                    addLibsJarsToClassPath(helper, project, artifact);
                }
            }
        }
    }

    if (addedJarFromLibs) {
        log.warn("Transitive dependencies should really be provided by Maven dependency management.\n"
                + "          We suggest you to ask the above providers to package their component properly.\n"
                + "          Things may break at compile and/or runtime due to multiple copies of incompatible libraries.");
    }
    log.debug("");
    log.debug("ClasspathModifierLifecycleParticipant#afterProjectsRead - finish");
}

From source file:info.ronjenkins.maven.rtr.RTR.java

License:Apache License

private List<AbstractMavenLifecycleParticipant> getExtensions(final MavenSession session)
        throws ComponentLookupException {
    final List<AbstractMavenLifecycleParticipant> mvnExtensionsXml = new ArrayList<>();
    // Save the original classloader.
    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    try {/*from w w  w .  j av a 2s .c o  m*/
        // Get the libext extensions.
        ClassLoader plexusCore = this.getClass().getClassLoader();
        while (plexusCore.getParent() != null) {
            plexusCore = plexusCore.getParent();
        }
        Thread.currentThread().setContextClassLoader(plexusCore);
        mvnExtensionsXml.addAll(this.container.lookupList(AbstractMavenLifecycleParticipant.class));
        // Get the .mvn/extensions.xml extensions.
        for (final MavenProject project : session.getProjects()) {
            // getClassRealm() is not considered part of Maven's public API for
            // plugins, but no mention is made of extensions. It's the only reliable
            // way to see which extensions are loaded for each project, so we'll use
            // it as long as we can get away with it.
            final ClassLoader projectRealm = project.getClassRealm();
            if (projectRealm != null) {
                Thread.currentThread().setContextClassLoader(projectRealm);
                mvnExtensionsXml.addAll(this.container.lookupList(AbstractMavenLifecycleParticipant.class));
            }
        }
    } finally {
        // Restore the original classloader.
        Thread.currentThread().setContextClassLoader(originalClassLoader);
    }
    return mvnExtensionsXml;
}

From source file:org.eclipse.che.maven.server.MavenServerImpl.java

License:Open Source License

/**
 * method from org.apache.maven.DefaultMaven#getLifecycleParticipants
 *///ww  w  .java  2  s . c  o m
private Collection<AbstractMavenLifecycleParticipant> getLifecycleParticipants(
        Collection<MavenProject> projects) {
    Collection<AbstractMavenLifecycleParticipant> lifecycleListeners = new LinkedHashSet<AbstractMavenLifecycleParticipant>();

    ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        try {
            lifecycleListeners.addAll(container.lookupList(AbstractMavenLifecycleParticipant.class));
        } catch (ComponentLookupException e) {
            // this is just silly, lookupList should return an empty list!
            logWarn("Failed to lookup lifecycle participants: " + e.getMessage());
        }

        Collection<ClassLoader> scannedRealms = new HashSet<ClassLoader>();

        for (MavenProject project : projects) {
            ClassLoader projectRealm = project.getClassRealm();

            if (projectRealm != null && scannedRealms.add(projectRealm)) {
                Thread.currentThread().setContextClassLoader(projectRealm);

                try {
                    lifecycleListeners.addAll(container.lookupList(AbstractMavenLifecycleParticipant.class));
                } catch (ComponentLookupException e) {
                    // this is just silly, lookupList should return an empty list!
                    logWarn("Failed to lookup lifecycle participants: " + e.getMessage());
                }
            }
        }
    } finally {
        Thread.currentThread().setContextClassLoader(originalClassLoader);
    }

    return lifecycleListeners;
}

From source file:org.eclipse.m2e.core.internal.embedder.MavenImpl.java

License:Open Source License

/**
 * Temporary solution/workaround for http://jira.codehaus.org/browse/MNG-4194. Extensions realm is created each time
 * MavenProject instance is built, so we have to remove unused extensions realms to avoid OOME.
 *//* w  w w.  j  av a2s  . c om*/
public void releaseExtensionsRealm(MavenProject project) {
    ClassRealm realm = project.getClassRealm();
    if (realm != null && realm != plexus.getContainerRealm()) {
        ClassWorld world = ((MutablePlexusContainer) plexus).getClassWorld();
        try {
            world.disposeRealm(realm.getId());
        } catch (NoSuchRealmException ex) {
            log.error("Could not dispose of project extensions class realm", ex);
        }
    }
}

From source file:org.eclipse.m2e.core.internal.embedder.MavenImpl.java

License:Open Source License

public ClassLoader getProjectRealm(MavenProject project) {
    ClassLoader classLoader = project.getClassRealm();
    if (classLoader == null) {
        classLoader = plexus.getContainerRealm();
    }/*  w w w  .j a v  a 2 s.co  m*/
    return classLoader;
}

From source file:org.jetbrains.idea.maven.server.Maven30ServerEmbedderImpl.java

License:Apache License

/**
 * adapted from {@link DefaultMaven#getLifecycleParticipants(Collection)}
 *//*from   ww w  . j  av  a  2s.c  o  m*/
private Collection<AbstractMavenLifecycleParticipant> getLifecycleParticipants(
        Collection<MavenProject> projects) {
    Collection<AbstractMavenLifecycleParticipant> lifecycleListeners = new LinkedHashSet<AbstractMavenLifecycleParticipant>();

    ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        try {
            lifecycleListeners.addAll(myContainer.lookupList(AbstractMavenLifecycleParticipant.class));
        } catch (ComponentLookupException e) {
            // this is just silly, lookupList should return an empty list!
            warn("Failed to lookup lifecycle participants", e);
        }

        Collection<ClassLoader> scannedRealms = new HashSet<ClassLoader>();

        for (MavenProject project : projects) {
            ClassLoader projectRealm = project.getClassRealm();

            if (projectRealm != null && scannedRealms.add(projectRealm)) {
                Thread.currentThread().setContextClassLoader(projectRealm);

                try {
                    lifecycleListeners.addAll(myContainer.lookupList(AbstractMavenLifecycleParticipant.class));
                } catch (ComponentLookupException e) {
                    // this is just silly, lookupList should return an empty list!
                    warn("Failed to lookup lifecycle participants", e);
                }
            }
        }
    } finally {
        Thread.currentThread().setContextClassLoader(originalClassLoader);
    }

    return lifecycleListeners;
}

From source file:org.sonatype.m2e.mavenarchiver.internal.AbstractMavenArchiverConfigurator.java

License:Open Source License

public void generateManifest(IMavenProjectFacade mavenFacade, IFile manifest, IProgressMonitor monitor)
        throws CoreException {

    MavenProject mavenProject = mavenFacade.getMavenProject();
    Set<Artifact> originalArtifacts = mavenProject.getArtifacts();
    boolean parentHierarchyLoaded = false;
    try {//from   ww  w .  j a  va  2 s . c o m
        markerManager.deleteMarkers(mavenFacade.getPom(), MavenArchiverConstants.MAVENARCHIVER_MARKER_ERROR);

        //Find the mojoExecution
        MavenSession session = getMavenSession(mavenFacade, monitor);

        parentHierarchyLoaded = loadParentHierarchy(mavenFacade, monitor);

        ClassLoader originalTCL = Thread.currentThread().getContextClassLoader();
        try {
            ClassRealm projectRealm = mavenProject.getClassRealm();
            if (projectRealm != null && projectRealm != originalTCL) {
                Thread.currentThread().setContextClassLoader(projectRealm);
            }
            MavenExecutionPlan executionPlan = maven.calculateExecutionPlan(session, mavenProject,
                    Collections.singletonList("package"), true, monitor);
            MojoExecution mojoExecution = getExecution(executionPlan, getExecutionKey());
            if (mojoExecution == null) {
                return;
            }

            //Get the target manifest file
            IFolder destinationFolder = (IFolder) manifest.getParent();
            M2EUtils.createFolder(destinationFolder, true, monitor);

            //Workspace project artifacts don't have a valid getFile(), so won't appear in the manifest
            //We need to workaround the issue by creating  fake files for such artifacts. 
            //We could also use a custom File implementation having "public boolean exists(){return true;}"
            mavenProject.setArtifacts(fixArtifactFileNames(mavenFacade));

            //Invoke the manifest generation API via reflection
            reflectManifestGeneration(mavenProject, mojoExecution, session,
                    new File(manifest.getLocation().toOSString()));
        } finally {
            Thread.currentThread().setContextClassLoader(originalTCL);
        }
    } catch (Exception ex) {
        markerManager.addErrorMarkers(mavenFacade.getPom(), MavenArchiverConstants.MAVENARCHIVER_MARKER_ERROR,
                ex);

    } finally {
        //Restore the project state
        mavenProject.setArtifacts(originalArtifacts);
        if (parentHierarchyLoaded) {
            mavenProject.setParent(null);
        }
    }

}

From source file:org.sourcepit.maven.bootstrap.core.AbstractBootstrapper.java

License:Apache License

private List<ClassRealm> discoverBootExtensionClassRealms(MavenProject bootProject) {
    final List<ClassRealm> bootExtensionRelams = new ArrayList<ClassRealm>();

    final ClassRealm projectRealm = bootProject.getClassRealm();
    if (projectRealm != null) {
        @SuppressWarnings("unchecked")
        final Collection<ClassRealm> importRealms = projectRealm.getImportRealms();
        for (ClassRealm classRealm : importRealms) {
            if (isBootExtensionClassRealm(extensionRealmPrefixes, classRealm)) {
                bootExtensionRelams.add(classRealm);
            }/*from www. j a v a 2  s  . c  o  m*/
        }
    }

    return bootExtensionRelams;
}

From source file:org.sourcepit.tpmp.resolver.tycho.TychoSessionTargetPlatformResolver.java

License:Apache License

private MavenProject setupAggregatedProject(MavenSession session,
        TargetPlatformConfiguration aggregatedConfiguration) {
    PropertiesMap mvnProperties = new LinkedPropertiesMap();
    mvnProperties.load(getClass().getClassLoader(), "META-INF/tpmp/maven.properties");

    String groupId = mvnProperties.get("groupId");
    String artifactId = mvnProperties.get("artifactId");
    String version = mvnProperties.get("version");

    final String tpmpKey = Plugin.constructKey(groupId, artifactId);

    MavenProject origin = session.getCurrentProject();

    Model model = origin.getModel().clone();
    Build build = model.getBuild();/*  ww  w.  jav  a  2s .c om*/
    if (build.getPluginsAsMap().get(tpmpKey) == null) {
        Plugin tpmp = new Plugin();
        tpmp.setGroupId(groupId);
        tpmp.setArtifactId(artifactId);
        tpmp.setVersion(version);

        build.getPlugins().add(tpmp);
        build.flushPluginMap();
    }

    MavenProject fake = new MavenProject(model);
    fake.setClassRealm(origin.getClassRealm());
    fake.setFile(origin.getFile());

    final Map<String, ArtifactRepository> artifactRepositories = new LinkedHashMap<String, ArtifactRepository>();
    final Map<String, ArtifactRepository> pluginRepositories = new LinkedHashMap<String, ArtifactRepository>();
    for (MavenProject project : session.getProjects()) {
        for (ArtifactRepository repository : project.getRemoteArtifactRepositories()) {
            if (!artifactRepositories.containsKey(repository.getId())) {
                artifactRepositories.put(repository.getId(), repository);
            }
        }
        for (ArtifactRepository repository : project.getPluginArtifactRepositories()) {
            if (!pluginRepositories.containsKey(repository.getId())) {
                pluginRepositories.put(repository.getId(), repository);
            }
        }
    }

    fake.setRemoteArtifactRepositories(new ArrayList<ArtifactRepository>(artifactRepositories.values()));
    fake.setPluginArtifactRepositories(new ArrayList<ArtifactRepository>(pluginRepositories.values()));
    fake.setManagedVersionMap(origin.getManagedVersionMap());

    if (getTychoProject(fake) == null) {
        fake.setPackaging("eclipse-repository");
    }

    fake.getBuildPlugins();

    AbstractTychoProject tychoProject = (AbstractTychoProject) getTychoProject(fake);
    tychoProject.setupProject(session, fake);

    Properties properties = new Properties();
    properties.putAll(fake.getProperties());
    properties.putAll(session.getSystemProperties()); // session wins
    properties.putAll(session.getUserProperties());
    fake.setContextValue(TychoConstants.CTX_MERGED_PROPERTIES, properties);

    fake.setContextValue(TychoConstants.CTX_TARGET_PLATFORM_CONFIGURATION, aggregatedConfiguration);

    ExecutionEnvironmentConfiguration eeConfiguration = new ExecutionEnvironmentConfigurationImpl(logger,
            aggregatedConfiguration.isResolveWithEEConstraints());
    tychoProject.readExecutionEnvironmentConfiguration(fake, eeConfiguration);
    fake.setContextValue(TychoConstants.CTX_EXECUTION_ENVIRONMENT_CONFIGURATION, eeConfiguration);

    final DependencyMetadata dm = new DependencyMetadata();
    for (ReactorProject reactorProject : DefaultReactorProject.adapt(session)) {
        mergeMetadata(dm, reactorProject, true);
        mergeMetadata(dm, reactorProject, false);
    }

    int i = 0;
    for (Object object : dm.getMetadata(true)) {
        InstallableUnitDAO dao = new TychoSourceIUResolver.InstallableUnitDAO(
                object.getClass().getClassLoader());
        dao.setProperty(object, RepositoryLayoutHelper.PROP_CLASSIFIER, "fake_" + i);
        i++;
    }

    for (Object object : dm.getMetadata(false)) {
        InstallableUnitDAO dao = new TychoSourceIUResolver.InstallableUnitDAO(
                object.getClass().getClassLoader());
        dao.setProperty(object, RepositoryLayoutHelper.PROP_CLASSIFIER, "fake_" + i);
        i++;
    }

    Map<String, DependencyMetadata> metadata = new LinkedHashMap<String, DependencyMetadata>();
    metadata.put(null, dm);

    fake.setContextValue("tpmp.aggregatedMetadata", metadata);

    return fake;
}