Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Fabric3
   * Copyright (c) 2009 Metaform Systems
   *
   * Fabric3 is free software: you can redistribute it and/or modify
   * it under the terms of the GNU General Public License as
   * published by the Free Software Foundation, either version 3 of
   * the License, or (at your option) any later version, with the
   * following exception:
  *
  * Linking this software statically or dynamically with other
  * modules is making a combined work based on this software.
  * Thus, the terms and conditions of the GNU General Public
  * License cover the whole combination.
  *
  * As a special exception, the copyright holders of this software
  * give you permission to link this software with independent
  * modules to produce an executable, regardless of the license
  * terms of these independent modules, and to copy and distribute
  * the resulting executable under terms of your choice, provided
  * that you also meet, for each linked independent module, the
  * terms and conditions of the license of that module. An
  * independent module is a module which is not derived from or
  * based on this software. If you modify this software, you may
  * extend this exception to your version of the software, but
  * you are not obligated to do so. If you do not wish to do so,
  * delete this exception statement from your version.
  *
  * Fabric3 is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty
  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  * See the GNU General Public License for more details.
  *
  * You should have received a copy of the
  * GNU General Public License along with Fabric3.
  * If not, see <http://www.gnu.org/licenses/>.
  *
  * ----------------------------------------------------
  *
  * Portions originally based on Apache Tuscany 2007
  * licensed under the Apache 2.0 license.
  *
  */
 package org.fabric3.runtime.maven.archive;
 
 import java.io.File;
 import java.util.List;
 import java.util.Map;
 
 import static org.apache.maven.artifact.Artifact.SCOPE_RUNTIME;
Utility class for embedding Maven.

Version:
$Rev: 7899 $ $Date: 2009-11-23 10:44:11 +0100 (Mon, 23 Nov 2009) $
 
 public class MavenHelper {

    
Remote repository URLs
 
     private final String[] remoteRepositoryUrls;

    
Maven metadata source
 
     private ArtifactMetadataSource metadataSource;

    
Artifact factory
    private ArtifactFactory artifactFactory;

    
Local artifact repository
    private ArtifactRepository localRepository;

    
Remote artifact repositories
TODO Make use of mirrors in Artifact resolution (when remote repositories are unavailable Remote artifact mirrors
    private List<ArtifactRepositoryremoteMirrors = new LinkedList<ArtifactRepository>();


    
Artifact resolver
    private ArtifactResolver artifactResolver;

    
Online
    private boolean online;

    
Initialize the remote repository URLs.

Parameters:
remoteRepositoryUrl Remote repository URLS.
online whether the runtime is online or not
    public MavenHelper(String remoteRepositoryUrlboolean online) {
        this. = remoteRepositoryUrl.split(",");
        this. = online;
    }

    
Starts the embedder.

Throws:
Fabric3DependencyException If unable to start the embedder.
    public void start() throws Fabric3DependencyException {
        try {
            Embedder embedder = new Embedder();
            ClassWorld classWorld = new ClassWorld();
            classWorld.newRealm("plexus.fabric"getClass().getClassLoader());
            // Evil hack for Tomcat classloader issue - starts
            Field realmsField = ClassWorld.class.getDeclaredField("realms");
            realmsField.setAccessible(true);
            Map realms = (MaprealmsField.get(classWorld);
            DefaultClassRealm realm = (DefaultClassRealmrealms.get("plexus.fabric");
            Class clazz = Class.forName("org.codehaus.classworlds.RealmClassLoader");
            Constructor ctr = clazz.getDeclaredConstructor(DefaultClassRealm.classClassLoader.class);
            ctr.setAccessible(true);
            Object realmClassLoader = ctr.newInstance(realmgetClass().getClassLoader());
            Field realmClassLoaderField = DefaultClassRealm.class.getDeclaredField("classLoader");
            realmClassLoaderField.setAccessible(true);
            realmClassLoaderField.set(realmrealmClassLoader);
            // Evil hack for Tomcat classloader issue - ends
            embedder.start(classWorld);
             = (ArtifactFactoryembedder.lookup(.);
             = (ArtifactResolverembedder.lookup(.);
            setUpRepositories(embedder);
            embedder.stop();
        } catch (DuplicateRealmException ex) {
            throw new Fabric3DependencyException(ex);
        } catch (PlexusContainerException ex) {
            throw new Fabric3DependencyException(ex);
        } catch (ComponentLookupException ex) {
            throw new Fabric3DependencyException(ex);
        } catch (NoSuchFieldException ex) {
            throw new Fabric3DependencyException(ex);
        } catch (IllegalAccessException ex) {
            throw new Fabric3DependencyException(ex);
        } catch (ClassNotFoundException ex) {
            throw new Fabric3DependencyException(ex);
        } catch (NoSuchMethodException ex) {
            throw new Fabric3DependencyException(ex);
        } catch (InstantiationException ex) {
            throw new Fabric3DependencyException(ex);
        } catch (InvocationTargetException ex) {
            throw new Fabric3DependencyException(ex);
        }
    }

    
Stops the embedder.

Throws:
Fabric3DependencyException If unable to stop the embedder.
    public void stop() throws Fabric3DependencyException {
    }

    
Resolves the dependencies transitively.

Parameters:
rootArtifact Artifact whose dependencies need to be resolved.
Returns:
true if the artifact was succesfully resolved
Throws:
Fabric3DependencyException If unable to resolve the dependencies.
    public boolean resolveTransitively(Artifact rootArtifactthrows Fabric3DependencyException {
        org.apache.maven.artifact.Artifact mavenRootArtifact;
        mavenRootArtifact = .createArtifact(rootArtifact.getGroup(),
                                                           rootArtifact.getName(),
                                                           rootArtifact.getVersion(),
                                                           ,
                                                           rootArtifact.getType());
        try {
            if (resolve(mavenRootArtifact)) {
                rootArtifact.setUrl(mavenRootArtifact.getFile().toURL());
                return resolveDependencies(rootArtifactmavenRootArtifact);
            } else {
                return false;
            }
        } catch (MalformedURLException ex) {
            throw new Fabric3DependencyException(ex);
        }
    }
    /*
     * Resolves the artifact.
     */
    private boolean resolve(org.apache.maven.artifact.Artifact mavenRootArtifact) {
        try {
            .resolve(mavenRootArtifact);
            return true;
        } catch (ArtifactResolutionException ex) {
            return false;
        } catch (ArtifactNotFoundException ex) {
            return false;
        }
    }
    /*
    * Sets up local and remote repositories.
    */
    private void setUpRepositories(Embedder embedder) {
        try {
            ArtifactRepositoryFactory artifactRepositoryFactory =
                    (ArtifactRepositoryFactoryembedder.lookup(.);
            ArtifactRepositoryLayout layout =
                    (ArtifactRepositoryLayoutembedder.lookup(."default");
            String updatePolicy =
            ArtifactRepositoryPolicy snapshotsPolicy =
                    new ArtifactRepositoryPolicy(trueupdatePolicy.);
            ArtifactRepositoryPolicy releasesPolicy =
                    new ArtifactRepositoryPolicy(trueupdatePolicy.);
            MavenSettingsBuilder settingsBuilder = (MavenSettingsBuilderembedder.lookup(.);
            Settings settings = settingsBuilder.buildSettings();
            String localRepo = settings.getLocalRepository();
             = artifactRepositoryFactory.createArtifactRepository("local",
                                                                                 new File(localRepo).toURI().toURL().toString(),
                                                                                 layout,
                                                                                 snapshotsPolicy,
                                                                                 releasesPolicy);
            if () {
                setupRemoteRepositories(settingsartifactRepositoryFactorylayoutsnapshotsPolicyreleasesPolicy);
                setupMirrors(settingsartifactRepositoryFactorylayoutsnapshotsPolicyreleasesPolicy);
            }
        } catch (Exception ex) {
            throw new Fabric3DependencyException(ex);
        }
    }

    
Read remote repository URLs from settings and create artifact repositories

Parameters:
settings
artifactRepositoryFactory
layout
snapshotsPolicy
releasesPolicy
    private void setupRemoteRepositories(
            Settings settings,
            ArtifactRepositoryFactory artifactRepositoryFactory,
            ArtifactRepositoryLayout layout,
            ArtifactRepositoryPolicy snapshotsPolicy,
            ArtifactRepositoryPolicy releasesPolicy) {
        // Read repository urls from settings file
        List<StringrepositoryUrls = resolveActiveProfileRepositories(settings);
        repositoryUrls.addAll(Arrays.asList());
        for (String remoteRepositoryUrl : repositoryUrls) {
            .add(
                    createArtifactRepository(
                            remoteRepositoryUrl,
                            artifactRepositoryFactory,
                            layout,
                            snapshotsPolicy,
                            releasesPolicy
                    )
            );
        }
    }

    
Read mirror URLs from settings and create artifact repositories

Parameters:
settings
artifactRepositoryFactory
layout
snapshotsPolicy
releasesPolicy
    private void setupMirrors(
            Settings settings,
            ArtifactRepositoryFactory artifactRepositoryFactory,
            ArtifactRepositoryLayout layout,
            ArtifactRepositoryPolicy snapshotsPolicy,
            ArtifactRepositoryPolicy releasesPolicy) {
        List<StringmirrorUrls = resolveMirrorUrls(settings);
        for (String mirrorUrl : mirrorUrls) {
            .add(
                    createArtifactRepository(
                            mirrorUrl,
                            artifactRepositoryFactory,
                            layout,
                            snapshotsPolicy,
                            releasesPolicy
                    )
            );
        }
    }


    
Creates an ArtifactFactory

Parameters:
repositoryUrl
Returns:
            String repositoryUrl,
            ArtifactRepositoryFactory artifactRepositoryFactory,
            ArtifactRepositoryLayout layout,
            ArtifactRepositoryPolicy snapshotsPolicy,
            ArtifactRepositoryPolicy releasesPolicy) {
        String repositoryId = convertUrlToRepositoryId(repositoryUrl);
        return
                artifactRepositoryFactory.createArtifactRepository(
                        repositoryId,
                        repositoryUrl,
                        layout,
                        snapshotsPolicy,
                        releasesPolicy);
    }

    
Converts a repository URL into a repository id

Parameters:
remoteRepositoryUrl a repository URL
Returns:
repository id
    private static String convertUrlToRepositoryId(String remoteRepositoryUrl) {
        assert remoteRepositoryUrl != null : "remoteRepositoryUrl cannot be null";
        String repoid = remoteRepositoryUrl.replace(':''_');
        repoid = repoid.replace('/''_');
        repoid = repoid.replace('\\''_');
        return repoid;
    }


    
Construct a list of repositories from any active profiles

Parameters:
settings The Maven settings to be used
Returns:
List<Repository> of remote repositories in order of precedence
    // Suppress Warnings for conversion from raw types 
    @SuppressWarnings("unchecked")
    private List<StringresolveActiveProfileRepositories(Settings settings) {
        List<Stringrepositories = new ArrayList<String>();
        Map<StringProfileprofilesMap = (Map<StringProfile>) settings.getProfilesAsMap();
        for (Object nextProfileId : settings.getActiveProfiles()) {
            Profile nextProfile = profilesMap.get((StringnextProfileId);
            if (nextProfile.getRepositories() != null) {
                for (Object repository : nextProfile.getRepositories()) {
                    String url = ((Repositoryrepository).getUrl();
                    repositories.add(url);
                }
            }
        }
        return repositories;
    }


    
Construct a list of mirror urls from the maven settings

Parameters:
settings The Maven settings to be used
Returns:
List<String> of mirror urls
    // Suppress Warnings for conversion from raw types 
    @SuppressWarnings("unchecked")
    private List<StringresolveMirrorUrls(Settings settings) {
        List<StringmirrorUrls = new ArrayList<String>();
        List<Mirrormirrors = (List<Mirror>) settings.getMirrors();
        for (Mirror mirror : mirrors) {
            mirrorUrls.add(mirror.getUrl());
        }
        return mirrorUrls;
    }
    /*
    * Resolves transitive dependencies.
    */
    private boolean resolveDependencies(Artifact rootArtifactorg.apache.maven.artifact.Artifact mavenRootArtifact) {
        try {
            ResolutionGroup resolutionGroup = null;
            ArtifactResolutionResult result = null;
            resolutionGroup = .retrieve(mavenRootArtifact);
            result = .resolveTransitively(resolutionGroup.getArtifacts(),
                                                          mavenRootArtifact,
                                                          ,
                                                          ,
                                                          );
            // Add the artifacts to the deployment unit
            for (Object obj : result.getArtifacts()) {
                org.apache.maven.artifact.Artifact depArtifact = (org.apache.maven.artifact.Artifactobj;
                Artifact artifact = new Artifact();
                artifact.setName(depArtifact.getArtifactId());
                artifact.setGroup(depArtifact.getGroupId());
                artifact.setType(depArtifact.getType());
                artifact.setVersion(depArtifact.getVersion());
                artifact.setClassifier(depArtifact.getClassifier());
                artifact.setUrl(depArtifact.getFile().toURL());
                rootArtifact.addDependency(artifact);
            }
        } catch (ArtifactMetadataRetrievalException ex) {
            return false;
        } catch (MalformedURLException ex) {
            throw new Fabric3DependencyException(ex);
        } catch (ArtifactResolutionException ex) {
            return false;
        } catch (ArtifactNotFoundException ex) {
            return false;
        }
        return true;
    }
New to GrepCode? Check out our FAQ X