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

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

Introduction

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

Prototype

public List<String> getTestClasspathElements() throws DependencyResolutionRequiredException 

Source Link

Usage

From source file:org.jahia.utils.maven.plugin.osgi.FindPackageUsesMojo.java

License:Open Source License

private static Set<String> findClassesThatUsePackage(File jarFile, String packageName, MavenProject project,
        Log log) {/*w w  w  .  j  a v  a  2  s.c o  m*/
    Set<String> classesThatHaveDependency = new TreeSet<String>();
    JarInputStream jarInputStream = null;
    if (jarFile == null) {
        log.warn("File is null !");
        return classesThatHaveDependency;
    }
    if (!jarFile.exists()) {
        log.warn("File " + jarFile + " does not exist !");
        return classesThatHaveDependency;
    }
    log.debug("Scanning JAR " + jarFile + "...");
    try {
        classesThatHaveDependency = ClassDependencyTracker.findDependencyInJar(jarFile, packageName,
                project.getTestClasspathElements());
    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (DependencyResolutionRequiredException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } finally {
        IOUtils.closeQuietly(jarInputStream);
    }
    return classesThatHaveDependency;
}

From source file:org.javagems.core.maven.DebianMojo.java

License:Apache License

/**
 * @see org.apache.maven.plugin.Mojo#execute()
 * @since modified by <a href="mailto:christophe@keyade.com">Christophe Cassagnabere</a> on lines 211-227
 *//*from  w w  w . j a va 2  s  . c  om*/
public void execute() throws MojoExecutionException {
    if (skip) {
        getLog().info("Skipping Antrun execution");
        return;
    }

    MavenProject mavenProject = getMavenProject();

    if (target == null && buildFile == null) {
        getLog().info("No ant target defined - SKIPPED");
        return;
    }

    if (target == null) {
        target = new XmlPlexusConfiguration("target");
    }

    if (buildFile != null) {
        XmlPlexusConfiguration tg = new XmlPlexusConfiguration("target");
        tg.setAttribute("name", targetName);
        XmlPlexusConfiguration ant = new XmlPlexusConfiguration("ant");
        ant.setAttribute("antfile", buildFile);
        ant.addChild(tg);
        target.addChild(ant);
    }

    if (propertyPrefix == null) {
        propertyPrefix = "";
    }

    try {
        Project antProject = new Project();
        File antBuildFile = this.writeTargetToProjectFile();
        ProjectHelper.configureProject(antProject, antBuildFile);
        antProject.init();

        DefaultLogger antLogger = new DefaultLogger();
        antLogger.setOutputPrintStream(System.out);
        antLogger.setErrorPrintStream(System.err);

        if (getLog().isDebugEnabled()) {
            antLogger.setMessageOutputLevel(Project.MSG_DEBUG);
        } else if (getLog().isInfoEnabled()) {
            antLogger.setMessageOutputLevel(Project.MSG_INFO);
        } else if (getLog().isWarnEnabled()) {
            antLogger.setMessageOutputLevel(Project.MSG_WARN);
        } else if (getLog().isErrorEnabled()) {
            antLogger.setMessageOutputLevel(Project.MSG_ERR);
        } else {
            antLogger.setMessageOutputLevel(Project.MSG_VERBOSE);
        }

        antProject.addBuildListener(antLogger);
        antProject.setBaseDir(mavenProject.getBasedir());

        Path p = new Path(antProject);
        p.setPath(StringUtils.join(mavenProject.getCompileClasspathElements().iterator(), File.pathSeparator));

        /* maven.dependency.classpath it's deprecated as it's equal to maven.compile.classpath */
        antProject.addReference("maven.dependency.classpath", p);
        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);

        /* set maven.plugin.classpath with plugin dependencies */
        antProject.addReference("maven.plugin.classpath", getPathFromArtifacts(pluginArtifacts, antProject));

        antProject.addReference(DEFAULT_MAVEN_PROJECT_REFID, getMavenProject());
        antProject.addReference(DEFAULT_MAVEN_PROJECT_HELPER_REFID, projectHelper);
        antProject.addReference("maven.local.repository", localRepository);
        initMavenTasks(antProject);

        // The ant project needs actual properties vs. using expression evaluator when calling an external build
        // file.
        copyProperties(mavenProject, antProject);

        if (getLog().isInfoEnabled()) {
            getLog().info("Executing tasks");
        }

        antProject.executeTarget(antTargetName);

        if (getLog().isInfoEnabled()) {
            getLog().info("Executed tasks");
        }

        copyProperties(antProject, mavenProject);
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("DependencyResolutionRequiredException: " + e.getMessage(), e);
    } catch (BuildException e) {
        StringBuffer sb = new StringBuffer();
        sb.append("An Ant BuildException has occured: " + e.getMessage());
        String fragment = findFragment(e);
        if (fragment != null) {
            sb.append("\n").append(fragment);
        }
        if (!failOnError) {
            getLog().info(sb.toString(), e);
            return; // do not register roots.
        } else {
            throw new MojoExecutionException(sb.toString(), e);
        }
    } catch (Throwable e) {
        throw new MojoExecutionException("Error executing ant tasks: " + e.getMessage(), e);
    }
}

From source file:org.jetbrains.kotlin.projectsextensions.maven.classpath.MavenExtendedClassPath.java

License:Apache License

private List<String> getTestClasspathElements(Project proj) throws DependencyResolutionRequiredException {
    MavenProject mavenProj = MavenHelper.getOriginalMavenProject(proj);
    if (mavenProj == null) {
        return Collections.emptyList();
    }/*w  w  w .  ja  v  a  2s  . c  o  m*/
    List<String> testClasspath = mavenProj.getTestClasspathElements();
    if (testClasspath == null || testClasspath.isEmpty()) {
        KotlinLogger.INSTANCE.logInfo(proj.getProjectDirectory().getPath() + " test classpath is empty");
    }

    return testClasspath;
}

From source file:org.jszip.maven.RunMojo.java

License:Apache License

@SuppressWarnings("unchecked")
private List<String> getClasspathElements(MavenProject project, String scope)
        throws DependencyResolutionRequiredException {
    if ("test".equals(scope)) {
        return project.getTestClasspathElements();
    }/*from  w  ww.  j av a2  s  .  c om*/
    if ("compile".equals(scope)) {
        return project.getCompileClasspathElements();
    }
    if ("runtime".equals(scope)) {
        return project.getRuntimeClasspathElements();
    }
    return Collections.emptyList();
}

From source file:org.jvnet.maven.plugin.antrun.AbstractAntMojo.java

License:Apache License

/**
 * @param antTasks/*from   ww w . ja va2  s. co m*/
 * @param mavenProject
 * @throws MojoExecutionException
 */
protected void executeTasks(Target antTasks, MavenProject mavenProject, List pluginArtifacts)
        throws MojoExecutionException {
    if (antTasks == null) {
        getLog().info("No ant tasks defined - SKIPPED");
        return;
    }

    try {
        //TODO refactor - place the manipulation of the expressionEvaluator into a separated class.
        ExpressionEvaluator exprEvaluator = (ExpressionEvaluator) antTasks.getProject()
                .getReference(AntTargetConverter.MAVEN_EXPRESSION_EVALUATOR_ID);

        Project antProject = antTasks.getProject();

        PropertyHelper propertyHelper = PropertyHelper.getPropertyHelper(antProject);
        propertyHelper.setNext(new AntPropertyHelper(exprEvaluator, mavenProject.getArtifacts(), getLog()));

        DefaultLogger antLogger = new DefaultLogger();
        antLogger.setOutputPrintStream(System.out);
        antLogger.setErrorPrintStream(System.err);
        antLogger.setMessageOutputLevel(getLog().isDebugEnabled() ? Project.MSG_DEBUG : Project.MSG_INFO);

        antProject.addBuildListener(antLogger);
        antProject.setBaseDir(mavenProject.getBasedir());

        Path p = new Path(antProject);
        p.setPath(StringUtils.join(mavenProject.getCompileClasspathElements().iterator(), File.pathSeparator));

        /* maven.dependency.classpath it's deprecated as it's equal to maven.compile.classpath */
        antProject.addReference("maven.dependency.classpath", p);
        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);

        /* set maven.plugin.classpath with plugin dependencies */
        antProject.addReference("maven.plugin.classpath", getPathFromArtifacts(pluginArtifacts, antProject));

        if (getLog().isInfoEnabled()) {
            getLog().info("Executing tasks");
        }

        configureProject(antProject);

        antTasks.execute();

        if (getLog().isInfoEnabled()) {
            getLog().info("Executed tasks");
        }
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("DependencyResolutionRequiredException: " + e.getMessage(), e);
    } catch (BuildException e) {
        throw new MojoExecutionException("An Ant BuildException has occured: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new MojoExecutionException("Error executing ant tasks: " + e.getMessage(), e);
    }
}

From source file:org.levigo.m2e.assertj.internal.AssertJBuildParticipant.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override// w w  w  . jav a  2  s.c  o  m
public Set<IProject> build(int kind, IProgressMonitor monitor) throws Exception {
    final BuildContext buildContext = getBuildContext();

    MavenProject mavenProject = getMavenProjectFacade().getMavenProject(monitor);

    List<String> classpathElements = new ArrayList<String>(mavenProject.getCompileClasspathElements());
    classpathElements.addAll(mavenProject.getTestClasspathElements());

    ClassFileMatcher deltaScanner = new ClassFileMatcher(//
            (List<String>) getMojoParameterValue("packages", List.class, monitor),
            (List<String>) getMojoParameterValue("classes", List.class, monitor),
            (List<String>) getMojoParameterValue("includes", List.class, monitor),
            (List<String>) getMojoParameterValue("excludes", List.class, monitor));

    boolean foundDelta = false;

    // Check for POM change
    Scanner pomScanner = buildContext.newScanner(mavenProject.getFile());
    pomScanner.scan();
    if (pomScanner.getIncludedFiles().length > 0) {
        log.info("###################### Found pom change");

        cleanTargetFolder(monitor);
        foundDelta = true;
    }

    // Check for resource change
    if (!foundDelta)
        for (String classpathElement : classpathElements) {
            File f = new File(classpathElement);
            if (f.isDirectory()) {
                String[] deletions = buildContext.newDeleteScanner(f).getIncludedFiles();
                if (null != deletions && deletions.length > 0) {
                    log.info("###################### Found deletion in " + f);

                    cleanTargetFolder(monitor);
                    foundDelta = true;
                    break;
                } else {
                    Scanner ds = buildContext.newScanner(f);
                    ds.scan();
                    String[] includedFiles = ds.getIncludedFiles();
                    if (includedFiles != null)
                        for (String file : includedFiles) {
                            foundDelta |= deltaScanner.matches(file);
                            log.info("###################### Found matching class file " + file + ": "
                                    + foundDelta);
                            break;
                        }
                }
                log.info("###################### Check for delta in " + f + ": " + foundDelta);
            }

            if (foundDelta)
                break;
        }

    if (!foundDelta) {
        log.info("No changes");
        return null;
    }

    log.info("Running template generation");

    // execute mojo
    Set<IProject> result = super.build(kind, monitor);

    // tell m2e builder to refresh generated files
    final File generated = getTargetDir(monitor);
    if (generated != null) {
        buildContext.refresh(generated);

        /*
         * For some weird reason the java build triggered by buildContext.refresh(generated) above
         * does not (yet) see the changed class file (although we detected the changed class file
         * result). This causes compile errors upon added/removed/updated fields and properties. We
         * schedule another workspace refresh to correct this situation.
         */
        new Job("Refresh generated assertions") {
            @Override
            protected IStatus run(IProgressMonitor monitor) {
                log.info("Refreshing generated assertions");

                IWorkspaceRoot myWorkspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
                try {
                    IJobManager jobManager = Job.getJobManager();
                    jobManager.join(ResourcesPlugin.FAMILY_MANUAL_BUILD, monitor);
                    jobManager.join(ResourcesPlugin.FAMILY_AUTO_BUILD, monitor);

                    myWorkspaceRoot.getFolder(Path.fromOSString(generated.getAbsoluteFile().getCanonicalPath()))
                            .refreshLocal(IResource.DEPTH_INFINITE, monitor);
                } catch (Exception e) {
                    log.error("Failed to refresh the generated assertions", e);
                }
                return Status.OK_STATUS;
            }
        }.schedule();
    }

    return result;
}

From source file:org.lib4j.maven.mojo.MojoUtil.java

License:Open Source License

public static File[] getExecutionClasspash(final MojoExecution execution,
        final PluginDescriptor pluginDescriptor, final MavenProject project,
        final ArtifactRepository localRepository, final ArtifactHandler artifactHandler)
        throws DependencyResolutionRequiredException {
    final List<String> classpath = MojoUtil.getPluginDependencyClassPath(pluginDescriptor, localRepository,
            artifactHandler);/* w  w  w . j a va  2s .c  o  m*/
    classpath.addAll(project.getCompileClasspathElements());
    classpath.addAll(project.getRuntimeClasspathElements());
    if (MojoUtil.isInTestPhase(execution)) {
        classpath.addAll(project.getTestClasspathElements());
        classpath.addAll(MojoUtil.getProjectExecutionArtifactClassPath(project, localRepository));
    }

    final File[] classpathFiles = new File[classpath.size()];
    for (int i = 0; i < classpathFiles.length; i++)
        classpathFiles[i] = new File(classpath.get(i));

    return classpathFiles;
}

From source file:org.sonarsource.scanner.maven.bootstrap.MavenProjectConverter.java

License:Open Source License

private static void populateLibraries(MavenProject pom, Properties props, boolean test)
        throws MojoExecutionException {
    List<File> libraries = new ArrayList<>();
    try {//from  ww w  . j av a2 s.c om
        List<String> classpathElements = test ? pom.getTestClasspathElements()
                : pom.getCompileClasspathElements();
        if (classpathElements != null) {
            for (String classPathString : classpathElements) {
                if (!classPathString.equals(
                        test ? pom.getBuild().getTestOutputDirectory() : pom.getBuild().getOutputDirectory())) {
                    File libPath = resolvePath(classPathString, pom.getBasedir());
                    if (libPath != null && libPath.exists()) {
                        libraries.add(libPath);
                    }
                }
            }
        }
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Unable to populate" + (test ? " test" : "") + " libraries", e);
    }
    if (!libraries.isEmpty()) {
        String librariesValue = StringUtils.join(toPaths(libraries), SEPARATOR);
        if (test) {
            props.setProperty(JAVA_PROJECT_TEST_LIBRARIES, librariesValue);
        } else {
            // Populate both deprecated and new property for backward compatibility
            props.setProperty(PROJECT_LIBRARIES, librariesValue);
            props.setProperty(JAVA_PROJECT_MAIN_LIBRARIES, librariesValue);
        }
    }
}

From source file:org.teleal.lemma.maven.LemmaMojo.java

License:Open Source License

public XHTMLTemplateJavadocPipeline createPipeline(File baseDirectory, List<String> packageNames,
        MavenProject project) throws Exception {
    getLog().info(">>> Generating documentation using source base directory: " + baseDirectory);

    // Yep, the Javadoc tool has its own classpath, we abuse the javac system property to get it into the Gaftercode
    String javadocClasspath = null;
    try {//w w w .  jav  a 2s.  co m

        List<String> classpathElements = (List<String>) project.getTestClasspathElements();
        StringBuilder sb = new StringBuilder();
        for (String classpathElement : classpathElements) {
            sb.append(classpathElement).append(File.pathSeparator);
        }
        if (sb.length() > 0)
            sb.deleteCharAt(sb.length() - 1);
        javadocClasspath = sb.toString();

        if (javadocClasspath != null) {
            getLog().debug("Setting Javadoc classpath: " + javadocClasspath);
            System.setProperty("env.class.path", javadocClasspath); // The Javadoc code reads this env variable!
        }

    } catch (DependencyResolutionRequiredException ex) {
        throw new Exception("Can't get test classpath: " + ex.toString(), ex);
    }

    // Hurray for more logging abstractions!
    Handler loggingAdapter = new Handler() {

        Formatter formatter = new Formatter() {
            @Override
            public String format(LogRecord logRecord) {
                return formatMessage(logRecord);
            }
        };

        @Override
        public void publish(LogRecord logRecord) {
            if (logRecord.getLevel().equals(Level.SEVERE) && getLog().isErrorEnabled()) {
                getLog().error(formatter.format(logRecord));
            } else if (logRecord.getLevel().equals(Level.WARNING) && getLog().isWarnEnabled()) {
                getLog().warn(formatter.format(logRecord));
            } else if (logRecord.getLevel().equals(Level.INFO) && getLog().isInfoEnabled()) {
                getLog().info(formatter.format(logRecord));
            } else if (getLog().isDebugEnabled()) {
                getLog().debug(formatter.format(logRecord));
            }
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    };
    loggingAdapter.setLevel(Level.ALL);
    LoggingUtil.resetRootHandler(loggingAdapter);
    LogManager.getLogManager().getLogger("").setLevel(Level.ALL);

    // Check the configuration
    if (!baseDirectory.canRead()) {
        throw new Exception("Configured 'testSourceDirectory' not found or not readable: " + baseDirectory);
    }

    if (packageNames.size() == 0) {
        // Default to all sub-directories in base directory
        File[] subdirs = baseDirectory.listFiles(new FileFilter() {
            public boolean accept(File file) {
                return file.isDirectory() && file.getName().matches("[a-zA-Z_]+");
            }
        });
        for (File subdir : subdirs) {
            getLog().info("Adding source package for Javadoc processing: " + subdir.getName() + ".*");
            packageNames.add(subdir.getName());
        }
    }

    // Finally, do the work
    return new XHTMLTemplateJavadocPipeline(baseDirectory, packageNames);
}

From source file:se.jguru.nazgul.tools.plugin.checkstyle.exec.DefaultCheckstyleExecutor.java

License:Apache License

private void prepareCheckstylePaths(CheckstyleExecutorRequest request, MavenProject project,
        List<String> classPathStrings, List<String> outputDirectories, Collection<File> sourceDirectories,
        Collection<File> testSourceDirectories) throws CheckstyleExecutorException {
    try {//from  w ww .j  a va 2 s  .  c o m
        outputDirectories.add(project.getBuild().getOutputDirectory());

        if (request.isIncludeTestSourceDirectory() && (testSourceDirectories != null)
                && anyDirectoryExists(testSourceDirectories)) {
            classPathStrings.addAll(project.getTestClasspathElements());
            outputDirectories.add(project.getBuild().getTestOutputDirectory());
        } else {
            classPathStrings.addAll(project.getCompileClasspathElements());
        }
    } catch (DependencyResolutionRequiredException e) {
        throw new CheckstyleExecutorException(e.getMessage(), e);
    }
}