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

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

Introduction

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

Prototype

public List<String> getCompileClasspathElements() throws DependencyResolutionRequiredException 

Source Link

Usage

From source file:ch.ifocusit.livingdoc.plugin.utils.ClassLoaderUtil.java

License:Apache License

public static ClassLoader getRuntimeClassLoader(MavenProject project) throws MojoExecutionException {
    try {//from ww  w  .  j  a  va 2  s  .  c o  m
        List<String> runtimeClasspathElements = project.getRuntimeClasspathElements();
        List<String> compileClasspathElements = project.getCompileClasspathElements();
        URL[] runtimeUrls = new URL[runtimeClasspathElements.size() + compileClasspathElements.size()];
        for (int i = 0; i < runtimeClasspathElements.size(); i++) {
            String element = runtimeClasspathElements.get(i);
            runtimeUrls[i] = new File(element).toURI().toURL();
        }

        int j = runtimeClasspathElements.size();

        for (int i = 0; i < compileClasspathElements.size(); i++) {
            String element = compileClasspathElements.get(i);
            runtimeUrls[i + j] = new File(element).toURI().toURL();
        }

        return new URLClassLoader(runtimeUrls, Thread.currentThread().getContextClassLoader());

    } catch (Exception e) {
        throw new MojoExecutionException("Unable to load project runtime !", e);
    }
}

From source file:com.agilejava.docbkx.maven.AbstractTransformerMojo.java

License:Apache License

/**
 * Configures and executes the given ant tasks, mainly preprocess and postprocess defined in the pom configuration.
 *
 * @param antTasks The tasks to execute/*w  ww  . jav a 2s  .c om*/
 * @param mavenProject The current maven project
 * @throws MojoExecutionException If something wrong occurs while executing the ant tasks.
 */
protected void executeTasks(Target antTasks, MavenProject mavenProject) throws MojoExecutionException {
    try {
        ExpressionEvaluator exprEvaluator = (ExpressionEvaluator) antTasks.getProject()
                .getReference("maven.expressionEvaluator");
        Project antProject = antTasks.getProject();
        PropertyHelper propertyHelper = PropertyHelper.getPropertyHelper(antProject);
        propertyHelper.setNext(new AntPropertyHelper(exprEvaluator, getLog()));
        DefaultLogger antLogger = new DefaultLogger();
        antLogger.setOutputPrintStream(System.out);
        antLogger.setErrorPrintStream(System.err);
        antLogger.setMessageOutputLevel(2);
        antProject.addBuildListener(antLogger);
        antProject.setBaseDir(mavenProject.getBasedir());
        Path p = new Path(antProject);
        p.setPath(StringUtils.join(mavenProject.getArtifacts().iterator(), File.pathSeparator));
        antProject.addReference("maven.dependency.classpath", p);
        p = new Path(antProject);
        p.setPath(StringUtils.join(mavenProject.getCompileClasspathElements().iterator(), File.pathSeparator));
        antProject.addReference("maven.compile.classpath", p);
        p = new Path(antProject);
        p.setPath(StringUtils.join(mavenProject.getRuntimeClasspathElements().iterator(), File.pathSeparator));
        antProject.addReference("maven.runtime.classpath", p);
        p = new Path(antProject);
        p.setPath(StringUtils.join(mavenProject.getTestClasspathElements().iterator(), File.pathSeparator));
        antProject.addReference("maven.test.classpath", p);
        List artifacts = getArtifacts();
        List list = new ArrayList(artifacts.size());
        File file;
        for (Iterator i = artifacts.iterator(); i.hasNext(); list.add(file.getPath())) {
            Artifact a = (Artifact) i.next();
            file = a.getFile();
            if (file == null)
                throw new DependencyResolutionRequiredException(a);
        }

        p = new Path(antProject);
        p.setPath(StringUtils.join(list.iterator(), File.pathSeparator));
        antProject.addReference("maven.plugin.classpath", p);
        getLog().info("Executing tasks");
        antTasks.execute();
        getLog().info("Executed tasks");
    } catch (Exception e) {
        throw new MojoExecutionException("Error executing ant tasks", e);
    }
}

From source file:com.bekioui.maven.plugin.client.initializer.ProjectInitializer.java

License:Apache License

@SuppressWarnings("unchecked")
public static Project initialize(MavenProject mavenProject, Properties properties)
        throws MojoExecutionException {
    String clientPackagename = mavenProject.getParent().getGroupId() + ".client";
    String contextPackageName = clientPackagename + ".context";
    String apiPackageName = clientPackagename + ".api";
    String implPackageName = clientPackagename + ".impl";
    String resourceBasedirPath = mavenProject.getBasedir().getAbsolutePath();
    String projectBasedirPath = resourceBasedirPath.substring(0,
            resourceBasedirPath.lastIndexOf(File.separator));

    File clientDirectory = new File(projectBasedirPath + File.separator + properties.clientArtifactId());
    if (clientDirectory.exists()) {
        try {//from  w ww .jav a2s  .c o  m
            FileUtils.deleteDirectory(clientDirectory);
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to delete existing client directory.", e);
        }
    }
    clientDirectory.mkdir();

    File javaSourceDirectory = new File(resourceBasedirPath + FULL_SRC_FOLDER
            + properties.resourcePackageName().replaceAll("\\.", File.separator));
    if (!javaSourceDirectory.isDirectory()) {
        throw new MojoExecutionException(
                "Java sources directory not found: " + javaSourceDirectory.getAbsolutePath());
    }

    List<String> classpathElements;
    try {
        classpathElements = mavenProject.getCompileClasspathElements();
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Failed to get compile classpath elements.", e);
    }

    List<URL> classpaths = new ArrayList<>();
    for (String element : classpathElements) {
        try {
            classpaths.add(new File(element).toURI().toURL());
        } catch (MalformedURLException e) {
            throw new MojoExecutionException(element + " is an invalid classpath element.", e);
        }
    }

    return Project.builder() //
            .mavenProject(mavenProject) //
            .properties(properties) //
            .clientPackageName(clientPackagename) //
            .contextPackageName(contextPackageName) //
            .apiPackageName(apiPackageName) //
            .implPackageName(implPackageName) //
            .clientDirectory(clientDirectory) //
            .javaSourceDirectory(javaSourceDirectory) //
            .classpaths(classpaths) //
            .build();
}

From source file:com.flipkart.masquerade.Masque.java

License:Apache License

public ClassLoader getClassLoader(MavenProject project, final ClassLoader parent, Log log)
        throws DependencyResolutionRequiredException {

    @SuppressWarnings("unchecked")
    List<String> classpathElements = project.getCompileClasspathElements();

    final List<URL> classpathUrls = new ArrayList<URL>(classpathElements.size());

    for (String classpathElement : classpathElements) {
        try {/*from  w  w w .  j a va2  s  . co  m*/
            log.debug("Adding project artifact to classpath: " + classpathElement);
            classpathUrls.add(new File(classpathElement).toURI().toURL());
        } catch (MalformedURLException e) {
            log.debug("Unable to use classpath entry as it could not be understood as a valid URL: "
                    + classpathElement, e);
        }
    }

    return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
        @Override
        public ClassLoader run() {
            return new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]), parent);
        }
    });

}

From source file:com.googlecode.jsonschema2pojo.integration.util.CodeGenerationHelper.java

License:Apache License

private static MavenProject getMockProject() throws DependencyResolutionRequiredException {

    MavenProject project = mock(MavenProject.class);
    when(project.getCompileClasspathElements()).thenReturn(new ArrayList<String>());

    return project;
}

From source file:com.googlecode.jsonschema2pojo.maven.ProjectClasspath.java

License:Apache License

/**
 * Provides a class loader that can be used to load classes from this
 * project classpath.// w  w w. java  2s. co  m
 * 
 * @param parent
 *            a classloader which should be used as the parent of the newly
 *            created classloader.
 * @param log
 *            object to which details of the found/loaded classpath elements
 *            can be logged.
 * 
 * @return a classloader that can be used to load any class that is
 *         contained in the set of artifacts that this project classpath is
 *         based on.
 * @throws DependencyResolutionRequiredException
 *             if maven encounters a problem resolving project dependencies
 */
public ClassLoader getClassLoader(MavenProject project, final ClassLoader parent, Log log)
        throws DependencyResolutionRequiredException {

    @SuppressWarnings("unchecked")
    List<String> classpathElements = project.getCompileClasspathElements();

    final List<URL> classpathUrls = new ArrayList<URL>(classpathElements.size());

    for (String classpathElement : classpathElements) {

        try {
            log.debug("Adding project artifact to classpath: " + classpathElement);
            classpathUrls.add(new File(classpathElement).toURI().toURL());
        } catch (MalformedURLException e) {
            log.debug("Unable to use classpath entry as it could not be understood as a valid URL: "
                    + classpathElement, e);
        }

    }

    return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
        @Override
        public ClassLoader run() {
            return new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]), parent);
        }
    });

}

From source file:com.guidewire.build.plugins.ijinstrument.Util.java

License:Apache License

/**
 * Create {@link com.intellij.ant.PseudoClassLoader} based on the resolved dependencies.
 * @return/*from  w w  w .j a  v a2s.  com*/
 * @throws org.apache.maven.plugin.MojoFailureException
 */
public static PseudoClassLoader createPseudoClassLoader(MavenProject project) throws MojoFailureException {
    List<URL> classpath = Lists.newArrayList();
    try {

        for (String entry : project.getCompileClasspathElements()) {
            File file = new File(entry);
            classpath.add(file.toURI().toURL());
        }
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoFailureException("Cannot resolve runtime classpath dependency", e);
    } catch (MalformedURLException e) {
        throw new MojoFailureException("Cannot resolve runtime classpath dependency", e);
    }
    return new PseudoClassLoader(classpath.toArray(new URL[0]));
}

From source file:com.liferay.maven.plugins.AbstractToolsLiferayMojo.java

License:Open Source License

protected List<String> getProjectClassPath() throws Exception {
    List<String> projectClassPath = new ArrayList<String>();

    projectClassPath.addAll(getToolsClassPath());

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

    classPathMavenProjects.add(project);

    for (Object object : project.getDependencyArtifacts()) {
        Artifact artifact = (Artifact) object;

        ArtifactHandler artifactHandler = artifact.getArtifactHandler();

        if (!artifactHandler.isAddedToClasspath()) {
            continue;
        }/*from w  w  w  .jav  a2 s .c o m*/

        MavenProject dependencyMavenProject = resolveProject(artifact);

        if (dependencyMavenProject == null) {
            continue;
        } else {
            getLog().debug("Resolved dependency project " + dependencyMavenProject);
        }

        List<String> compileSourceRoots = dependencyMavenProject.getCompileSourceRoots();

        if (compileSourceRoots.isEmpty()) {
            continue;
        }

        getLog().debug("Adding project to class path " + dependencyMavenProject);

        classPathMavenProjects.add(dependencyMavenProject);
    }

    for (MavenProject classPathMavenProject : classPathMavenProjects) {
        for (Object object : classPathMavenProject.getCompileClasspathElements()) {

            String path = (String) object;

            getLog().debug("Class path element " + path);

            File file = new File(path);

            URI uri = file.toURI();

            URL url = uri.toURL();

            projectClassPath.add(url.toString());
        }
    }

    getLog().debug("Project class path:");

    for (String path : projectClassPath) {
        getLog().debug("\t" + path);
    }

    return projectClassPath;
}

From source file:com.napramirez.relief.maven.plugins.GenerateConfigurationMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    try {/*from w w  w.java  2s.  co  m*/
        JAXBContext jaxbContext = JAXBContext.newInstance(Configuration.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        Configuration configuration = new Configuration();

        List<Project> projects = new ArrayList<Project>();
        for (MavenProject mavenProject : reactorProjects) {
            if (!MAVEN_PROJECT_PACKAGING_POM.equals(mavenProject.getPackaging())) {
                Project project = new Project();
                project.setName(mavenProject.getName());

                Jre jre = new Jre();
                String jrePath = System.getenv(ENV_VAR_JAVA_HOME);
                if (jrePath != null && !jrePath.trim().isEmpty()) {
                    jre.setPath(jrePath);
                }
                project.setJre(jre);

                project.setBuildDirectory(mavenProject.getBuild().getOutputDirectory());
                project.setSources(mavenProject.getCompileSourceRoots());

                Library library = new Library();
                library.setFullPath(mavenProject.getCompileClasspathElements());

                project.setLibrary(library);
                projects.add(project);
            }
        }

        configuration.setProjects(projects);

        if (!outputDirectory.exists() || !outputDirectory.isDirectory()) {
            if (!outputDirectory.mkdirs()) {
                throw new IOException("Failed to create directory " + outputDirectory.getAbsolutePath());
            }
        }

        File outputFile = new File(outputDirectory, outputFilename);

        marshaller.marshal(configuration, outputFile);

        getLog().info("Successfully generated configuration file " + outputFilename);
    } catch (JAXBException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:com.opengamma.maven.ScriptableScriptGeneratorMojo.java

License:Open Source License

@SuppressWarnings("unchecked")
private static URL[] buildProjectClasspath(MavenProject project) throws MojoExecutionException {
    List<String> classpathElementList;
    try {/* w ww  .j  a  v  a2  s . c  o  m*/
        classpathElementList = project.getCompileClasspathElements();
    } catch (DependencyResolutionRequiredException ex) {
        throw new MojoExecutionException("Error obtaining dependencies", ex);
    }
    return ScriptUtils.getClasspathURLs(classpathElementList);
}