Example usage for org.apache.maven.project MavenProject MavenProject

List of usage examples for org.apache.maven.project MavenProject MavenProject

Introduction

In this page you can find the example usage for org.apache.maven.project MavenProject MavenProject.

Prototype

public MavenProject(MavenProject project) 

Source Link

Usage

From source file:ch.sventschui.maven.visualizer.VisualizerMojo.java

License:Apache License

public void execute() throws MojoExecutionException {

    this.createOutputDir();

    for (String directory : this.directories) {
        this.poms.addAll(FileUtils.listFiles(new File(directory), new PomFileFilter(), new TargetFileFilter()));
    }/* ww w  .j  a  v  a 2  s.  co  m*/

    for (File pom : this.poms) {

        Model model = null;

        FileReader reader = null;

        MavenXpp3Reader mavenreader = new MavenXpp3Reader();

        try {
            reader = new FileReader(pom);
            model = mavenreader.read(reader);
            model.setPomFile(pom);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        MavenProject project = new MavenProject(model);

        MavenArtifact base = new MavenArtifact(project.getGroupId(), project.getArtifactId(),
                project.getVersion());

        if (this.filter.matches(base)) {

            this.store.addArtifact(base);

            for (Dependency artifact : project.getDependencies()) {
                MavenArtifact dependency = new MavenArtifact(artifact.getGroupId(), artifact.getArtifactId(),
                        artifact.getVersion());

                if (this.filter.matches(dependency)) {
                    this.store.addArtifact(dependency);
                    this.store.addRelationship(base, dependency);
                }
            }
        }
    }

    try {
        FileWriter fstream = new FileWriter(new File(this.outputDir, "test.json"));
        BufferedWriter out = new BufferedWriter(fstream);

        out.write(this.store.toJSON());

        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.ardoq.mavenImport.MavenUtil.java

private static MavenProject loadProject(File pomFile) {
    MavenXpp3Reader mavenReader = new MavenXpp3Reader();
    FileReader reader = null;//www. ja v  a2  s . com

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

        return new MavenProject(model);
    } catch (Exception e) {
        throw new RuntimeException("Error reading Maven project from file", e);
    } finally {
        IOUtil.close(reader);
    }
}

From source file:com.carrotgarden.m2e.config.LaunchDelegate.java

License:BSD License

private void launchMaven(final File pomFile, final List<String> commandList, final IProgressMonitor monitor)
        throws CoreException {

    final IMaven maven = MavenPlugin.getMaven();

    final Model mavenModel = maven.readModel(pomFile);

    final MavenProject mavenProject = new MavenProject(mavenModel);

    final Properties mavenProps = mavenProject.getProperties();

    for (final Map.Entry<?, ?> entry : mavenProps.entrySet()) {
        final String key = entry.getKey().toString();
        final String value = entry.getValue().toString();
        // ConfigPlugin.logInfo("key= " + key + " value=" + value);
    }//from  w ww  . j a v a2 s .  c o  m

    //

    final List<String> goalList = new LinkedList<String>();
    final List<String> profileActiveList = new LinkedList<String>();
    final List<String> profileInactiveList = new LinkedList<String>();

    for (final String command : commandList) {

        if (command.startsWith("-")) {

            /** command line options */

            if (command.startsWith("--activate-profiles")) {
                ConfigPlugin.log(IStatus.ERROR, "TODO : " + command);
            } else {
                ConfigPlugin.log(IStatus.ERROR, "not supported : " + command);
            }

        } else {

            /** maven execution goals */

            goalList.add(command);

        }

    }

    //

    final MavenExecutionRequest request = maven.createExecutionRequest(monitor);

    request.setPom(pomFile);
    request.setGoals(goalList);

    // TODO
    // request.setActiveProfiles(profileActiveList);
    // request.setInactiveProfiles(profileInactiveList);

    //

    final String id = mavenProject.getId();

    ConfigPlugin.log(IStatus.INFO,
            "maven execute : " + mavenProject.getId() + " " + MojoUtil.join(commandList, ","));

    // final Job job = new Job(id) {
    // {
    // setSystem(true);
    // setPriority(BUILD);
    // }
    // @Override
    // protected IStatus run(final IProgressMonitor monitor) {
    // return null;
    // }
    // };

    final MavenExecutionResult result = maven.execute(request, monitor);

    if (result.hasExceptions()) {
        throw new CoreException(new Status(IStatus.ERROR, ConfigPlugin.ID, "maven execution failed",
                result.getExceptions().get(0)));
    }

}

From source file:com.datacoper.maven.util.MavenUtil.java

public static MavenProject startNewProject(File folderProject) {
    try {//from ww w.jav  a  2s . co m
        File pomFile = getPomFile(folderProject);

        FileReader reader = new FileReader(pomFile);
        Model model = new MavenXpp3Reader().read(reader);
        model.setPomFile(pomFile);

        MavenProject project = new MavenProject(model);
        project.setFile(folderProject);

        return project;
    } catch (IOException | XmlPullParserException ex) {
        throw new DcRuntimeException(ex.getMessage());
    }
}

From source file:com.oracle.istack.maven.PropertyResolver.java

License:Open Source License

/**
 *
 * @param project maven project//w w  w. j  a va 2s .c  o m
 * @throws FileNotFoundException properties not found
 * @throws IOException IO error
 * @throws XmlPullParserException error parsing xml
 */
public void resolveProperties(MavenProject project)
        throws FileNotFoundException, IOException, XmlPullParserException {
    logger.info("Resolving properties for " + project.getGroupId() + ":" + project.getArtifactId());

    Model model = null;
    FileReader reader;
    try {
        reader = new FileReader(project.getFile());
        model = mavenreader.read(reader);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ImportPropertiesMojo.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ImportPropertiesMojo.class.getName()).log(Level.SEVERE, null, ex);
    }
    MavenProject loadedProject = new MavenProject(model);

    DependencyManagement dm = loadedProject.getDependencyManagement();
    if (dm == null) {
        logger.warn("No dependency management section found in: " + loadedProject.getGroupId() + ":"
                + loadedProject.getArtifactId());
        return;
    }

    List<Dependency> depList = dm.getDependencies();

    DependencyResult result;
    for (Dependency d : depList) {
        if ("import".equals(d.getScope())) {
            try {
                String version = d.getVersion();
                logger.info("Imported via import-scope: " + d.getGroupId() + ":" + d.getArtifactId() + ":"
                        + version);
                if (version.contains("$")) {
                    version = properties
                            .getProperty(version.substring(version.indexOf('{') + 1, version.lastIndexOf('}')));
                    logger.info("Imported version resolved to: " + version);
                }
                d.setVersion(version);
                d.setType("pom");
                d.setClassifier("pom");
                result = DependencyResolver.resolve(d, pluginRepos, repoSystem, repoSession);
                Artifact a = result.getArtifactResults().get(0).getArtifact();
                reader = new FileReader(a.getFile());
                Model m = mavenreader.read(reader);
                MavenProject p = new MavenProject(m);
                p.setFile(a.getFile());
                for (Map.Entry<Object, Object> e : p.getProperties().entrySet()) {
                    logger.info("Setting property: " + (String) e.getKey() + ":" + (String) e.getValue());
                    properties.setProperty((String) e.getKey(), (String) e.getValue());
                }

                resolveProperties(p);
            } catch (DependencyResolutionException ex) {
                Logger.getLogger(ImportPropertiesMojo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:com.phoenixnap.oss.ramlapisync.plugin.SpringMvcEndpointGeneratorMojo.java

License:Apache License

protected void generateEndpoints()
        throws MojoExecutionException, MojoFailureException, IOException, InvalidRamlResourceException {

    File pomFile = null;/*from w w w . jav  a2s  . com*/
    if (!pomPath.equals("NA")) {

        Model model = null;
        FileReader reader = null;
        MavenXpp3Reader mavenreader = new MavenXpp3Reader();
        pomFile = new File(pomPath);
        try {
            reader = new FileReader(pomFile);
            model = mavenreader.read(reader);
            model.setPomFile(pomFile);
        } catch (Exception ex) {
            getLog().info("Exception Occured", ex);
        }
        project = new MavenProject(model);
        project.setFile(pomFile);
    }

    String resolvedPath = project.getBasedir().getAbsolutePath();
    if (resolvedPath.endsWith(File.separator) || resolvedPath.endsWith("/")) {
        resolvedPath = resolvedPath.substring(0, resolvedPath.length() - 1);
    }

    String resolvedRamlPath = project.getBasedir().getAbsolutePath();

    if (!ramlPath.startsWith(File.separator) && !ramlPath.startsWith("/")) {
        resolvedRamlPath += File.separator + ramlPath;
    } else {
        resolvedRamlPath += ramlPath;
    }

    // Resolve schema location and add to classpath
    resolvedSchemaLocation = getSchemaLocation();

    RamlRoot loadRamlFromFile = RamlLoader.loadRamlFromFile(new File(resolvedRamlPath).toURI().toString());

    JCodeModel codeModel = null;
    //In the RJP10V2 we have support for a unified code model. RJP08V1 does not work well with this.
    //TODO update RJP08V1 to support a unified view.
    boolean unifiedModel = false;
    if (loadRamlFromFile instanceof RJP10V2RamlRoot) {
        codeModel = new JCodeModel();
        unifiedModel = true;
    }

    //Map the jsconschema2pojo config to ours. This will need to eventually take over. update just in case previous one was set before jsonconfig was set
    typeGenerationConfig = mapGenerationConfigMapping();

    RamlParser par = new RamlParser(typeGenerationConfig, getBasePath(loadRamlFromFile),
            seperateMethodsByContentType, injectHttpHeadersParameter, this.resourceDepthInClassNames);
    Set<ApiResourceMetadata> controllers = par.extractControllers(codeModel, loadRamlFromFile);
    controllers.forEach(controller -> {
        //controller.
    });
    if (StringUtils.hasText(outputRelativePath)) {
        if (!outputRelativePath.startsWith(File.separator) && !outputRelativePath.startsWith("/")) {
            resolvedPath += File.separator;
        }
        resolvedPath += outputRelativePath;
    } else {
        resolvedPath += "/target/generated-sources/spring-mvc";
    }

    File rootDir = new File(
            resolvedPath + (addTimestampFolder == true ? System.currentTimeMillis() : "") + "/");

    if (!rootDir.exists() && !rootDir.mkdirs()) {
        throw new IOException("Could not create directory:" + rootDir.getAbsolutePath());
    }

    generateCode(codeModel, controllers, rootDir);
    generateUnreferencedSchemas(codeModel, resolvedRamlPath, loadRamlFromFile, rootDir);

    if (unifiedModel) {
        buildCodeModelToDisk(codeModel, "Unified", rootDir);
    }
}

From source file:com.runwaysdk.business.generation.maven.MavenClasspathBuilder.java

License:Open Source License

public static MavenProject loadProject(File pomFile) throws IOException, XmlPullParserException {
    MavenProject ret = null;//from  w  ww  .  j a  v a  2s  .c om
    MavenXpp3Reader mavenReader = new MavenXpp3Reader();

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

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

            List<Repository> repositories = model.getRepositories();
            Properties properties = model.getProperties();
            properties.setProperty("basedir", pomFile.getParent());

            Parent parent = model.getParent();
            if (parent != null) {
                File parentPom = new File(pomFile.getParent(), parent.getRelativePath());
                MavenProject parentProj = loadProject(parentPom);

                if (parentProj == null) {
                    throw new CoreException("Unable to load parent project at " + parentPom.getAbsolutePath());
                }

                repositories.addAll(parentProj.getRepositories());
                model.setRepositories(repositories);

                properties.putAll(parentProj.getProperties());
            }

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

    return ret;
}

From source file:com.webcohesion.enunciate.mojo.DeployArtifactBaseMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {
    if (this.enunciateArtifactId == null) {
        throw new MojoExecutionException("An enunciate artifact id must be supplied.");
    }/*www  .  j a  va 2 s. c  om*/

    Enunciate enunciate = (Enunciate) getPluginContext().get(ConfigMojo.ENUNCIATE_PROPERTY);
    if (enunciate == null) {
        throw new MojoExecutionException("No enunciate mechanism found in the project!");
    }

    com.webcohesion.enunciate.artifacts.Artifact enunciateArtifact = enunciate
            .findArtifact(this.enunciateArtifactId);
    if (enunciateArtifact == null) {
        throw new MojoExecutionException("Unknown Enunciate artifact: " + this.enunciateArtifactId + ".");
    }

    File mainArtifact = null;
    File sources = null;
    File javadocs = null;
    if (enunciateArtifact instanceof ClientLibraryArtifact) {
        for (com.webcohesion.enunciate.artifacts.Artifact childArtifact : ((ClientLibraryArtifact) enunciateArtifact)
                .getArtifacts()) {
            if (childArtifact instanceof FileArtifact) {
                ArtifactType artifactType = ((FileArtifact) childArtifact).getArtifactType();
                if (artifactType != null) {
                    switch (artifactType) {
                    case binaries:
                        mainArtifact = ((FileArtifact) childArtifact).getFile();
                        break;
                    case sources:
                        sources = ((FileArtifact) childArtifact).getFile();
                        break;
                    case javadocs:
                        javadocs = ((FileArtifact) childArtifact).getFile();
                        break;
                    }
                }
            }
        }
    } else if (enunciateArtifact instanceof FileArtifact) {
        mainArtifact = ((FileArtifact) enunciateArtifact).getFile();
    } else {
        try {
            mainArtifact = enunciate.createTempFile(this.enunciateArtifactId, "artifact");
            enunciateArtifact.exportTo(mainArtifact, enunciate);
        } catch (IOException e) {
            throw new MojoExecutionException("Unable to create a temp file.", e);
        }
    }

    if (mainArtifact == null) {
        if (sources != null) {
            mainArtifact = sources;
            sources = null;
        }
    }

    if (mainArtifact == null) {
        throw new MojoExecutionException(
                "Unable to determine the file to deploy from enunciate artifact " + enunciateArtifactId + ".");
    }

    // Process the supplied POM (if there is one)
    Model model = null;
    if (pomFile != null) {
        generatePom = false;
        model = readModel(pomFile);
        processModel(model);
    }

    if (this.packaging == null) {
        String artifactName = mainArtifact.getName();
        int dotIndex = artifactName.indexOf('.');
        if (dotIndex > 0 && (dotIndex + 1 < artifactName.length())) {
            this.packaging = artifactName.substring(dotIndex + 1);
        }
    }

    if (this.packaging == null) {
        throw new MojoExecutionException("Unable to determine the packaging of enunciate artifact "
                + enunciateArtifactId + ". Please specify it in the configuration.");
    }

    if (this.version == null) {
        throw new MojoExecutionException("Null version.");
    }

    if (model == null) {
        model = new Model();
        model.setModelVersion("4.0.0");
        model.setGroupId(this.groupId);
        model.setArtifactId(this.artifactId);
        model.setVersion(this.version);
        model.setPackaging(this.packaging);
        model.setDescription(this.description);
    }

    ArtifactRepository repo = getDeploymentRepository();

    String protocol = repo.getProtocol();

    if (protocol.equals("scp")) {
        File sshFile = new File(System.getProperty("user.home"), ".ssh");

        if (!sshFile.exists()) {
            sshFile.mkdirs();
        }
    }

    Artifact artifact = this.artifactFactory.createArtifactWithClassifier(groupId, artifactId, version,
            packaging, classifier);

    // Upload the POM if requested, generating one if need be
    if (generatePom) {
        ArtifactMetadata metadata = new ProjectArtifactMetadata(artifact, generatePomFile(model));
        artifact.addMetadata(metadata);
    } else {
        ArtifactMetadata metadata = new ProjectArtifactMetadata(artifact, pomFile);
        artifact.addMetadata(metadata);
    }

    try {
        getDeployer().deploy(mainArtifact, artifact, repo, this.localRepository);

        if (sources != null || javadocs != null) {
            MavenProject project = new MavenProject(model);
            project.setArtifact(artifact);
            if (sources != null) {
                //we have to do it this way because of classloading issues.
                this.projectHelper.attachArtifact(project, artifact.getType(), "sources", sources);
                getDeployer().deploy(sources, (Artifact) project.getAttachedArtifacts().get(0), repo,
                        this.localRepository);
            }

            if (javadocs != null) {
                //we have to do it this way because of classloading issues.
                this.projectHelper.attachArtifact(project, artifact.getType(), "javadoc", javadocs);
                getDeployer().deploy(javadocs, (Artifact) project.getAttachedArtifacts().get(0), repo,
                        this.localRepository);
            }
        }
    } catch (ArtifactDeploymentException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:de.jiac.micro.util.ReducedArchiver.java

License:Open Source License

public void createArchive(MavenProject project, MavenArchiveConfiguration archiveConfiguration)
        throws ArchiverException, ManifestException, IOException, DependencyResolutionRequiredException {
    // ----------------------------------------------------------------------
    // We want to add the metadata for the project to the JAR in two forms:
    ////from w w  w  . j a v  a2s  .  c om
    // The first form is that of the POM itself. Applications that wish to
    // access the POM for an artifact using maven tools they can.
    //
    // The second form is that of a properties file containing the basic
    // top-level POM elements so that applications that wish to access
    // POM information without the use of maven tools can do so.
    // ----------------------------------------------------------------------

    // we have to clone the project instance so we can write out the pom with the deployment version,
    // without impacting the main project instance...
    MavenProject workingProject = new MavenProject(project);

    if (workingProject.getArtifact().isSnapshot()) {
        workingProject.setVersion(workingProject.getArtifact().getVersion());
    }

    // ----------------------------------------------------------------------
    // Create the manifest
    // ----------------------------------------------------------------------

    File manifestFile = archiveConfiguration.getManifestFile();

    if (manifestFile != null) {
        archiver.setManifest(manifestFile);
    }

    Manifest manifest = getManifest(workingProject, archiveConfiguration.getManifest());

    // any custom manifest entries in the archive configuration manifest?
    if (!archiveConfiguration.isManifestEntriesEmpty()) {
        Map entries = archiveConfiguration.getManifestEntries();
        Set entrySet = entries.entrySet();

        for (Iterator iter = entrySet.iterator(); iter.hasNext();) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            Manifest.Attribute attr = new Manifest.Attribute(key, value);
            manifest.addConfiguredAttribute(attr);
        }
    }

    // any custom manifest sections in the archive configuration manifest?
    if (!archiveConfiguration.isManifestSectionsEmpty()) {
        List sections = archiveConfiguration.getManifestSections();
        for (Iterator iter = sections.iterator(); iter.hasNext();) {
            ManifestSection section = (ManifestSection) iter.next();
            Manifest.Section theSection = new Manifest.Section();
            theSection.setName(section.getName());

            if (!section.isManifestEntriesEmpty()) {
                Map entries = section.getManifestEntries();
                Set keys = entries.keySet();
                for (Iterator it = keys.iterator(); it.hasNext();) {
                    String key = (String) it.next();
                    String value = (String) entries.get(key);
                    Manifest.Attribute attr = new Manifest.Attribute(key, value);
                    theSection.addConfiguredAttribute(attr);
                }
            }

            manifest.addConfiguredSection(theSection);
        }
    }

    // Configure the jar
    archiver.addConfiguredManifest(manifest);

    archiver.setCompress(archiveConfiguration.isCompress());

    archiver.setIndex(archiveConfiguration.isIndex());

    archiver.setDestFile(archiveFile);

    // create archive
    archiver.createArchive();
}

From source file:fr.fastconnect.factory.tibco.bw.maven.builtin.CopyBWSourcesMojo.java

License:Apache License

@Override
protected List<Resource> getResources() {
    List<Resource> result = new ArrayList<Resource>();
    if (resources != null) {
        result.addAll(resources);/* w  w w  .  ja  v a2  s .c  o  m*/
    }

    if (isContainerEnabled(getProject())) {
        result.clear(); // ignore configuration from Plexus 'components.xml'

        getLog().debug(getProject().getProperties().toString());
        getLog().debug(getProject().getProperties().getProperty("project.build.directory.src"));
        File buildSrcDirectory = new File(
                getProject().getProperties().getProperty("project.build.directory.src"));
        buildSrcDirectory.mkdirs(); // create "target/src" directory

        // define a ".archive" file to merge all ".archive" found in other projects
        String bwProjectArchiveBuilder = getProject().getProperties().getProperty("bw.project.archive.builder");
        File bwProjectArchiveMerged = new File(
                buildSrcDirectory.getAbsolutePath() + File.separator + bwProjectArchiveBuilder);
        getLog().debug(".archive: " + bwProjectArchiveMerged.getAbsolutePath());

        // create an empty Archive Builder (".archive" file)
        ArchiveBuilder mergedArchiveBuilder = new ArchiveBuilder();

        List<MavenProject> projectsToAggregate = new ArrayList<MavenProject>();

        MavenProject aggregator = getProject().getParent();
        @SuppressWarnings("unchecked")
        List<String> modules = aggregator.getModules();

        for (String module : modules) {
            getLog().debug(module);
            String pom = aggregator.getBasedir() + File.separator + module + File.separator + "pom.xml";
            File pomFile = new File(pom);

            try {
                projectsToAggregate.add(new MavenProject(POMManager.getModelFromPOM(pomFile, getLog())));
            } catch (Exception e) {
                getLog().debug("Unable to add project from module: " + module);
            }
        }

        List<MavenProject> projects = new ArrayList<MavenProject>();
        projects.addAll(getSession().getProjects());

        for (Iterator<MavenProject> it = projects.iterator(); it.hasNext();) {
            MavenProject p = (MavenProject) it.next();
            if (!isProjectToAggregate(p, projectsToAggregate)) {
                it.remove();
            }
        }

        if (projects.size() > 0) {
            for (MavenProject p : projects) {
                if (p.getPackaging().equals(AbstractBWMojo.BWEAR_TYPE) && !isContainerEnabled(p)) {
                    // initialize project information
                    String basedir = p.getBasedir().getAbsolutePath();
                    String bwProjectLocation = p.getProperties().getProperty("bw.project.location");
                    bwProjectArchiveBuilder = p.getProperties().getProperty("bw.project.archive.builder"); // the ".archive" of the project
                    getLog().debug(basedir);
                    getLog().debug(bwProjectLocation);

                    File bwProjectArchive = new File(basedir + File.separator + bwProjectLocation
                            + File.separator + bwProjectArchiveBuilder);
                    getLog().debug(bwProjectArchive.getAbsolutePath());
                    //

                    mergedArchiveBuilder.merge(bwProjectArchive);

                    // add sources from the project to the container sources
                    File srcDirectory = new File(basedir + File.separator + bwProjectLocation);
                    result.add(addResource(srcDirectory));
                }
            }

            mergedArchiveBuilder.setSharedArchiveAuthor(pluginDescriptor.getArtifactId());
            mergedArchiveBuilder.setEnterpriseArchiveAuthor(pluginDescriptor.getArtifactId());
            mergedArchiveBuilder.setEnterpriseArchiveFileLocationProperty(
                    this.getProject().getArtifactId() + AbstractBWMojo.BWEAR_EXTENSION);
            mergedArchiveBuilder.setEnterpriseArchiveName(enterpriseArchiveName);
            mergedArchiveBuilder.setFirstProcessArchiveName(processArchiveName);
            mergedArchiveBuilder.removeDuplicateProcesses();
            mergedArchiveBuilder.save(bwProjectArchiveMerged);
        }
    }

    return result;
}