Example usage for org.apache.maven.model.building ModelProcessor SOURCE

List of usage examples for org.apache.maven.model.building ModelProcessor SOURCE

Introduction

In this page you can find the example usage for org.apache.maven.model.building ModelProcessor SOURCE.

Prototype

String SOURCE

To view the source code for org.apache.maven.model.building ModelProcessor SOURCE.

Click Source Link

Usage

From source file:fr.brouillard.oss.jgitver.JGitverModelProcessor.java

License:Apache License

private Model provisionModel(Model model, Map<String, ?> options) throws IOException {
    try {/*from  ww  w  . j a v a  2  s .  co  m*/
        calculateVersionIfNecessary();
    } catch (Exception ex) {
        throw new IOException("cannot build a Model object using jgitver", ex);
    }

    Source source = (Source) options.get(ModelProcessor.SOURCE);
    //logger.debug( "JGitverModelProcessor.provisionModel source="+source );
    if (source == null) {
        return model;
    }

    File location = new File(source.getLocation());
    //logger.debug( "JGitverModelProcessor.provisionModel location="+location );
    if (!location.isFile()) {
        // their JavaDoc says Source.getLocation "could be a local file path, a URI or just an empty string."
        // if it doesn't resolve to a file then calling .getParentFile will throw an exception,
        // but if it doesn't resolve to a file then it isn't under getMultiModuleProjectDirectory,
        return model; // therefore the model shouldn't be modified.
    }

    File relativePath = location.getParentFile().getCanonicalFile();

    if (StringUtils.containsIgnoreCase(relativePath.getCanonicalPath(),
            workingConfiguration.getMultiModuleProjectDirectory().getCanonicalPath())) {

        workingConfiguration.getNewProjectVersions().put(GAV.from(model.clone()),
                workingConfiguration.getCalculatedVersion());

        if (Objects.nonNull(model.getVersion())) {
            // TODO evaluate how to set the version only when it was originally set in the pom file
            model.setVersion(workingConfiguration.getCalculatedVersion());
        }

        if (Objects.nonNull(model.getParent())) {
            // if the parent is part of the multi module project, let's update the parent version 
            File relativePathParent = new File(
                    relativePath.getCanonicalPath() + File.separator + model.getParent().getRelativePath())
                            .getParentFile().getCanonicalFile();
            if (StringUtils.containsIgnoreCase(relativePathParent.getCanonicalPath(),
                    workingConfiguration.getMultiModuleProjectDirectory().getCanonicalPath())) {
                model.getParent().setVersion(workingConfiguration.getCalculatedVersion());
            }
        }

        // we should only register the plugin once, on the main project
        if (relativePath.getCanonicalPath()
                .equals(workingConfiguration.getMultiModuleProjectDirectory().getCanonicalPath())) {
            if (Objects.isNull(model.getBuild())) {
                model.setBuild(new Build());
            }

            if (Objects.isNull(model.getBuild().getPlugins())) {
                model.getBuild().setPlugins(new ArrayList<>());
            }

            Optional<Plugin> pluginOptional = model.getBuild().getPlugins().stream()
                    .filter(x -> JGitverUtils.EXTENSION_GROUP_ID.equalsIgnoreCase(x.getGroupId())
                            && JGitverUtils.EXTENSION_ARTIFACT_ID.equalsIgnoreCase(x.getArtifactId()))
                    .findFirst();

            StringBuilder pluginVersion = new StringBuilder();

            try (InputStream inputStream = getClass()
                    .getResourceAsStream("/META-INF/maven/" + JGitverUtils.EXTENSION_GROUP_ID + "/"
                            + JGitverUtils.EXTENSION_ARTIFACT_ID + "/pom" + ".properties")) {
                Properties properties = new Properties();
                properties.load(inputStream);
                pluginVersion.append(properties.getProperty("version"));
            } catch (IOException ignored) {
                // TODO we should not ignore in case we have to reuse it
                logger.warn(ignored.getMessage(), ignored);
            }

            Plugin plugin = pluginOptional.orElseGet(() -> {
                Plugin plugin2 = new Plugin();
                plugin2.setGroupId(JGitverUtils.EXTENSION_GROUP_ID);
                plugin2.setArtifactId(JGitverUtils.EXTENSION_ARTIFACT_ID);
                plugin2.setVersion(pluginVersion.toString());

                model.getBuild().getPlugins().add(plugin2);
                return plugin2;
            });

            if (Objects.isNull(plugin.getExecutions())) {
                plugin.setExecutions(new ArrayList<>());
            }

            Optional<PluginExecution> pluginExecutionOptional = plugin.getExecutions().stream()
                    .filter(x -> "verify".equalsIgnoreCase(x.getPhase())).findFirst();

            PluginExecution pluginExecution = pluginExecutionOptional.orElseGet(() -> {
                PluginExecution pluginExecution2 = new PluginExecution();
                pluginExecution2.setPhase("verify");

                plugin.getExecutions().add(pluginExecution2);
                return pluginExecution2;
            });

            if (Objects.isNull(pluginExecution.getGoals())) {
                pluginExecution.setGoals(new ArrayList<>());
            }

            if (!pluginExecution.getGoals().contains(JGitverAttachModifiedPomsMojo.GOAL_ATTACH_MODIFIED_POMS)) {
                pluginExecution.getGoals().add(JGitverAttachModifiedPomsMojo.GOAL_ATTACH_MODIFIED_POMS);
            }

            if (Objects.isNull(plugin.getDependencies())) {
                plugin.setDependencies(new ArrayList<>());
            }

            Optional<Dependency> dependencyOptional = plugin.getDependencies().stream()
                    .filter(x -> JGitverUtils.EXTENSION_GROUP_ID.equalsIgnoreCase(x.getGroupId())
                            && JGitverUtils.EXTENSION_ARTIFACT_ID.equalsIgnoreCase(x.getArtifactId()))
                    .findFirst();

            dependencyOptional.orElseGet(() -> {
                Dependency dependency = new Dependency();
                dependency.setGroupId(JGitverUtils.EXTENSION_GROUP_ID);
                dependency.setArtifactId(JGitverUtils.EXTENSION_ARTIFACT_ID);
                dependency.setVersion(pluginVersion.toString());

                plugin.getDependencies().add(dependency);
                return dependency;
            });
        }

        try {
            legacySupport.getSession().getUserProperties().put(
                    JGitverModelProcessorWorkingConfiguration.class.getName(),
                    JGitverModelProcessorWorkingConfiguration.serializeTo(workingConfiguration));
        } catch (JAXBException ex) {
            throw new IOException("unexpected Model serialization issue", ex);
        }
    }

    return model;
}

From source file:org.sonatype.maven.polyglot.atom.AtomModelReader.java

License:Open Source License

public Model read(final Reader input, final Map<String, ?> options) throws IOException {
    assert input != null;

    // Parse the token stream from our pom.atom configuration file.
    Project project = new AtomParser((ModelSource) options.get(ModelProcessor.SOURCE),
            new Tokenizer(IOUtil.toString(input)).tokenize()).parse();
    return project.toMavenModel();
}

From source file:org.sonatype.maven.polyglot.mapping.MappingSupport.java

License:Open Source License

public String getLocation(final Map<?, ?> options) {
    if (options != null) {
        Object tmp = options.get(ModelProcessor.SOURCE);
        if (tmp instanceof String) {
            return (String) tmp;
        } else if (tmp instanceof URL) {
            return ((URL) tmp).toExternalForm();
        } else if (tmp instanceof File) {
            return ((File) tmp).getAbsolutePath();
        } else if (tmp instanceof ModelSource) {
            return ((ModelSource) tmp).getLocation();
        }// ww  w  .j av  a 2  s .  c om
    }
    return null;
}

From source file:org.sonatype.maven.polyglot.mapping.XmlMapping.java

License:Open Source License

@Override
public boolean accept(Map<String, ?> options) {
    // assume StringModelSource is default maven, i.e. xml
    if (options != null && options.get(ModelProcessor.SOURCE) instanceof StringModelSource) {
        return true;
    }//from ww w. j  a  v  a  2  s.  c o m
    return super.accept(options);
}

From source file:org.sonatype.maven.polyglot.plugin.ExecuteMojo.java

License:Open Source License

protected Model modelFromNativePom(Log log) throws MojoExecutionException, MojoFailureException {
    Map<String, ModelSource> options = new HashMap<String, ModelSource>();
    options.put(ModelProcessor.SOURCE, new FileModelSource(nativePom));

    assert modelManager != null;
    try {/*from   w ww. j a  v  a2s  .  co  m*/
        ModelReader reader = modelManager.getReaderFor(options);
        if (reader == null) {
            throw new MojoExecutionException("no model reader found for " + nativePom);
        }
        if (log.isDebugEnabled()) {
            log.debug("Parsing native pom " + nativePom);
        }
        return reader.read(nativePom, options);
    } catch (IOException e) {
        throw new MojoFailureException("error parsing " + nativePom, e);
    }
}

From source file:org.sonatype.maven.polyglot.PolyglotModelUtil.java

License:Open Source License

/**
 * Gets the location, as configured via the {@link ModelProcessor#SOURCE} key.
 *
 * Supports values of:/*ww  w  .j  a v a  2 s  .co m*/
 * <ul>
 * <li>String
 * <li>File
 * <li>URL
 * <li>ModelSource
 * </ul>
 *
 * @return  The model location; or null.
 */
public static String getLocation(final Map<?, ?> options) {
    if (options != null) {
        Object tmp = options.get(ModelProcessor.SOURCE);
        if (tmp instanceof String) {
            return (String) tmp;
        } else if (tmp instanceof URL) {
            return ((URL) tmp).toExternalForm();
        } else if (tmp instanceof File) {
            return ((File) tmp).getAbsolutePath();
        } else if (tmp instanceof ModelSource) {
            return ((ModelSource) tmp).getLocation();
        }
    }
    return null;
}

From source file:org.sonatype.maven.polyglot.PolyglotModelUtil.java

License:Open Source License

public static File getLocationFile(final Map<?, ?> options) {
    if (options != null) {
        Object src = options.get(ModelProcessor.SOURCE);
        if (src instanceof URL) {
            return new File(((URL) src).getFile());
        } else if (src != null) {
            ModelSource sm = (ModelSource) src;
            return new File(sm.getLocation());
        }//  w ww .ja va  2 s . com
    }
    return null;
}

From source file:org.sonatype.maven.polyglot.ruby.AbstractInjectedTestCase.java

License:Open Source License

protected void assertModels(File pom, String pomRuby, boolean debug) throws Exception {
    MavenXpp3Reader xmlModelReader = new MavenXpp3Reader();
    Model xmlModel = xmlModelReader.read(new FileInputStream(pom));

    ///*ww  w .  j av a  2  s .  co m*/
    // Read in the Ruby POM
    //
    RubyModelReader rubyModelReader = new RubyModelReader();
    final PolyglotModelManager modelManager = new PolyglotModelManager() {
        {
            mappings = new ArrayList<Mapping>();
        }
    };
    modelManager.addMapping(new RubyMapping());
    rubyModelReader.executeManager = new ExecuteManagerImpl() {
        {
            log = new ConsoleLogger(Logger.LEVEL_INFO, "test");
            manager = modelManager;
        }
    };
    rubyModelReader.setupManager = new SetupClassRealm();

    File pomRubyFile = new File(specs(), pomRuby);
    Reader reader = new FileReader(pomRubyFile);
    Map<String, Object> options = new HashMap<String, Object>();
    options.put(ModelProcessor.SOURCE, pomRubyFile.toURI().toURL());
    Model rubyModel = rubyModelReader.read(reader, options);

    assertModels(xmlModel, rubyModel, debug);
}

From source file:org.sonatype.maven.polyglot.TeslaModelProcessor.java

License:Open Source License

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Model read(final Reader input, final Map<String, ?> options) throws IOException, ModelParseException {
    assert manager != null;
    ModelSource source = (ModelSource) options.get(ModelProcessor.SOURCE);
    if (("" + source).contains(".polyglot.")) {
        log.debug(source.getLocation());

        File pom = new File(source.getLocation());
        source = new FileModelSource(new File(pom.getPath().replaceFirst("[.]polyglot[.]", "")));

        ((Map) options).put(ModelProcessor.SOURCE, source);

        ModelReader reader = manager.getReaderFor(options);
        Model model = reader.read(source.getInputStream(), options);

        MavenXpp3Writer xmlWriter = new MavenXpp3Writer();
        StringWriter xml = new StringWriter();
        xmlWriter.write(xml, model);/*from  ww  w .  j  a va  2  s  .c  o m*/

        FileUtils.fileWrite(pom, xml.toString());

        // dump pom if filename is given via the pom properties
        String dump = model.getProperties().getProperty("polyglot.dump.pom");
        if (dump == null) {
            // just nice to dump the pom.xml via commandline switch
            dump = System.getProperty("polyglot.dump.pom");
        }
        if (dump != null) {
            File dumpPom = new File(pom.getParentFile(), dump);
            if (!dumpPom.exists() || !FileUtils.fileRead(dumpPom).equals(xml.toString())) {
                dumpPom.setWritable(true);
                FileUtils.fileWrite(dumpPom, xml.toString());
                if ("true".equals(model.getProperties().getProperty("polyglot.dump.readonly"))) {
                    dumpPom.setReadOnly();
                }
            }
        }

        model.setPomFile(pom);
        return model;
    } else {
        ModelReader reader = manager.getReaderFor(options);
        return reader.read(input, options);
    }
}

From source file:org.sonatype.maven.polyglot.TeslaModelTranslator.java

License:Open Source License

public void translate(final File input, final File output) throws IOException, ModelParseException {
    assert input != null;
    assert output != null;

    Map<String, Object> inputOptions = new HashMap<String, Object>();
    inputOptions.put(ModelProcessor.SOURCE, input);

    Map<String, Object> outputOptions = new HashMap<String, Object>();
    outputOptions.put(ModelProcessor.SOURCE, output);

    translate(input, inputOptions, output, outputOptions);
}