15

おそらくこれは私が当初考えていたよりも大きなタスクになるでしょうが、それにもかかわらず、私はMavenProjectファイルからをロードしてその依存関係を解決しようとしています。両方のビットのコードがありますが、必要なオブジェクト参照がいくつかありません。具体的には、とのインスタンスを取得する必要が RepositorySystemSessionありますRepositorySystem。任意のヒント?

注:この質問にタグを付けましたが、これはMavenプラグインではありません。私はMaven3を義務付けることができてうれしいです(とにかく私はすでに持っていると思います..)

これが私がこれまでに持っているコードです:

の構築MavenProject

public static MavenProject loadProject(File pomFile) throws Exception
{
    MavenProject ret = null;
    MavenXpp3Reader mavenReader = new MavenXpp3Reader();

    if (pomFile != null && pomFile.exists())
    {
        FileReader reader = null;

        try
            {
            reader = new FileReader(pomFile);
            Model model = mavenReader.read(reader);
            model.setPomFile(pomFile);

            ret = new MavenProject(model);
        }
        finally
        {
            // Close reader
        }
    }

    return ret;
}

依存関係の解決:

public static List<Dependency> getArtifactsDependencies(MavenProject project, String dependencyType, String scope) throws Exception
{    
    DefaultArtifact pomArtifact = new DefaultArtifact(project.getId());

    RepositorySystemSession repoSession = null; // TODO
    RepositorySystem repoSystem = null; // TODO

    List<RemoteRepository> remoteRepos = project.getRemoteProjectRepositories();
    List<Dependency> ret = new ArrayList<Dependency>();

    Dependency dependency = new Dependency(pomArtifact, scope);

    CollectRequest collectRequest = new CollectRequest();
    collectRequest.setRoot(dependency);
    collectRequest.setRepositories(remoteRepos);

    DependencyNode node = repoSystem.collectDependencies(repoSession, collectRequest).getRoot();
    DependencyRequest projectDependencyRequest = new DependencyRequest(node, null);

    repoSystem.resolveDependencies(repoSession, projectDependencyRequest);

    PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
    node.accept(nlg);

    ret.addAll(nlg.getDependencies(true));

    return ret;
}

これは珍しいリクエストかもしれないと思います。たぶん、私がやろうとしていたことを破棄してプラグインとしてラップする必要があります...しかし、私は今始めたことを終わらせたいだけです!前もって感謝します。

4

6 に答える 6

5

まさにそのような目的のためのAether libに関する情報を読むことをお勧めします。

注: Aether は以前は Sonatype で開発されていましたが、その後Eclipseに移行されました。

于 2012-08-03T17:24:53.050 に答える
5

Sonatype のApache Aetherのラッパーであるjcabi-aetherを試してください。

final File repo = this.session.getLocalRepository().getBasedir();
final Collection<Artifact> deps = new Aether(this.getProject(), repo).resolve(
  new DefaultArtifact("junit", "junit-dep", "", "jar", "4.10"),
  JavaScopes.RUNTIME
);

Maven プラグインを使用していない場合:

final File repo = new File(System.getProperty("java.io.tmpdir"), "my-repo");
final MavenProject project = new MavenProject();
project.setRemoteArtifactRepositories(
  Arrays.asList(
    new RemoteRepository(
      "maven-central",
      "default",
      "http://repo1.maven.org/maven2/"
    )
  )
);
final Collection<Artifact> deps = new Aether(project, repo).resolve(
  new DefaultArtifact("junit", "junit-dep", "", "jar", "4.10"),
  JavaScopes.RUNTIME
);
于 2012-10-28T12:40:20.163 に答える
4

私はちょうどあなたと私の問題の両方に対する解決策を作り上げました:

/*******************************************************************************
 * Copyright (c) 2013 TerraFrame, Inc. All rights reserved. 
 * 
 * This file is part of Runway SDK(tm).
 * 
 * Runway SDK(tm) is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * Runway SDK(tm) 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 Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with Runway SDK(tm).  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/

package com.test.mavenaether;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
import org.apache.maven.artifact.repository.MavenArtifactRepository;
import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.sonatype.aether.artifact.Artifact;
import org.sonatype.aether.resolution.DependencyResolutionException;
import org.sonatype.aether.util.artifact.DefaultArtifact;
import org.sonatype.aether.util.artifact.JavaScopes;

import com.jcabi.aether.Aether;

public class MavenAether
{
  public static void main(String[] args) throws Exception
  {
    String classpath = getClasspathFromMavenProject(new File("/users/terraframe/documents/workspace/MavenSandbox/pom.xml"), new File("/users/terraframe/.m2/repository"));
    System.out.println("classpath = " + classpath);
  }

  public static String getClasspathFromMavenProject(File projectPom, File localRepoFolder) throws DependencyResolutionException, IOException, XmlPullParserException
  {
    MavenProject proj = loadProject(projectPom);

    proj.setRemoteArtifactRepositories(
        Arrays.asList(
            (ArtifactRepository) new MavenArtifactRepository(
                "maven-central", "http://repo1.maven.org/maven2/", new DefaultRepositoryLayout(),
                new ArtifactRepositoryPolicy(), new ArtifactRepositoryPolicy()
            )
        )
    );

    String classpath = "";
    Aether aether = new Aether(proj, localRepoFolder);

    List<org.apache.maven.model.Dependency> dependencies = proj.getDependencies();
    Iterator<org.apache.maven.model.Dependency> it = dependencies.iterator();

    while (it.hasNext()) {
      org.apache.maven.model.Dependency depend = it.next();

      final Collection<Artifact> deps = aether.resolve(
        new DefaultArtifact(depend.getGroupId(), depend.getArtifactId(), depend.getClassifier(), depend.getType(), depend.getVersion()),
        JavaScopes.RUNTIME
      );

      Iterator<Artifact> artIt = deps.iterator();
      while (artIt.hasNext()) {
        Artifact art = artIt.next();
        classpath = classpath + " " + art.getFile().getAbsolutePath();
      }
    }

    return classpath;
  }

  public static MavenProject loadProject(File pomFile) throws IOException, XmlPullParserException
  {
      MavenProject ret = null;
      MavenXpp3Reader mavenReader = new MavenXpp3Reader();

      if (pomFile != null && pomFile.exists())
      {
          FileReader reader = null;

          try
              {
              reader = new FileReader(pomFile);
              Model model = mavenReader.read(reader);
              model.setPomFile(pomFile);

              ret = new MavenProject(model);
          }
          finally
          {
            reader.close();
          }
      }

      return ret;
  }
}

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.test</groupId>
  <artifactId>MavenSandbox</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
    <dependency>
      <groupId>com.jcabi</groupId>
      <artifactId>jcabi-aether</artifactId>
      <version>0.7.19</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-core</artifactId>
      <version>3.0.3</version>
    </dependency>
  </dependencies>
</project>

コードは最初に Maven プロジェクトをロードし (元の質問で提供された関数を使用)、次に jcabi-aether を使用してローカル リポジトリでアーティファクトを見つけます。main 関数の 2 つのパラメーター (プロジェクトの pom.xml の場所とローカル リポジトリの場所) を変更する必要があります。

楽しみ!:)

于 2013-06-03T21:53:20.920 に答える
2

最新の Maven (3.1.1) で使用されている Eclipses Aether API のスタンドアロンの例の素晴らしいセットがあり、ここで見つけることができます。

注: Maven 3.1.X は引き続き Aether を使用します0.9.0.M2(例で使用した最新バージョンは です0.9.0.M3)。したがって、Maven プラグイン内でこれらの例を実行するには、バージョン M2 が必要であり、スタンドアロン アプリケーションは最新の M3 バージョンを使用できます。

于 2013-09-30T11:05:52.093 に答える
2

これを試してください( ather-demoからわかるように):

...
LocalRepository localRepository = new LocalRepository("/path/to/local-repo");

RepositorySystem system = getRepositorySystemInstance();
RepositorySystemSession session = getRepositorySystemSessionInstance(system, localRepository);
....

public static RepositorySystem getRepositorySystemInstance()
{
    /**
     * Aether's components implement org.sonatype.aether.spi.locator.Service to ease manual wiring and using the
     * prepopulated DefaultServiceLocator, we only need to register the repository connector factories.
     */
    MavenServiceLocator locator = new MavenServiceLocator();
    locator.addService(RepositoryConnectorFactory.class, FileRepositoryConnectorFactory.class);
    locator.addService(RepositoryConnectorFactory.class, WagonRepositoryConnectorFactory.class);
    locator.setServices(WagonProvider.class, new ManualWagonProvider());

    return locator.getService(RepositorySystem.class);
}

private static RepositorySystemSession getRepositorySystemSessionInstance(RepositorySystem system,
                                                                          LocalRepository localRepo)
{
    MavenRepositorySystemSession session = new MavenRepositorySystemSession();

    session.setLocalRepositoryManager(system.newLocalRepositoryManager(localRepo));

    session.setTransferListener(new ConsoleTransferListener());
    session.setRepositoryListener(new ConsoleRepositoryListener());

    // Set this in order to generate dirty trees
    session.setDependencyGraphTransformer(null);

    return session;
}
于 2013-05-23T15:04:44.290 に答える