Java Code Examples for org.apache.maven.model.building.ModelBuildingException

The following examples show how to use org.apache.maven.model.building.ModelBuildingException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cloud-opensource-java   Source File: LinkageMonitor.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] arguments)
    throws RepositoryException, IOException, MavenRepositoryException, ModelBuildingException {
  if (arguments.length < 1 || arguments[0].split(":").length != 2) {
    logger.severe(
        "Please specify BOM coordinates without version. Example:"
            + " com.google.cloud:libraries-bom");
    System.exit(1);
  }
  String bomCoordinates = arguments[0];
  List<String> coordinatesElements = Splitter.on(':').splitToList(bomCoordinates);

  Set<SymbolProblem> newSymbolProblems =
      new LinkageMonitor().run(coordinatesElements.get(0), coordinatesElements.get(1));
  int errorSize = newSymbolProblems.size();
  if (errorSize > 0) {
    logger.severe(
        String.format("Found %d new linkage error%s", errorSize, errorSize > 1 ? "s" : ""));
    logger.info(
        "For the details of the linkage errors, see "
            + "https://github.com/GoogleCloudPlatform/cloud-opensource-java/wiki/Linkage-Checker-Messages");
    System.exit(1); // notify CI tools of the failure
  } else {
    logger.info("No new problem found");
  }
}
 
Example 2
Source Project: cloud-opensource-java   Source File: LinkageMonitorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildModelWithSnapshotBom_noSnapshotUpdate()
    throws ModelBuildingException, ArtifactResolutionException {
  Model model =
      LinkageMonitor.buildModelWithSnapshotBom(
          system, session, "com.google.cloud:libraries-bom:2.2.1", ImmutableMap.of());
  List<Dependency> dependencies = model.getDependencyManagement().getDependencies();

  assertEquals(
      "There should not be a duplicate",
      dependencies.stream().distinct().count(),
      dependencies.size());

  // This number is different from the number appearing in BOM dashboard because model from
  // buildModelWithSnapshotBom still contains unnecessary artifacts that would be filtered by
  // RepositoryUtility.shouldSkipBomMember
  assertEquals(214, dependencies.size());
}
 
Example 3
Source Project: quarkus   Source File: MavenModelBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ModelBuildingResult build(ModelBuildingRequest request) throws ModelBuildingException {
    if (workspaceResolver != null) {
        request.setWorkspaceModelResolver(workspaceResolver);
        final Model requestModel = getModel(request);
        try {
            if (requestModel != null && workspaceResolver.resolveRawModel(ModelUtils.getGroupId(requestModel),
                    requestModel.getArtifactId(), ModelUtils.getVersion(requestModel)) != null) {
                completeWorkspaceProjectBuildRequest(request);
            }
        } catch (UnresolvableModelException e) {
            // ignore
        }
    }
    return builder.build(request);
}
 
Example 4
Source Project: netbeans   Source File: MavenEmbedder.java    License: Apache License 2.0 6 votes vote down vote up
/**
     * Creates a list of POM models in an inheritance lineage.
     * Each resulting model is "raw", so contains no interpolation or inheritance.
     * In particular beware that groupId and/or version may be null if inherited from a parent; use {@link Model#getParent} to resolve.
     * Internally calls <code>executeModelBuilder</code> so if you need to call both just use the execute method.
     * @param pom a POM to inspect
     * @param embedder an embedder to use
     * @return a list of models, starting with the specified POM, going through any parents, finishing with the Maven superpom (with a null artifactId)
     * @throws ModelBuildingException if the POM or parents could not even be parsed; warnings are not reported
     */
    public List<Model> createModelLineage(File pom) throws ModelBuildingException {
        ModelBuildingResult res = executeModelBuilder(pom);
        List<Model> toRet = new ArrayList<Model>();

        for (String id : res.getModelIds()) {
            Model m = res.getRawModel(id);
            normalizePath(m);
            toRet.add(m);
        }
//        for (ModelProblem p : res.getProblems()) {
//            System.out.println("problem=" + p);
//            if (p.getException() != null) {
//                p.getException().printStackTrace();
//            }
//        }
        return toRet;
    }
 
Example 5
Source Project: netbeans   Source File: NBModelBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ModelBuildingResult build(ModelBuildingRequest request) throws ModelBuildingException {
    ModelBuildingResult toRet = super.build(request);
    Model eff = toRet.getEffectiveModel();
    InputSource source = new InputSource();
    source.setLocation("");
    InputLocation location = new InputLocation(-1, -1, source);
    eff.setLocation(NETBEANS_PROFILES, location);
    for (String id : toRet.getModelIds()) {
        Model mdl = toRet.getRawModel(id);
        for (Profile p : mdl.getProfiles()) {
            source.setLocation(source.getLocation() + "|" + p.getId());
        }
    }
    return toRet;
}
 
Example 6
Source Project: netbeans   Source File: EmbedderFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testInvalidRepositoryException() throws Exception { // #197831
    File pom = TestFileUtils.writeFile(new File(getWorkDir(), "pom.xml"), "<project xmlns='http://maven.apache.org/POM/4.0.0'>" +
        "<modelVersion>4.0.0</modelVersion>" +
        "<groupId>grp</groupId>" +
        "<artifactId>art</artifactId>" +
        "<packaging>jar</packaging>" +
        "<version>1.0-SNAPSHOT</version>" +
        "<repositories><repository><url>http://nowhere.net/</url></repository></repositories>" +
        "</project>");
    try {
        EmbedderFactory.createProjectLikeEmbedder().createModelLineage(pom);
        fail();
    } catch (ModelBuildingException x) {
        // right
    }
}
 
Example 7
Source Project: repairnator   Source File: MavenHelper.java    License: MIT License 6 votes vote down vote up
public static Model readPomXml(File pomXml, String localMavenRepository) {
    ModelBuildingRequest req = new DefaultModelBuildingRequest();
    req.setProcessPlugins(true);
    req.setPomFile(pomXml);
    req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
    req.setModelResolver(new RepositoryModelResolver(localMavenRepository));

    DefaultModelBuilder defaultModelBuilder = new DefaultModelBuilderFactory().newInstance();

    // we try to build the model, and if we fail, we try to get the raw model
    try {
        ModelBuildingResult modelBuildingResult = defaultModelBuilder.build(req);
        return modelBuildingResult.getEffectiveModel();
    } catch (ModelBuildingException e) {
        LOGGER.error("Error while building complete model. The raw model will be used. Error message: " + e.getMessage());
        return defaultModelBuilder.buildRawModel(pomXml, ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL, true).get();
    }

}
 
Example 8
public ModelBuildingResult build( ModelBuildingRequest buildingRequest, ProfileInjector customInjector, ProfileSelector customSelector )
    throws ModelBuildingException
{
    // note: there is neither DefaultModelBuilder.get*(), nor DefaultModelBuilder.clone()
    return new DefaultModelBuilderFactory().newInstance()
        .setProfileInjector( customInjector )
        .setProfileSelector( customSelector )
        // apply currently active ModelProcessor etc. to support extensions like jgitver
        .setDependencyManagementImporter( dependencyManagementImporter )
        .setDependencyManagementInjector( dependencyManagementInjector )
        .setInheritanceAssembler( inheritanceAssembler )
        .setLifecycleBindingsInjector( lifecycleBindingsInjector )
        .setModelInterpolator( modelInterpolator )
        .setModelNormalizer( modelNormalizer )
        .setModelPathTranslator( modelPathTranslator )
        .setModelProcessor( modelProcessor )
        .setModelUrlNormalizer( modelUrlNormalizer )
        .setModelValidator( modelValidator )
        .setPluginConfigurationExpander( pluginConfigurationExpander )
        .setPluginManagementInjector( pluginManagementInjector )
        .setReportConfigurationExpander( reportConfigurationExpander )
        .setReportingConverter( reportingConverter )
        .setSuperPomProvider( superPomProvider )
        .build( buildingRequest );
}
 
Example 9
Source Project: cloud-opensource-java   Source File: LinkageMonitor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a copy of {@code bom} replacing its managed dependencies that have locally-installed
 * snapshot versions.
 */
@VisibleForTesting
static Bom copyWithSnapshot(
    RepositorySystem repositorySystem,
    RepositorySystemSession session,
    Bom bom,
    Map<String, String> localArtifacts)
    throws ModelBuildingException, ArtifactResolutionException {
  ImmutableList.Builder<Artifact> managedDependencies = ImmutableList.builder();

  Model model =
      buildModelWithSnapshotBom(repositorySystem, session, bom.getCoordinates(), localArtifacts);

  ArtifactTypeRegistry registry = session.getArtifactTypeRegistry();
  ImmutableList<Artifact> newManagedDependencies =
      model.getDependencyManagement().getDependencies().stream()
          .map(dependency -> RepositoryUtils.toDependency(dependency, registry))
          .map(Dependency::getArtifact)
          .collect(toImmutableList());
  for (Artifact managedDependency : newManagedDependencies) {
    if (Bom.shouldSkipBomMember(managedDependency)) {
      continue;
    }
    String version =
        localArtifacts.getOrDefault(
            managedDependency.getGroupId() + ":" + managedDependency.getArtifactId(),
            managedDependency.getVersion());
    managedDependencies.add(managedDependency.setVersion(version));
  }
  // "-SNAPSHOT" suffix for coordinate to distinguish easily.
  return new Bom(bom.getCoordinates() + "-SNAPSHOT", managedDependencies.build());
}
 
Example 10
@Test
public void testSubstitution() throws ArtifactResolutionException, ModelBuildingException {

  // Google-cloud-bom 0.121.0-alpha imports google-auth-library-bom 0.19.0.
  DefaultArtifact googleCloudBom =
      new DefaultArtifact("com.google.cloud:google-cloud-bom:pom:0.121.0-alpha");
  ArtifactResult bomResult =
      repositorySystem.resolveArtifact(
          session, new ArtifactRequest(googleCloudBom, ImmutableList.of(CENTRAL), null));

  ImmutableMap<String, String> substitution =
      ImmutableMap.of(
          "com.google.auth:google-auth-library-bom",
          "0.18.0" // This is intentionally different from 0.19.0
          );
  VersionSubstitutingModelResolver resolver =
      new VersionSubstitutingModelResolver(
          session,
          null,
          repositorySystem,
          remoteRepositoryManager,
          ImmutableList.of(CENTRAL), // Needed when parent pom is not locally available
          substitution);

  ModelBuildingRequest modelRequest = new DefaultModelBuildingRequest();
  modelRequest.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
  modelRequest.setPomFile(bomResult.getArtifact().getFile());
  modelRequest.setModelResolver(resolver);
  modelRequest.setSystemProperties(System.getProperties()); // for Java version property

  ModelBuildingResult result = modelBuilder.build(modelRequest);
  DependencyManagement dependencyManagement =
      result.getEffectiveModel().getDependencyManagement();

  Truth.assertWithMessage(
          "Google-cloud-bom's google-auth-library part should be substituted for a different version.")
      .that(dependencyManagement.getDependencies())
      .comparingElementsUsing(dependencyToCoordinates)
      .contains("com.google.auth:google-auth-library-credentials:0.18.0");
}
 
Example 11
Source Project: cloud-opensource-java   Source File: LinkageMonitorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBomSnapshot()
    throws ModelBuildingException, ArtifactResolutionException, ArtifactDescriptorException {

  Bom bom = Bom.readBom("com.google.cloud:libraries-bom:1.2.0");
  Bom snapshotBom =
      LinkageMonitor.copyWithSnapshot(
          system,
          session,
          bom,
          ImmutableMap.of("com.google.protobuf:protobuf-java", "3.8.0-SNAPSHOT"));

  assertWithMessage(
          "The first element of the SNAPSHOT BOM should be the same as the original BOM")
      .that(toCoordinates(snapshotBom.getManagedDependencies().get(0)))
      .isEqualTo("com.google.protobuf:protobuf-java:3.8.0-SNAPSHOT");

  assertWithMessage("Artifacts other than protobuf-java should have the original version")
      .that(skip(snapshotBom.getManagedDependencies(), 1))
      .comparingElementsUsing(
          transforming(
              Artifacts::toCoordinates,
              Artifacts::toCoordinates,
              "has the same Maven coordinates as"))
      .containsExactlyElementsIn(skip(bom.getManagedDependencies(), 1))
      .inOrder();
}
 
Example 12
Source Project: cloud-opensource-java   Source File: LinkageMonitorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildModelWithSnapshotBom_invalidCoordinates()
    throws ModelBuildingException, ArtifactResolutionException {
  for (String invalidCoordinates : ImmutableList.of("a.b.c:d", "a:b:c:d:e:1", "a::c:0.1")) {
    try {
      LinkageMonitor.buildModelWithSnapshotBom(
          system, session, invalidCoordinates, ImmutableMap.of());
      fail("The method should invalidate coordinates: " + invalidCoordinates);
    } catch (IllegalArgumentException ex) {
      // pass
    }
  }
}
 
Example 13
Source Project: cloud-opensource-java   Source File: LinkageMonitorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildModelWithSnapshotBom_BomSnapshotUpdate()
    throws ModelBuildingException, ArtifactResolutionException {
  // Linkage Monitor should update a BOM in Google Cloud Libraries BOM when it's available local
  // repository. This test case simulates the issue below where
  // google-cloud-bom:0.106.0-alpha-SNAPSHOT should provide gax:1.48.0.
  // https://github.com/GoogleCloudPlatform/cloud-opensource-java/issues/853
  // Libraries-bom:2.2.1 has google-cloud-bom:0.91.0-alpha, which has gax:1.44.0
  Model model =
      LinkageMonitor.buildModelWithSnapshotBom(
          system,
          session,
          "com.google.cloud:libraries-bom:2.2.1",
          ImmutableMap.of("com.google.cloud:google-cloud-bom", "0.106.0-alpha"));
  List<Dependency> dependencies = model.getDependencyManagement().getDependencies();

  // google-cloud-bom:0.106.0 has new artifacts such as google-cloud-gameservices
  assertEquals(224, dependencies.size());

  // google-cloud-bom:0.106.0-alpha has gax:1.48.0
  assertTrue(
      dependencies.stream()
          .anyMatch(
              dependency ->
                  "gax".equals(dependency.getArtifactId())
                      && "1.48.0".equals(dependency.getVersion())));
}
 
Example 14
Source Project: cloud-opensource-java   Source File: LinkageMonitorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildModelWithSnapshotBom_JdkVersionActivation()
    throws ModelBuildingException, ArtifactResolutionException {
  // google-cloud-core-parent's parent google-cloud-shared-config uses JDK version to activate
  // a profile. Without JDK system property, this throws ModelBuildingException.
  Model model =
      LinkageMonitor.buildModelWithSnapshotBom(
          system, session, "com.google.cloud:google-cloud-core-parent:1.91.0", ImmutableMap.of());
  assertNotNull(model);
}
 
Example 15
Source Project: netbeans   Source File: NbMavenProjectImpl.java    License: Apache License 2.0 5 votes vote down vote up
public Model getRawModel() throws ModelBuildingException {
    synchronized(MODEL_LOCK) {
        if(model == null) {
            MavenEmbedder projectEmbedder = EmbedderFactory.getProjectEmbedder();
            ModelBuildingResult br = projectEmbedder.executeModelBuilder(getPOMFile());
            model = br.getRawModel();
        }
        return model;
    }
}
 
Example 16
Source Project: netbeans   Source File: EffectivePomMD.java    License: Apache License 2.0 5 votes vote down vote up
static List<ModelProblem> runMavenValidationImpl(final File pom) {
    //TODO profiles based on current configuration??
    MavenEmbedder embedder = EmbedderFactory.getProjectEmbedder();
    MavenExecutionRequest meReq = embedder.createMavenExecutionRequest();
    ProjectBuildingRequest req = meReq.getProjectBuildingRequest();
    req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1); // currently enables just <reporting> warning
    req.setLocalRepository(embedder.getLocalRepository());
    List<ArtifactRepository> remoteRepos = RepositoryPreferences.getInstance().remoteRepositories(embedder);
    req.setRemoteRepositories(remoteRepos);
    req.setRepositorySession(((DefaultMaven) embedder.lookupComponent(Maven.class)).newRepositorySession(meReq));
    List<ModelProblem> problems;
    try {
        problems = embedder.lookupComponent(ProjectBuilder.class).build(pom, req).getProblems();
    } catch (ProjectBuildingException x) {
        problems = new ArrayList<ModelProblem>();
        List<ProjectBuildingResult> results = x.getResults();
        if (results != null) { //one code point throwing ProjectBuildingException contains results,
            for (ProjectBuildingResult result : results) {
                problems.addAll(result.getProblems());
            }
        } else {
            // another code point throwing ProjectBuildingException doesn't contain results..
            Throwable cause = x.getCause();
            if (cause instanceof ModelBuildingException) {
                problems.addAll(((ModelBuildingException) cause).getProblems());
            }
        }
    }
    return problems;
}
 
Example 17
Source Project: netbeans   Source File: POMInheritancePanel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    //#164852 somehow a folder dataobject slipped in, test mimetype to avoid that.
    // the root cause of the problem is unknown though
    if (current != null && Constants.POM_MIME_TYPE.equals(current.getPrimaryFile().getMIMEType())) { //NOI18N
        File file = FileUtil.toFile(current.getPrimaryFile());
        // can be null for stuff in jars?
        if (file != null) {
            try {
                List<Model> lin = EmbedderFactory.getProjectEmbedder().createModelLineage(file);
                final Children ch = Children.create(new PomChildren(lin), false);
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                       treeView.setRootVisible(false);
                       explorerManager.setRootContext(new AbstractNode(ch));
                    } 
                });
            } catch (final ModelBuildingException ex) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                       treeView.setRootVisible(true);
                       explorerManager.setRootContext(POMModelPanel.createErrorNode(ex));
                    }
                });
            }
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                   treeView.setRootVisible(false);
                   explorerManager.setRootContext(createEmptyNode());
                } 
            });
        }
    }
}
 
Example 18
Source Project: netbeans   Source File: POMModelPanel.java    License: Apache License 2.0 5 votes vote down vote up
static Node createErrorNode(ModelBuildingException x) {
    AbstractNode an = new AbstractNode(Children.LEAF);
    StringBuilder b = new StringBuilder();
    for (ModelProblem p : x.getProblems()) {
        if (b.length() > 0) {
            b.append("; ");
        }
        b.append(p.getMessage());
    }
    an.setDisplayName(b.toString());
    return an;
}
 
Example 19
Source Project: netbeans   Source File: MavenEmbedder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param pom
 * @return result object with access to effective pom model and raw models for each parent.
 * @throws ModelBuildingException if the POM or parents could not even be parsed; warnings are not reported
 */
public ModelBuildingResult executeModelBuilder(File pom) throws ModelBuildingException {
    ModelBuilder mb = lookupComponent(ModelBuilder.class);
    assert mb!=null : "ModelBuilder component not found in maven";
    ModelBuildingRequest req = new DefaultModelBuildingRequest();
    req.setPomFile(pom);
    req.setProcessPlugins(false);
    req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
    req.setLocationTracking(true);
    req.setModelResolver(new NBRepositoryModelResolver(this));
    req.setSystemProperties(getSystemProperties());
    req.setUserProperties(embedderConfiguration.getUserProperties());
    return mb.build(req);
    
}
 
Example 20
Source Project: netbeans   Source File: StatusProvider.java    License: Apache License 2.0 5 votes vote down vote up
static List<ModelProblem> runMavenValidationImpl(final File pom) {
    MavenEmbedder embedder = EmbedderFactory.getProjectEmbedder();
    MavenExecutionRequest meReq = embedder.createMavenExecutionRequest();
    ProjectBuildingRequest req = meReq.getProjectBuildingRequest();
    req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0); // 3.1 currently enables just <reporting> warning, see issue 223562 for details on why it's bad to show.
    req.setLocalRepository(embedder.getLocalRepository());
    List<ArtifactRepository> remoteRepos = RepositoryPreferences.getInstance().remoteRepositories(embedder);
    req.setRemoteRepositories(remoteRepos);
    req.setRepositorySession(((DefaultMaven) embedder.lookupComponent(Maven.class)).newRepositorySession(meReq));
    List<ModelProblem> problems;
    try {
        problems = embedder.lookupComponent(ProjectBuilder.class).build(pom, req).getProblems();
    } catch (ProjectBuildingException x) {
        problems = new ArrayList<ModelProblem>();
        List<ProjectBuildingResult> results = x.getResults();
        if (results != null) { //one code point throwing ProjectBuildingException contains results,
            for (ProjectBuildingResult result : results) {
                problems.addAll(result.getProblems());
            }
        } else {
            // another code point throwing ProjectBuildingException doesn't contain results..
            Throwable cause = x.getCause();
            if (cause instanceof ModelBuildingException) {
                problems.addAll(((ModelBuildingException) cause).getProblems());
            }
        }
    }
    List<ModelProblem> toRet = new LinkedList<ModelProblem>();
    for (ModelProblem problem : problems) {
        if(ModelUtils.checkByCLIMavenValidationLevel(problem)) {
            toRet.add(problem);
        }
    }
    return toRet;
}
 
Example 21
public void cacheArtifact(Artifact artifact)
    throws IOException, SettingsBuildingException,
    DependencyCollectionException, DependencyResolutionException,
    ArtifactResolutionException, ModelBuildingException {

  // setup a maven resolution hierarchy that uses the main local repo as
  // a remote repo and then cache into a new local repo
  List<RemoteRepository> repos = Utils.getRepositoryList();
  RepositorySystem repoSystem = Utils.getRepositorySystem();
  DefaultRepositorySystemSession repoSession =
      Utils.getRepositorySession(repoSystem, null);

  // treat the usual local repository as if it were a remote, ignoring checksum
  // failures as the local repo doesn't have checksums as a rule
  RemoteRepository localAsRemote =
      new RemoteRepository.Builder("localAsRemote", "default",
          repoSession.getLocalRepository().getBasedir().toURI().toString())
              .setPolicy(new RepositoryPolicy(true,
                      RepositoryPolicy.UPDATE_POLICY_NEVER,
                      RepositoryPolicy.CHECKSUM_POLICY_IGNORE))
              .build();

  repos.add(0, localAsRemote);

  repoSession.setLocalRepositoryManager(repoSystem.newLocalRepositoryManager(
      repoSession, new LocalRepository(head.getAbsolutePath())));

  Dependency dependency = new Dependency(artifact, "runtime");

  CollectRequest collectRequest = new CollectRequest(dependency, repos);

  DependencyNode node =
      repoSystem.collectDependencies(repoSession, collectRequest).getRoot();

  DependencyRequest dependencyRequest = new DependencyRequest();
  dependencyRequest.setRoot(node);

  repoSystem.resolveDependencies(repoSession, dependencyRequest);

}
 
Example 22
Source Project: IJava   Source File: MavenResolver.java    License: MIT License 5 votes vote down vote up
private void addPomReposToIvySettings(IvySettings settings, File pomFile) throws ModelBuildingException {
    Model mavenModel = Maven.getInstance().readEffectiveModel(pomFile).getEffectiveModel();
    ChainResolver pomRepos = MavenToIvy.createChainForModelRepositories(mavenModel);
    pomRepos.setName(DEFAULT_RESOLVER_NAME);

    settings.addResolver(pomRepos);
    settings.setDefaultResolver(DEFAULT_RESOLVER_NAME);
}
 
Example 23
Source Project: IJava   Source File: MavenResolver.java    License: MIT License 5 votes vote down vote up
@LineMagic
public void loadFromPOM(List<String> args) {
    if (args.isEmpty())
        throw new IllegalArgumentException("Loading from POM requires at least the path to the POM file");

    MagicsArgs schema = MagicsArgs.builder()
            .required("pomPath")
            .varargs("scopes")
            .flag("verbose", 'v')
            .onlyKnownKeywords().onlyKnownFlags().build();

    Map<String, List<String>> vals = schema.parse(args);

    String pomPath = vals.get("pomPath").get(0);
    List<String> scopes = vals.get("scopes");
    int verbosity = vals.get("verbose").size();

    File pomFile = new File(pomPath);
    try {
        Ivy ivy = this.createDefaultIvyInstance(verbosity);
        IvySettings settings = ivy.getSettings();

        File ivyFile = this.convertPomToIvy(ivy, pomFile);

        this.addPomReposToIvySettings(settings, pomFile);

        this.addJarsToClasspath(
                this.resolveFromIvyFile(ivy, ivyFile, scopes).stream()
                        .map(File::getAbsolutePath)
                        ::iterator
        );
    } catch (IOException | ParseException | ModelBuildingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 24
/**
 * @return ModelBuilderThreadSafetyWorkaround with a reduced scope for this simple test
 */
private ModelBuilderThreadSafetyWorkaround buildModelBuilderThreadSafetyWorkaroundForTest()
{
    return new ModelBuilderThreadSafetyWorkaround() {
        @Override
        public ModelBuildingResult build(ModelBuildingRequest buildingRequest, ProfileInjector customInjector, ProfileSelector customSelector)
                throws ModelBuildingException {

            return new DefaultModelBuilderFactory().newInstance()
                .setProfileInjector( customInjector )
                .setProfileSelector( customSelector )
                .build( buildingRequest );
        }
    };
}
 
Example 25
Source Project: furnace   Source File: ProjectHelper.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public Model loadPomFromFile(File pomFile, String... profiles)
{
   RepositorySystem system = mavenContainer.getRepositorySystem();
   Settings settings = mavenContainer.getSettings();
   DefaultRepositorySystemSession session = mavenContainer.setupRepoSession(system, settings);
   final DefaultModelBuildingRequest request = new DefaultModelBuildingRequest()
            .setSystemProperties(System.getProperties())
            .setPomFile(pomFile)
            .setActiveProfileIds(settings.getActiveProfiles());
   ModelBuilder builder = new DefaultModelBuilderFactory().newInstance();
   ModelBuildingResult result;
   try
   {
      request.setModelResolver(new MavenModelResolver(system, session,
               MavenRepositories.getRemoteRepositories(mavenContainer, settings)));
      result = builder.build(request);
   }
   // wrap exception message
   catch (ModelBuildingException e)
   {
      String pomPath = request.getPomFile().getAbsolutePath();
      StringBuilder sb = new StringBuilder("Found ").append(e.getProblems().size())
               .append(" problems while building POM model from ").append(pomPath).append("\n");

      int counter = 1;
      for (ModelProblem problem : e.getProblems())
      {
         sb.append(counter++).append("/ ").append(problem).append("\n");
      }

      throw new RuntimeException(sb.toString());
   }
   return result.getEffectiveModel();
}
 
Example 26
Source Project: buck   Source File: Resolver.java    License: Apache License 2.0 5 votes vote down vote up
private Model loadPomModel(Path pomFile) {
  DefaultModelBuildingRequest request = new DefaultModelBuildingRequest();
  request.setPomFile(pomFile.toFile());
  try {
    ModelBuildingResult result = modelBuilder.build(request);
    return result.getRawModel();
  } catch (ModelBuildingException | IllegalArgumentException e) {
    // IllegalArg can be thrown if the parent POM cannot be resolved.
    throw new RuntimeException(e);
  }
}
 
Example 27
Source Project: buck   Source File: Pom.java    License: Apache License 2.0 5 votes vote down vote up
private Model constructModel(File file, Model model) {
  ModelBuilder modelBuilder = MODEL_BUILDER_FACTORY.newInstance();

  try {
    ModelBuildingRequest req = new DefaultModelBuildingRequest().setPomFile(file);
    ModelBuildingResult modelBuildingResult = modelBuilder.build(req);

    Model constructed = Objects.requireNonNull(modelBuildingResult.getRawModel());

    return merge(model, constructed);
  } catch (ModelBuildingException e) {
    throw new RuntimeException(e);
  }
}
 
Example 28
Source Project: cloud-opensource-java   Source File: LinkageMonitor.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns a map from versionless coordinates to version for all pom.xml found in {@code
 * projectDirectory}.
 */
@VisibleForTesting
static ImmutableMap<String, String> findLocalArtifacts(
    RepositorySystem repositorySystem, RepositorySystemSession session, Path projectDirectory) {
  ImmutableMap.Builder<String, String> artifactToVersion = ImmutableMap.builder();
  Iterable<Path> paths = MoreFiles.fileTraverser().breadthFirst(projectDirectory);

  for (Path path : paths) {
    if (!path.getFileName().endsWith("pom.xml")) {
      continue;
    }

    // This path element check should not depend on directory name outside the project
    Path relativePath = path.isAbsolute() ? projectDirectory.relativize(path) : path;
    ImmutableSet<Path> elements = ImmutableSet.copyOf(relativePath);
    if (elements.contains(Paths.get("build")) || elements.contains(Paths.get("target"))) {
      // Exclude Gradle's build directory and Maven's target directory, which would contain irrelevant pom.xml such as
      // gax/build/tmp/expandedArchives/(... omit ...)/META-INF/maven/org.jacoco/org.jacoco.agent/pom.xml
      continue;
    }

    ModelBuildingRequest modelRequest = new DefaultModelBuildingRequest();
    modelRequest.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
    modelRequest.setProcessPlugins(false);
    modelRequest.setTwoPhaseBuilding(false);
    modelRequest.setPomFile(path.toFile());
    modelRequest.setModelResolver(
        new ProjectModelResolver(
            session,
            null,
            repositorySystem,
            new DefaultRemoteRepositoryManager(),
            ImmutableList.of(CENTRAL), // Needed when parent pom is not locally available
            null,
            null));
    // Profile activation needs JDK version through system properties
    // https://github.com/GoogleCloudPlatform/cloud-opensource-java/issues/923
    modelRequest.setSystemProperties(System.getProperties());

    try {
      ModelBuildingResult modelBuildingResult = modelBuilder.build(modelRequest);
      Model model = modelBuildingResult.getEffectiveModel();
      artifactToVersion.put(model.getGroupId() + ":" + model.getArtifactId(), model.getVersion());
    } catch (ModelBuildingException ex) {
      // Maven may fail to build pom.xml files found in irrelevant directories, such as "target"
      // and "test" directories of the project. Such failures can be ignored.
      logger.info("Ignoring bad model: " + path + ": " + ex.getMessage());
    }
  }
  return artifactToVersion.build();
}
 
Example 29
Source Project: cloud-opensource-java   Source File: LinkageMonitor.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns new problems in the BOM specified by {@code groupId} and {@code artifactId}. This
 * method compares the latest release of the BOM and its snapshot version which uses artifacts in
 * {@link #localArtifacts}.
 */
private ImmutableSet<SymbolProblem> run(String groupId, String artifactId)
    throws RepositoryException, IOException, MavenRepositoryException, ModelBuildingException {
  String latestBomCoordinates =
      RepositoryUtility.findLatestCoordinates(repositorySystem, groupId, artifactId);
  logger.info("BOM Coordinates: " + latestBomCoordinates);
  Bom baseline = Bom.readBom(latestBomCoordinates);
  ImmutableSet<SymbolProblem> problemsInBaseline =
      LinkageChecker.create(baseline, null).findSymbolProblems().keySet();
  Bom snapshot = copyWithSnapshot(repositorySystem, session, baseline, localArtifacts);

  // Comparing coordinates because DefaultArtifact does not override equals
  ImmutableList<String> baselineCoordinates = coordinatesList(baseline.getManagedDependencies());
  ImmutableList<String> snapshotCoordinates = coordinatesList(snapshot.getManagedDependencies());
  if (baselineCoordinates.equals(snapshotCoordinates)) {
    logger.info(
        "Snapshot is same as baseline. Not running comparison.");
    logger.info(
        "Baseline coordinates: " + Joiner.on(";").join(baselineCoordinates));
    return ImmutableSet.of();
  }

  ImmutableList<Artifact> snapshotManagedDependencies = snapshot.getManagedDependencies();
  ClassPathResult classPathResult = (new ClassPathBuilder()).resolve(snapshotManagedDependencies);
  ImmutableList<ClassPathEntry> classpath = classPathResult.getClassPath();
  List<ClassPathEntry> entryPointJars = classpath.subList(0, snapshotManagedDependencies.size());

  ImmutableSetMultimap<SymbolProblem, ClassFile> snapshotSymbolProblems =
      LinkageChecker.create(classpath, ImmutableSet.copyOf(entryPointJars), null)
          .findSymbolProblems();
  ImmutableSet<SymbolProblem> problemsInSnapshot = snapshotSymbolProblems.keySet();

  if (problemsInBaseline.equals(problemsInSnapshot)) {
    logger.info(
        "Snapshot versions have the same " + problemsInBaseline.size() + " errors as baseline");
    return ImmutableSet.of();
  }

  Set<SymbolProblem> fixedProblems = Sets.difference(problemsInBaseline, problemsInSnapshot);
  if (!fixedProblems.isEmpty()) {
    logger.info(messageForFixedErrors(fixedProblems));
  }

  Set<SymbolProblem> newProblems = Sets.difference(problemsInSnapshot, problemsInBaseline);
  if (!newProblems.isEmpty()) {
    logger.severe(
        messageForNewErrors(snapshotSymbolProblems, problemsInBaseline, classPathResult));
  }
  return ImmutableSet.copyOf(newProblems);
}
 
Example 30
Source Project: quarkus   Source File: MavenModelBuilder.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public ModelBuildingResult build(ModelBuildingRequest request, ModelBuildingResult result) throws ModelBuildingException {
    return builder.build(request, result);
}