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

The following examples show how to use org.apache.maven.model.building.ModelBuildingException. 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 File: LinkageMonitor.java    From cloud-opensource-java with 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 File: MavenEmbedder.java    From netbeans with 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 #3
Source File: NBModelBuilder.java    From netbeans with 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 #4
Source File: ModelBuilderThreadSafetyWorkaround.java    From flatten-maven-plugin with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: LinkageMonitorTest.java    From cloud-opensource-java with 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 #6
Source File: MavenHelper.java    From repairnator with 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 #7
Source File: EmbedderFactoryTest.java    From netbeans with 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 #8
Source File: MavenModelBuilder.java    From quarkus with 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 #9
Source File: MavenResolver.java    From IJava with 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 #10
Source File: MavenEmbedder.java    From netbeans with 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 #11
Source File: StatusProvider.java    From netbeans with 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 #12
Source File: SimpleMavenCache.java    From gate-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #13
Source File: POMModelPanel.java    From netbeans with 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 #14
Source File: MavenResolver.java    From IJava with 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 #15
Source File: CreateEffectivePomTest.java    From flatten-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * @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 #16
Source File: ProjectHelper.java    From furnace with 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 #17
Source File: Resolver.java    From buck with 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 #18
Source File: Pom.java    From buck with 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 #19
Source File: EffectivePomMD.java    From netbeans with 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 #20
Source File: LinkageMonitor.java    From cloud-opensource-java with 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 #21
Source File: VersionSubstitutingModelResolverTest.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
@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 #22
Source File: LinkageMonitorTest.java    From cloud-opensource-java with 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 #23
Source File: LinkageMonitorTest.java    From cloud-opensource-java with 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 #24
Source File: LinkageMonitorTest.java    From cloud-opensource-java with 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 #25
Source File: LinkageMonitorTest.java    From cloud-opensource-java with 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 #26
Source File: NbMavenProjectImpl.java    From netbeans with 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 #27
Source File: POMInheritancePanel.java    From netbeans with 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 #28
Source File: MavenModelBuilder.java    From quarkus with 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);
}
 
Example #29
Source File: OSGILookupProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void checkContent(Project prj, InstanceContent ic, AccessQueryImpl access, ForeignClassBundlerImpl bundler, RecommendedTemplates templates) {
    NbMavenProject nbprj = prj.getLookup().lookup(NbMavenProject.class);
    String effPackaging = nbprj.getPackagingType();
    
    boolean needToCheckFelixProjectTypes = true;
    if(!nbprj.isMavenProjectLoaded()) { 
        // issue #262646 
        // due to unfortunate ProjectManager.findPorjetc calls in awt, 
        // speed is essential during project init, so lets try to avoid
        // maven project loading if we can get the info faster from raw model.
        needToCheckFelixProjectTypes = false;
        Model model;
        try {
            model = nbprj.getRawModel();
        } catch (ModelBuildingException ex) {
            // whatever happend, we can't use the model, 
            // lets try to follow up with loading the maven project
            model = null;
            Logger.getLogger(OSGILookupProvider.class.getName()).log(Level.FINE, null, ex);
        }
        Build build = model != null ? model.getBuild() : null;
        List<Plugin> plugins = build != null ? build.getPlugins() : null;
        if(plugins != null) {
            for (Plugin plugin : plugins) {
                if(OSGiConstants.GROUPID_FELIX.equals(plugin.getGroupId()) && OSGiConstants.ARTIFACTID_BUNDLE_PLUGIN.equals(plugin.getArtifactId())) {
                    needToCheckFelixProjectTypes = true;
                    break;
                }
            }
        } 
    }
    if(needToCheckFelixProjectTypes) {
        String[] types = PluginPropertyUtils.getPluginPropertyList(prj, OSGiConstants.GROUPID_FELIX, OSGiConstants.ARTIFACTID_BUNDLE_PLUGIN, "supportedProjectTypes", "supportedProjectType", /*"bundle" would not work for GlassFish parent POM*/null);
        if (types != null) {
            for (String type : types) {
                if (effPackaging.equals(type)) {
                    effPackaging = NbMavenProject.TYPE_OSGI;
                }
            }
        }
    }
    if (NbMavenProject.TYPE_OSGI.equals(effPackaging)) {
        ic.add(access);
        ic.add(bundler);
        ic.add(templates);
    } else {
        ic.remove(access);
        ic.remove(bundler);
        ic.remove(templates);
    }
}
 
Example #30
Source File: MavenToIvy.java    From IJava with MIT License 4 votes vote down vote up
public static List<DependencyResolver> getRepositoriesFromModel(CharSequence pom) throws ModelBuildingException {
    return MavenToIvy.getRepositoriesFromModel(Maven.getInstance().readEffectiveModel(pom).getEffectiveModel());
}