Java 类org.apache.maven.model.Model 实例源码

项目:Reer    文件:CustomModelBuilder.java   
public CustomModelBuilder(Model model) {
    ExecuteManager executeManager = new ExecuteManagerImpl();
    setProp(executeManager.getClass(), executeManager, "log",
            new PlexusLoggerAdapter(LoggerFactory.getLogger(ExecuteManagerImpl.class)));
    setProp(ModelBuilder.class, this, "executeManager", executeManager);
    setProp(ModelBuilder.class, this, "log",
            new PlexusLoggerAdapter(LoggerFactory.getLogger(ModelBuilder.class)));
    try {
        initialize();
    } catch (InitializationException e) {
        throw new RuntimeException(e);
    }
    Map factories = (Map) getProp(FactoryBuilderSupport.class, this, "factories");
    factories.remove("project");
    ModelFactory modelFactory = new ModelFactory(model);
    registerFactory(modelFactory.getName(), null, modelFactory);
}
项目:smart-testing    文件:DependencyResolver.java   
private void addStrategies(Model model) {

        final StrategyDependencyResolver strategyDependencyResolver = new StrategyDependencyResolver(configuration.getCustomStrategies());
        final Map<String, Dependency> dependencies = strategyDependencyResolver.resolveDependencies();
        final List<String> errorMessages = new ArrayList<>();

        configuration.autocorrectStrategies(dependencies.keySet(), errorMessages);
        errorMessages.forEach(msg -> LOGGER.error(msg));
        if (!errorMessages.isEmpty()) {
            throw new IllegalStateException("Unknown strategies (see above). Please refer to http://arquillian.org/smart-testing/#_strategies "
                + "for the list of available strategies.");
        }
        final String[] strategies = configuration.getStrategies();
        Arrays.stream(strategies).forEach(strategy -> {
            final Dependency dependency = dependencies.get(strategy);
            model.addDependency(dependency);
        });
        configuration.loadStrategyConfigurations(strategies);
    }
项目:smart-testing    文件:CustomProvidersTest.java   
@Test
public void should_remove_custom_provider_dependency_and_create_info_file_when_set_in_config() {
    // given
    Configuration config = ConfigurationLoader.load(tmpFolder);
    config.setCustomProviders(new String[] {"org.foo.provider:my-custom-provider=org.foo.impl.SurefireProvider"});
    DependencyResolver dependencyResolver = new DependencyResolver(config);
    Dependency customDep = createDependency("org.foo.provider", "my-custom-provider", "1.2.3");
    Model model = Mockito.mock(Model.class);
    Plugin plugin = prepareModelWithPluginDep(model, customDep);

    // when
    dependencyResolver.removeAndRegisterFirstCustomProvider(model, plugin);

    // then
    verifyDependencyIsRemovedAndFileCreated(plugin, customDep, "org.foo.impl.SurefireProvider");
}
项目:incubator-netbeans    文件:MavenEmbedder.java   
/**
     * 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;
    }
项目:incubator-netbeans    文件:NBModelBuilder.java   
@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;
}
项目:apache-maven-shade-plugin    文件:PomWriter.java   
public static void write( Writer w, Model newModel, boolean namespaceDeclaration )
    throws IOException
{
    Element root = new Element( "project" );

    if ( namespaceDeclaration )
    {
        String modelVersion = newModel.getModelVersion();

        Namespace pomNamespace = Namespace.getNamespace( "", "http://maven.apache.org/POM/" + modelVersion );

        root.setNamespace( pomNamespace );

        Namespace xsiNamespace = Namespace.getNamespace( "xsi", "http://www.w3.org/2001/XMLSchema-instance" );

        root.addNamespaceDeclaration( xsiNamespace );

        if ( root.getAttribute( "schemaLocation", xsiNamespace ) == null )
        {
            root.setAttribute( "schemaLocation",
                               "http://maven.apache.org/POM/" + modelVersion + " http://maven.apache.org/maven-v"
                                   + modelVersion.replace( '.', '_' ) + ".xsd", xsiNamespace );
        }
    }

    Document doc = new Document( root );

    MavenJDOMWriter writer = new MavenJDOMWriter();

    String encoding = newModel.getModelEncoding() != null ? newModel.getModelEncoding() : "UTF-8";

    Format format = Format.getPrettyFormat().setEncoding( encoding );

    writer.write( newModel, doc, w, format );
}
项目:butterfly    文件:ModelTree.java   
/**
     * This is a tree of Maven artifacts, which are represented by {@link Model} objects.
     * The idea here is, given a list of Maven pom.xml {@link File} objects, create a tree
     * based on dependency among them, but specifying explicitly which Maven artifact should
     * be at the root of the tree. That means, if any artifact in the list is not a child,
     * directly or indirectly, of the root artifact, then it will end up no being in the tree.
     * <br>
     * As a result of building this tree, it is possible to know, out of the initial pom.xml files list,
     * which ones actually inherit, directly or not, from the root artifact. The result is retrieved
     * by calling {@link #getPomFilesInTree()}
     *
     * @param rootGroupId the group id of the artifact that should be at the root of the tree
     * @param rootArtifactId the artifact id of the artifact that should be at the root of the tree
     * @param rootVersion the version of the artifact that should be at the root of the tree
     * @param pomFiles a list of pom.xml files used to make the tree
     */
    public ModelTree(String rootGroupId, String rootArtifactId, String rootVersion, List<File> pomFiles) {
        Model rootModel = new Model();
        rootModel.setGroupId(rootGroupId);
        rootModel.setArtifactId(rootArtifactId);
        rootModel.setVersion(rootVersion);

        List<Model> models = new ArrayList<>();
        models.add(rootModel);

        for (File pomFile : pomFiles) {
            models.add(createModel(pomFile));
        }

// TODO we can comment this out in the future if we need this feature
//        modelsNotInTree = add(models);
        add(models);
    }
项目:butterfly    文件:PomChangeParentTest.java   
@Test
public void changeVersionTest() throws IOException, XmlPullParserException {
    Model pomModelBeforeChange = getOriginalPomModel("pom.xml");
    assertEquals(pomModelBeforeChange.getParent().getVersion(), "1.0");

    PomChangeParent pomChangeParent = new PomChangeParent("2.0").relative("pom.xml");

    assertNull(pomChangeParent.getGroupId());
    assertNull(pomChangeParent.getArtifactId());
    assertEquals(pomChangeParent.getVersion(), "2.0");

    TOExecutionResult executionResult = pomChangeParent.execution(transformedAppFolder, transformationContext);
    assertEquals(executionResult.getType(), TOExecutionResult.Type.SUCCESS);
    assertEquals(pomChangeParent.getDescription(), "Change parent artifact in POM file pom.xml");
    assertNull(executionResult.getException());

    Model pomModelAfterChange = getTransformedPomModel("pom.xml");
    assertEquals(pomModelAfterChange.getParent().getVersion(), "2.0");
}
项目:butterfly    文件:PomChangeParentTest.java   
@Test
public void changeParentTest() throws IOException, XmlPullParserException {
    Model pomModelBeforeChange = getOriginalPomModel("pom.xml");

    assertEquals(pomModelBeforeChange.getParent().getGroupId(), "com.test");
    assertEquals(pomModelBeforeChange.getParent().getArtifactId(), "foo-parent");
    assertEquals(pomModelBeforeChange.getParent().getVersion(), "1.0");

    PomChangeParent pomChangeParent = new PomChangeParent().setGroupId("com.newgroupid").setArtifactId("newartifactid").setVersion("2.0").relative("pom.xml");

    assertEquals(pomChangeParent.getGroupId(), "com.newgroupid");
    assertEquals(pomChangeParent.getArtifactId(), "newartifactid");
    assertEquals(pomChangeParent.getVersion(), "2.0");


    TOExecutionResult executionResult = pomChangeParent.execution(transformedAppFolder, transformationContext);
    assertEquals(executionResult.getType(), TOExecutionResult.Type.SUCCESS);
    assertEquals(pomChangeParent.getDescription(), "Change parent artifact in POM file pom.xml");
    assertNull(executionResult.getException());

    Model pomModelAfterChange = getTransformedPomModel("pom.xml");
    assertEquals(pomModelAfterChange.getParent().getGroupId(), "com.newgroupid");
    assertEquals(pomModelAfterChange.getParent().getArtifactId(), "newartifactid");
    assertEquals(pomModelAfterChange.getParent().getVersion(), "2.0");
}
项目:butterfly    文件:PomChangeParentTest.java   
@Test
public void failTest() throws IOException, XmlPullParserException, CloneNotSupportedException {
    Model pomModelBeforeChange = getOriginalPomModel("/src/main/resources/no_parent_pom.xml");
    assertNull(pomModelBeforeChange.getParent());

    PomChangeParent pomChangeParent = new PomChangeParent("2.0").relative("/src/main/resources/no_parent_pom.xml");

    assertNull(pomChangeParent.getGroupId());
    assertNull(pomChangeParent.getArtifactId());
    assertEquals(pomChangeParent.getVersion(), "2.0");

    TOExecutionResult executionResult = pomChangeParent.execution(transformedAppFolder, transformationContext);
    assertEquals(executionResult.getType(), TOExecutionResult.Type.ERROR);
    assertEquals(pomChangeParent.getDescription(), "Change parent artifact in POM file /src/main/resources/no_parent_pom.xml");
    assertEquals(executionResult.getException().getClass(), TransformationOperationException.class);
    assertEquals(executionResult.getException().getMessage(), "Pom file /src/main/resources/no_parent_pom.xml does not have a parent");

    Model pomModelAfterChange = getTransformedPomModel("/src/main/resources/no_parent_pom.xml");
    assertNull(pomModelAfterChange.getParent());

    executionResult = pomChangeParent.clone().failIfNotPresent().execution(transformedAppFolder, transformationContext);
    assertEquals(executionResult.getType(), TOExecutionResult.Type.ERROR);
}
项目:butterfly    文件:PomChangeParentTest.java   
@Test
public void invalidOperationTest() throws IOException, XmlPullParserException {
    // You have to either set the version only, or the group id AND artifact id AND version.
    // Here only the group id is being set
    PomChangeParent pomChangeParent = new PomChangeParent().setGroupId("com.test").relative("pom.xml");

    assertEquals(pomChangeParent.getGroupId(), "com.test");
    assertNull(pomChangeParent.getArtifactId());
    assertNull(pomChangeParent.getVersion());

    TOExecutionResult executionResult = pomChangeParent.execution(transformedAppFolder, transformationContext);
    assertEquals(executionResult.getType(), TOExecutionResult.Type.ERROR);
    assertEquals(pomChangeParent.getDescription(), "Change parent artifact in POM file pom.xml");
    assertEquals(executionResult.getException().getClass(), TransformationOperationException.class);
    assertEquals(executionResult.getException().getMessage(), "Invalid POM parent transformation operation");

    Model pomModelAfterChange = getTransformedPomModel("pom.xml");
    assertEquals(pomModelAfterChange.getParent().getGroupId(), "com.test");
    assertEquals(pomModelAfterChange.getParent().getArtifactId(), "foo-parent");
    assertEquals(pomModelAfterChange.getParent().getVersion(), "1.0");
}
项目:butterfly    文件:PomAddPluginTest.java   
@Test
public void addPluginWithVersionTest() throws IOException, XmlPullParserException {
    Model pomModelBeforeChange = getOriginalPomModel("pom.xml");
    assertEquals(pomModelBeforeChange.getBuild().getPlugins().size(), 1);
    assertEquals(pomModelBeforeChange.getBuild().getPlugins().get(0).getGroupId(), "org.codehaus.mojo");
    assertEquals(pomModelBeforeChange.getBuild().getPlugins().get(0).getArtifactId(), "cobertura-maven-plugin");

       PomAddPlugin pomAddPlugin = new PomAddPlugin("org.apache.maven.plugins", "maven-javadoc-plugin", "2.10.4").relative("pom.xml");
    TOExecutionResult executionResult = pomAddPlugin.execution(transformedAppFolder, transformationContext);
    assertEquals(executionResult.getType(), TOExecutionResult.Type.SUCCESS);

    Model pomModelAfterChange = getTransformedPomModel("pom.xml");
    assertEquals(pomModelAfterChange.getBuild().getPlugins().size(), 2);
       Plugin plugin = new Plugin();
       plugin.setGroupId("org.apache.maven.plugins");
       plugin.setArtifactId("maven-javadoc-plugin");
       assertTrue(pomModelAfterChange.getBuild().getPlugins().contains(plugin));
       assertEquals(pomModelAfterChange.getBuild().getPluginsAsMap().get("org.apache.maven.plugins:maven-javadoc-plugin").getVersion(), "2.10.4");
}
项目:butterfly    文件:PomAddPluginTest.java   
@Test
public void defaultIfPresentTest() throws IOException, XmlPullParserException {
    Model pomModelBeforeChange = getOriginalPomModel("pom.xml");
    assertEquals(pomModelBeforeChange.getBuild().getPlugins().size(), 1);
    assertEquals(pomModelBeforeChange.getBuild().getPlugins().get(0).getGroupId(), "org.codehaus.mojo");
    assertEquals(pomModelBeforeChange.getBuild().getPlugins().get(0).getArtifactId(), "cobertura-maven-plugin");

    // Trying to add the same plugin
    PomAddPlugin pomAddPlugin = new PomAddPlugin().setArtifact("org.codehaus.mojo:cobertura-maven-plugin").relative("pom.xml");
    TOExecutionResult executionResult = pomAddPlugin.execution(transformedAppFolder, transformationContext);
    assertEquals(executionResult.getType(), TOExecutionResult.Type.ERROR);
    assertNull(executionResult.getDetails());
    assertEquals(executionResult.getException().getMessage(), "Plugin org.codehaus.mojo:cobertura-maven-plugin is already present in pom.xml");

    Model pomModelAfterChange = getTransformedPomModel("pom.xml");
    assertEquals(pomModelAfterChange.getBuild().getPlugins().size(), 1);
    assertEquals(pomModelAfterChange.getBuild().getPlugins().size(), 1);
    assertEquals(pomModelAfterChange.getBuild().getPlugins().get(0).getGroupId(), "org.codehaus.mojo");
    assertEquals(pomModelAfterChange.getBuild().getPlugins().get(0).getArtifactId(), "cobertura-maven-plugin");
}
项目:migration-tooling    文件:DefaultModelResolver.java   
public Model getEffectiveModel(ModelSource modelSource) {
  DefaultModelBuildingRequest request = new DefaultModelBuildingRequest();
  request.setModelResolver(this);
  request.setModelSource(modelSource);
  Model model;
  try {
    ModelBuildingResult result = modelBuilder.build(request);
    model = result.getEffectiveModel();
  } catch (ModelBuildingException | IllegalArgumentException e) {
    // IllegalArg can be thrown if the parent POM cannot be resolved.
    logger.warning(
        "Unable to resolve Maven model from "
            + modelSource.getLocation()
            + ": "
            + e.getMessage());
    return null;
  }
  return model;
}
项目:migration-tooling    文件:ResolverTest.java   
@Test
public void scopesHonoredForRoot() throws Exception {
  Model mockModel = mock(Model.class);
  // Only "compile" should go through.
  when(mockModel.getDependencies())
      .thenReturn(
          ImmutableList.of(
              getDependency("a:b:1.0", "compile"), getDependency("c:d:1.0", "test")));

  Aether aether = mock(Aether.class);
  when(aether.requestVersionRange(fromCoords("a:b:[1.0,)"))).thenReturn(newArrayList("1.0"));
  when(aether.requestVersionRange(fromCoords("c:d:[1.0,)"))).thenReturn(newArrayList("1.0"));
  VersionResolver versionResolver = new VersionResolver(aether);

  Resolver resolver = new Resolver(mock(DefaultModelResolver.class), versionResolver, ALIASES);

  resolver.traverseDeps(mockModel, Sets.newHashSet("compile"), Sets.newHashSet(), null);
  Collection<Rule> rules = resolver.getRules();
  assertThat(rules).hasSize(1);
  Rule actual = rules.iterator().next();
  assertThat(actual.name()).isEqualTo("a_b");
}
项目:migration-tooling    文件:ResolverTest.java   
@Test
public void aliasWins() throws Exception {
  Aether aether = mock(Aether.class);
  when(aether.requestVersionRange(fromCoords("a:b:[1.0,)"))).thenReturn(newArrayList("1.0"));
  VersionResolver versionResolver = new VersionResolver(aether);

  Rule aliasedRule = new Rule(fromCoords("a:b:0"), "c");
  Model mockModel = mock(Model.class);
  when(mockModel.getDependencies()).thenReturn(ImmutableList.of(getDependency("a:b:1.0")));

  Resolver resolver =
      new Resolver(
          mock(DefaultModelResolver.class), versionResolver, ImmutableList.of(aliasedRule));
  resolver.traverseDeps(
      mockModel,
      Sets.newHashSet(),
      Sets.newHashSet(),
      new Rule(new DefaultArtifact("par:ent:1.2.3")));
  Collection<Rule> rules = resolver.getRules();
  assertThat(rules).hasSize(2);
  rules.iterator().next();
  Rule actualRule = rules.iterator().next();
  assertThat(actualRule).isSameAs(aliasedRule);
}
项目:neoscada    文件:VisitorChange.java   
@Override
public void visit ( final MavenProject project ) throws IOException
{
    this.changeManager.addChange ( project.getFile (), new ModelModifier () {

        @Override
        public boolean apply ( final Model model )
        {
            return performChange ( model );
        }

        @Override
        public String toString ()
        {
            return VisitorChange.this.toString ();
        };
    } );
}
项目:smart-testing    文件:SmartTestingMavenConfigurer.java   
private void purgeLocalStorageAndExportPom(MavenSession session) {
    session.getAllProjects().forEach(mavenProject -> {
        Model model = mavenProject.getModel();
        boolean isDebug = configuration.isDebug() || mavenLogger.isDebugEnabled();
        String target = model.getBuild() != null ? model.getBuild().getDirectory() : null;

        new LocalStorage(model.getProjectDirectory()).duringExecution().purge(target);
        if (isDebug && new File(target).exists()) {
            ModifiedPomExporter.exportModifiedPom(mavenProject.getModel());
        }
    });
}
项目:Reer    文件:AbstractMavenPublishAction.java   
protected AbstractMavenPublishAction(File pomFile, List<File> wagonJars) {
    container = newPlexusContainer(wagonJars);
    session = new MavenRepositorySystemSession();
    session.setTransferListener(new LoggingMavenTransferListener());
    session.getConfigProperties().put("maven.metadata.legacy", "true");

    Model pom = parsePom(pomFile);
    pomArtifact = new DefaultArtifact(pom.getGroupId(), pom.getArtifactId(), "pom", pom.getVersion()).setFile(pomFile);
    mainArtifact = createTypedArtifact(pom.getPackaging(), null);
}
项目:spring-cloud-release-tools    文件:PomUpdater.java   
private List<VersionChange> updateParentIfPossible(ModelWrapper wrapper, Versions versions,
        Model model, List<VersionChange> sourceChanges) {
    String rootProjectName = wrapper.projectName();
    String rootProjectGroupId = wrapper.groupId();
    List<VersionChange> changes = new ArrayList<>(sourceChanges);
    if (model.getParent() == null || isEmpty(model.getParent().getVersion())) {
        log.debug("Can't set the value for parent... Will return {}", sourceChanges);
        return changes;
    }
    if (model.getGroupId() != null && !model.getGroupId().equals(rootProjectGroupId)) {
        log.info("Will not update the project's [{}] parent [{}] since its group id [{}] is not equal the parent group id [{}]",
                model.getArtifactId(), model.getParent().getArtifactId(), model.getGroupId(), rootProjectGroupId);
        return changes;
    }
    String parentGroupId = model.getParent().getGroupId();
    String parentArtifactId = model.getParent().getArtifactId();
    log.debug("Searching for a version of parent [{}:{}]", parentGroupId, parentArtifactId);
    String oldVersion = model.getParent().getVersion();
    String version = versions.versionForProject(parentArtifactId);
    log.debug("Found version is [{}]", version);
    if (isEmpty(version)) {
        if (hasText(model.getParent().getRelativePath())) {
            version = versions.versionForProject(rootProjectName);
        } else {
            log.warn("There is no info on the [{}:{}] version", parentGroupId, parentArtifactId);
            return changes;
        }
    }
    if (oldVersion.equals(version)) {
        log.debug("Won't update the version of parent [{}:{}] since you're already using the proper one", parentGroupId, parentArtifactId);
        return changes;
    }
    log.info("Setting version of parent [{}] to [{}] for module [{}]", parentArtifactId,
            version, model.getArtifactId());
    if (hasText(version)) {
        changes.add(new VersionChange(parentGroupId, parentArtifactId, oldVersion, version));
    }
    return changes;
}
项目:spring-cloud-release-tools    文件:ProjectVersion.java   
public ProjectVersion(File project) {
    PomReader pomReader = new PomReader();
    Model model = pomReader.readPom(project);
    this.projectName = nameWithoutParent(model.getArtifactId());
    this.version = model.getVersion();
    this.model = model;
}
项目:smart-testing    文件:MavenProjectConfigurator.java   
private List<Plugin> removePluginsThatAreSkipped(List<Plugin> testRunnerPluginConfigurations, Model model) {
    SkipModuleChecker skipModuleChecker = new SkipModuleChecker(model);
    if (skipModuleChecker.areAllTestsSkipped()) {
        return Collections.emptyList();
    }
    return testRunnerPluginConfigurations.stream()
        .filter(testRunnerPlugin -> !(ApplicablePlugins.FAILSAFE.hasSameArtifactId(testRunnerPlugin.getArtifactId())
            && skipModuleChecker.areIntegrationTestsSkipped()))
        .filter(testRunnerPlugin -> !(ApplicablePlugins.SUREFIRE.hasSameArtifactId(testRunnerPlugin.getArtifactId())
            && skipModuleChecker.areUnitTestsSkipped()))
        .collect(Collectors.toList());
}
项目:incubator-netbeans    文件:NbMavenProjectImpl.java   
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;
    }
}
项目:incubator-netbeans    文件:LocationAwareMavenXpp3Writer.java   
public List<Location> write(StringWriter writer, Model model)
        throws java.io.IOException {
    locations = new ArrayList<Location>();
    XmlSerializer serializer = new MXSerializer();
    serializer.setProperty("http://xmlpull.org/v1/doc/properties.html#serializer-indentation", "  ");
    serializer.setProperty("http://xmlpull.org/v1/doc/properties.html#serializer-line-separator", "\n");
    serializer.setOutput(writer);
    serializer.startDocument(model.getModelEncoding(), null);
    writeModel(model, "project", serializer);
    serializer.endDocument();
    return locations;
}
项目:incubator-netbeans    文件:POMInheritancePanel.java   
protected @Override Node createNodeForKey(Model mdl) {
    File fl = mdl.getPomFile();
    String version = mdl.getVersion();
    if (version == null && mdl.getParent() != null) {
        version = mdl.getParent().getVersion();
    }
    if (version == null) {
        return null;
    }
    if (fl == null) {
        ArtifactRepository repo = EmbedderFactory.getProjectEmbedder().getLocalRepository();
        DefaultArtifactHandler handler = new DefaultArtifactHandler();
        handler.setExtension("pom");
        String groupId = mdl.getGroupId();
        if (groupId == null && mdl.getParent() != null) {
            groupId = mdl.getParent().getGroupId();
        }
        assert groupId != null;
        fl = new File(repo.getBasedir(), repo.pathOf(new DefaultArtifact(groupId, mdl.getArtifactId(), version, null, "pom", null, handler)));
    }
    FileObject fo = FileUtil.toFileObject(FileUtil.normalizeFile(fl));
    if (fo != null) {
        try {
            return new POMNode(fl, mdl, DataObject.find(NodeUtils.readOnlyLocalRepositoryFile(fo)), version);
        } catch (DataObjectNotFoundException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    return null;
}
项目:incubator-netbeans    文件:POMInheritancePanel.java   
private POMNode(@NonNull File key, @NonNull Model mdl, @NonNull DataObject dobj, @NonNull String version) {
    super(Children.LEAF);
    setDisplayName(NbBundle.getMessage(POMInheritancePanel.class, "TITLE_PomNode", mdl.getArtifactId(), version));
    if (!dobj.getPrimaryFile().canWrite()) {
        //coming from repository
        readonly = true;
    }
    setShortDescription(key.getAbsolutePath());
    this.dobj = dobj;
}
项目:incubator-netbeans    文件:MavenEmbedder.java   
static void normalizePath(Model model) {
    if (model != null) {
        File f = model.getPomFile();
        if (f != null) {
            model.setPomFile(FileUtil.normalizeFile(f));
        }
    }
}
项目:incubator-netbeans    文件:NBModelBuilder.java   
/**
 *
 * @param effective model created by Project Maven Embedder.
 * @return 
 */
public static List<ModelDescription> getModelDescriptors(Model effective) {
    InputLocation loc = effective.getLocation(NETBEANS_MODELDESCS);
    if (loc != null && loc.getSource() instanceof ModelInputSource) {
        ModelInputSource mis = (ModelInputSource) loc.getSource();
        return mis.rawModels;
    }
    return null;
}
项目:textmd    文件:TextMd.java   
private void loadPomVariables() {
    logger.debug("Loading maven pom.xml variables");
    MavenXpp3Reader reader = new MavenXpp3Reader();
    try {
        Model model = reader.read(new FileReader("pom.xml"));
        ARTIFACT_ID = model.getArtifactId();
        VERSION = model.getVersion();
        NAME = model.getName();
        GROUP_ID = model.getGroupId();
    } catch (IOException | XmlPullParserException e) {
        e.printStackTrace();
    }
}
项目:deployment-recorder-extension    文件:PomReadTest.java   
@Test
public void shouldReturnVersion() throws IOException, XmlPullParserException {
    InputStream resourceAsStream = this.getClass().getResourceAsStream("/pom-without-parent.xml");
    PomRead pomRead = new PomRead();
    Model model = pomRead.readModel(resourceAsStream);
    String expectedVersion = pomRead.getPomVersion(model);
    assertThat(expectedVersion).isEqualTo("0.1.0-SNAPSHOT");
}
项目:butterfly    文件:ModelTree.java   
private List<Model> add(List<Model> models) {
    int previousTreeSize = -1;
    while (models.size() > 0 && size() > previousTreeSize) {
        previousTreeSize = size();
        List<Model> leftOverModels = models;
        models = new ArrayList<>();
        for (Model model : leftOverModels) {
            if (!add(model)) {
                models.add(model);
            }
        }
    }
    return models;
}
项目:butterfly    文件:ModelTree.java   
private boolean add(Model model) {
        ModelNode temp = null;
        if (rootNode == null) {
            rootNode = new ModelNode(model);
            nodesInTree.add(rootNode);
// TODO
// We can comment this out in the future if we want to allow
// not fixing the root artifact
//        } else if (rootNode.isChildOf(model)) {
//            temp = rootNode;
//            rootNode = new ModelNode(model);
//            rootNode.addChild(temp);
//            nodesInTree.add(rootNode);
        } else {
            for (ModelNode n : nodesInTree) {
                if(n.isParentOf(model)) {
                    temp = new ModelNode(model);
                    n.addChild(temp);
                    nodesInTree.add(temp);
                    break;
                }
            }
            if (temp == null) {
                return false;
            }
        }
// TODO
// We can comment this out in the future if we need this feature
//        modelsInTree.add(model);
        if (model.getPomFile() != null) {
            pomFilesInTree.add(model.getPomFile());
        }
        return true;
    }
项目:butterfly    文件:ModelTree.java   
@SuppressWarnings("PMD.SimplifyBooleanReturns")
private boolean isParentOf(Model model) {
    if (model.getParent() == null) {
        return false;
    }

    if (!this.model.getGroupId().equals(model.getParent().getGroupId())) return false;
    if (!this.model.getArtifactId().equals(model.getParent().getArtifactId())) return false;
    if (!this.model.getVersion().equals(model.getParent().getVersion())) return false;
    return true;
}
项目:butterfly    文件:PomRemoveManagedDependency.java   
@Override
protected TOExecutionResult pomExecution(String relativePomFile, Model model) {
    TOExecutionResult result = null;
    String details;

    Dependency dependency = getManagedDependency(model, groupId, artifactId);
    if (dependency != null) {
        model.getDependencyManagement().removeDependency(dependency);
        details = String.format("Managed dependency %s:%s has been removed from POM file %s", groupId, artifactId, relativePomFile);
        result = TOExecutionResult.success(this, details);
    } else {
        details = String.format("Managed dependency %s:%s has NOT been removed from POM file %s because it is not present", groupId, artifactId, relativePomFile);
        switch (ifNotPresent) {
            case Warn:
                result = TOExecutionResult.warning(this, new TransformationOperationException(details));
                break;
            case NoOp:
                result = TOExecutionResult.noOp(this, details);
                break;
            case Fail:
                // Fail is the default
            default:
                result = TOExecutionResult.error(this, new TransformationOperationException(details));
                break;
        }
    }

    return result;
}
项目:butterfly    文件:PomRemoveDependency.java   
@Override
protected TOExecutionResult pomExecution(String relativePomFile, Model model) {
    TOExecutionResult result = null;
    String details;

    Dependency dependency = getDependency(model, groupId, artifactId);
    if (dependency != null) {
        model.removeDependency(dependency);
        details = String.format("Dependency %s:%s has been removed from POM file %s", groupId, artifactId, relativePomFile);
        result = TOExecutionResult.success(this, details);
    } else {
        details = String.format("Dependency %s:%s has NOT been removed from POM file %s because it is not present", groupId, artifactId, relativePomFile);
        switch (ifNotPresent) {
            case Warn:
                result = TOExecutionResult.warning(this, new TransformationOperationException(details));
                break;
            case NoOp:
                result = TOExecutionResult.noOp(this, details);
                break;
            case Fail:
                // Fail is the default
            default:
                result = TOExecutionResult.error(this, new TransformationOperationException(details));
                break;
        }
    }

    return result;
}
项目:smart-testing    文件:MavenProjectConfigurator.java   
private List<Plugin> getEffectivePlugins(Model model) {
    final List<Plugin> testRunnerPluginConfigurations = model.getBuild().getPlugins()
        .stream()
        .filter(
            plugin -> ApplicablePlugins.contains(plugin.getArtifactId()) && hasMinimumVersionRequired(plugin, model))
        .filter(this::hasPluginSelectionConfigured)
        .collect(Collectors.toList());

    if (areNotApplicableTestingPlugins(testRunnerPluginConfigurations) && isNotPomProject(model)) {
        failBecauseOfMissingApplicablePlugin(model);
    }

    return removePluginsThatAreSkipped(testRunnerPluginConfigurations, model);
}
项目:butterfly    文件:PomChangePackaging.java   
@Override
protected TOExecutionResult pomExecution(String relativePomFile, Model model) {
    model.setPackaging(packagingType);
    String details = String.format("Packaging for POM file %s has been changed to %s", relativePomFile, packagingType);

    return TOExecutionResult.success(this, details);
}
项目:butterfly    文件:PomChangeParent.java   
@Override
protected TOExecutionResult pomExecution(String relativePomFile, Model model) {
    String details;
    Parent parent = model.getParent();

    if (parent == null) {
        String message = String.format("Pom file %s does not have a parent", getRelativePath());

        switch (ifNotPresent) {
            case Warn:
                return TOExecutionResult.warning(this, new TransformationOperationException(message));
            case NoOp:
                return TOExecutionResult.noOp(this, message);
            case Fail:
                // Fail is the default
            default:
                return TOExecutionResult.error(this, new TransformationOperationException(message));
        }
    }

    if(groupId != null && artifactId != null && version != null) {
        parent.setGroupId(groupId);
        parent.setArtifactId(artifactId);
        parent.setVersion(version);
        String newParent = parent.toString();
        details = String.format("Parent for POM file (%s) has been set to %s", relativePomFile, newParent);
    } else if (groupId == null && artifactId == null && version != null) {
        String oldVersion = parent.getVersion();
        parent.setVersion(version);
        details = String.format("Parent's version for POM file (%s) has been changed from %s to %s", relativePomFile, oldVersion, version);
    } else {
        // FIXME this should be in a pre-validation
        return TOExecutionResult.error(this, new TransformationOperationException("Invalid POM parent transformation operation"));
    }

    return TOExecutionResult.success(this, details);
}
项目:deployment-recorder-extension    文件:PomReadTest.java   
@Test(expectedExceptions = IllegalArgumentException.class)
public void shouldFailCauseTheArtifactDoesNotDefineAVersion() throws IOException, XmlPullParserException {
    InputStream resourceAsStream = this.getClass().getResourceAsStream("/first-pom.xml");
    PomRead pomRead = new PomRead();
    Model model = pomRead.readModel(resourceAsStream);
    String expectedVersion = pomRead.getPomVersion(model);
    assertThat(expectedVersion).isEqualTo("0.1.0-SNAPSHOT");
}
项目:butterfly    文件:AbstractArtifactPomOperation.java   
protected Plugin getManagedPlugin(Model model, String groupId, String artifactId) {
    if (model.getBuild() == null) {
        return null;
    }
    if (model.getBuild().getPluginManagement().getPlugins() == null) {
        return null;
    }
    return getPluginInList(model.getBuild().getPluginManagement().getPlugins(), groupId, artifactId);
}