Example usage for org.apache.maven.plugin.descriptor InvalidPluginDescriptorException InvalidPluginDescriptorException

List of usage examples for org.apache.maven.plugin.descriptor InvalidPluginDescriptorException InvalidPluginDescriptorException

Introduction

In this page you can find the example usage for org.apache.maven.plugin.descriptor InvalidPluginDescriptorException InvalidPluginDescriptorException.

Prototype

public InvalidPluginDescriptorException(String message, Throwable cause) 

Source Link

Usage

From source file:org.efaps.maven_java5.EfapsAnnotationDescriptorExtractor.java

License:Open Source License

/**
 * Scan given class name for a mojo (using the annotations).
 *
 * @param _cl         class loader/*from   w  w w . j av  a 2 s. com*/
 * @param _className  class name
 * @return mojo descriptor, or <code>null</code> if the given class is not a
 *         mojo
 * @throws InvalidPluginDescriptorException
 */
private MojoDescriptor scan(final ClassLoader _cl, final String _className)
        throws InvalidPluginDescriptorException {
    final MojoDescriptor mojoDescriptor;
    Class<?> c;
    try {
        c = _cl.loadClass(_className);
    } catch (final ClassNotFoundException e) {
        throw new InvalidPluginDescriptorException("Error scanning class " + _className, e);
    }

    final Goal goalAnno = c.getAnnotation(Goal.class);
    if (goalAnno == null) {
        getLogger().debug("  Not a mojo: " + c.getName());
        mojoDescriptor = null;
    } else {
        mojoDescriptor = new MojoDescriptor();
        mojoDescriptor.setRole(Mojo.ROLE);
        mojoDescriptor.setImplementation(c.getName());
        mojoDescriptor.setLanguage("java");
        mojoDescriptor.setInstantiationStrategy(goalAnno.instantiationStrategy());
        mojoDescriptor.setExecutionStrategy(goalAnno.executionStrategy());
        mojoDescriptor.setGoal(goalAnno.name());
        mojoDescriptor.setAggregator(goalAnno.aggregator());
        mojoDescriptor.setDependencyResolutionRequired(goalAnno.requiresDependencyResolutionScope());
        mojoDescriptor.setDirectInvocationOnly(goalAnno.requiresDirectInvocation());
        mojoDescriptor.setProjectRequired(goalAnno.requiresProject());
        mojoDescriptor.setOnlineRequired(goalAnno.requiresOnline());
        mojoDescriptor.setInheritedByDefault(goalAnno.inheritByDefault());

        if (!Phase.VOID.equals(goalAnno.defaultPhase())) {
            mojoDescriptor.setPhase(goalAnno.defaultPhase().key());
        }

        final Deprecated deprecatedAnno = c.getAnnotation(Deprecated.class);

        if (deprecatedAnno != null) {
            mojoDescriptor.setDeprecated("true");
        }

        final Execute executeAnno = c.getAnnotation(Execute.class);

        if (executeAnno != null) {
            final String lifecycle = nullify(executeAnno.lifecycle());
            mojoDescriptor.setExecuteLifecycle(lifecycle);

            if (Phase.VOID.equals(executeAnno.phase())) {
                mojoDescriptor.setExecutePhase(executeAnno.phase().key());
            }

            final String customPhase = executeAnno.customPhase();

            if (customPhase.length() > 0) {
                if (!Phase.VOID.equals(executeAnno.phase())) {
                    getLogger().warn("Custom phase is overriding \"phase\" field.");
                }
                if (lifecycle == null) {
                    getLogger().warn(
                            "Setting a custom phase without a lifecycle is prone to error. If the phase is not custom, set the \"phase\" field instead.");
                }
                mojoDescriptor.setExecutePhase(executeAnno.customPhase());
            }

            mojoDescriptor.setExecuteGoal(nullify(executeAnno.goal()));
        }

        Class<?> cur = c;
        while (!Object.class.equals(cur)) {
            attachFieldParameters(cur, mojoDescriptor);
            cur = cur.getSuperclass();
        }

        if (getLogger().isDebugEnabled()) {
            getLogger().debug("  Component found: " + mojoDescriptor.getHumanReadableKey());
        }
    }

    return mojoDescriptor;
}

From source file:org.efaps.maven_java5.EfapsAnnotationDescriptorExtractor.java

License:Open Source License

/**
 *
 * @param _project  maven project/*  w ww  . j  a v  a 2  s  .c om*/
 * @return
 * @throws InvalidPluginDescriptorException
 */
protected ClassLoader getClassLoader(final MavenProject _project) throws InvalidPluginDescriptorException {
    final List<URL> urls = new ArrayList<URL>();

    // append all compile dependencies to the urls
    final Set<Artifact> toResolve = new HashSet<Artifact>();
    for (final Object obj : _project.getDependencies()) {
        final Dependency dependency = (Dependency) obj;
        final String scope = dependency.getScope();
        if (isCompileScope(scope)) {
            final Artifact artifact = this.artifactFactory.createArtifact(dependency.getGroupId(),
                    dependency.getArtifactId(), dependency.getVersion(), scope, dependency.getType());
            toResolve.add(artifact);
        }
    }
    try {
        final ArtifactResolutionResult result = this.artifactResolver.resolveTransitively(toResolve,
                _project.getArtifact(), getManagedVersionMap(_project), getLocalRepository(),
                _project.getRemoteArtifactRepositories(), this.artifactMetadataSource, this.filter);
        for (final Object obj : result.getArtifacts()) {
            final Artifact artifact = (Artifact) obj;
            urls.add(artifact.getFile().toURL());
        }
    } catch (final Exception e) {
        throw new InvalidPluginDescriptorException(
                "Failed to resolve transitively artifacts: " + e.getMessage(), e);
    }

    // append compile class path elements
    for (final Object obj : _project.getArtifacts()) {
        final Artifact cpe = (Artifact) obj;
        try {
            urls.add(cpe.getFile().toURL()); // URI().toURL() );
        } catch (final MalformedURLException e) {
            getLogger().warn("Cannot convert '" + cpe + "' to URL", e);
        }
    }

    // append target output directory (where the compiled files are)
    try {
        urls.add(new File(_project.getBuild().getOutputDirectory()).toURL());
    } catch (final MalformedURLException e) {
        getLogger().warn("Cannot convert '" + _project.getBuild().getOutputDirectory() + "' to URL", e);
    }

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("URLS: \n" + urls.toString().replaceAll(",", "\n  "));
    } else if (getLogger().isInfoEnabled()) {
        getLogger().info("URLS: \n" + urls.toString().replaceAll(",", "\n  "));
    }

    return new URLClassLoader(urls.toArray(new URL[urls.size()]), getClass().getClassLoader());
}

From source file:org.efaps.maven_java5.EfapsAnnotationDescriptorExtractor.java

License:Open Source License

/**
 *
 * @param _project//from w  w w.  j av  a 2  s .c  o m
 * @return
 * @throws InvalidPluginDescriptorException
 */
protected Map<String, Artifact> getManagedVersionMap(final MavenProject _project)
        throws InvalidPluginDescriptorException {

    final Map<String, Artifact> map = new HashMap<String, Artifact>();
    final DependencyManagement dependencyManagement = _project.getDependencyManagement();
    final String projectId = _project.getId();

    if ((dependencyManagement != null) && (dependencyManagement.getDependencies() != null)) {
        for (final Object obj : dependencyManagement.getDependencies()) {
            final Dependency d = (Dependency) obj;

            try {
                final VersionRange versionRange = VersionRange.createFromVersionSpec(d.getVersion());
                final Artifact artifact = this.artifactFactory.createDependencyArtifact(d.getGroupId(),
                        d.getArtifactId(), versionRange, d.getType(), d.getClassifier(), d.getScope(),
                        d.isOptional());
                map.put(d.getManagementKey(), artifact);
            } catch (final InvalidVersionSpecificationException e) {
                throw new InvalidPluginDescriptorException(
                        "Unable to parse version '" + d.getVersion() + "' for dependency '"
                                + d.getManagementKey() + "' in project " + projectId + " : " + e.getMessage(),
                        e);
            }
        }
    }
    return map;
}

From source file:org.efaps.maven_java5.EfapsAnnotationDescriptorExtractor.java

License:Open Source License

/**
 * Retrieve the local repository path using the following search pattern:
 * <ol>//from   w  w  w  .j a v a2  s  .c  o  m
 * <li>System Property</li>
 * <li>localRepository specified in user settings file</li>
 * <li><code>${user.home}/.m2/repository</code></li>
 * </ol>
 *
 * @see #PROP_KEY_LOCAL_REPOSITORY_LOCATION
 * @see #PROP_KEY_USER_SETTINGS_XML_LOCATION
 * @see #PROP_KEY_USER_HOME
 */
protected ArtifactRepository getLocalRepository() throws InvalidPluginDescriptorException {
    String localRepositoryPath = System
            .getProperty(EfapsAnnotationDescriptorExtractor.PROP_KEY_LOCAL_REPOSITORY_LOCATION);
    if (localRepositoryPath == null) {

        final File userSettingsPath = new File(
                System.getProperty(EfapsAnnotationDescriptorExtractor.PROP_KEY_USER_SETTINGS_XML_LOCATION)
                        + "");

        try {
            final Settings settings = this.settingsBuilder.buildSettings(userSettingsPath);
            localRepositoryPath = settings.getLocalRepository();
        } catch (final IOException e) {
            throw new InvalidPluginDescriptorException("Error reading settings file", e);
        } catch (final XmlPullParserException e) {
            throw new InvalidPluginDescriptorException(
                    e.getMessage() + e.getDetail() + e.getLineNumber() + e.getColumnNumber());
        }

    }
    if (localRepositoryPath == null) {
        localRepositoryPath = new File(
                new File(System.getProperty(EfapsAnnotationDescriptorExtractor.PROP_KEY_USER_HOME), ".m2"),
                "repository").getAbsolutePath();
    }

    // get local repository path as URL
    final File directory = new File(localRepositoryPath);
    String repositoryUrl = directory.getAbsolutePath();
    if (!repositoryUrl.startsWith("file:")) {
        repositoryUrl = "file://" + repositoryUrl;
    }

    final ArtifactRepository localRepository = new DefaultArtifactRepository("local", repositoryUrl,
            this.artifactRepositoryLayout);

    this.artifactRepositoryFactory.setGlobalUpdatePolicy(ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS);
    this.artifactRepositoryFactory.setGlobalChecksumPolicy(ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN);

    return localRepository;
}

From source file:org.jfrog.maven.annomojo.extractor.AnnoMojoDescriptorExtractor.java

License:Apache License

@SuppressWarnings({ "unchecked" })
public List<MojoDescriptor> execute(MavenProject project, PluginDescriptor pluginDescriptor)
        throws InvalidPluginDescriptorException {
    List<String> sourceRoots = project.getCompileSourceRoots();
    Set<String> sourcePathElements = new HashSet<String>();
    String srcRoot = null;/*from  www. jav a 2s. co  m*/
    try {
        for (String sourceRoot : sourceRoots) {
            srcRoot = sourceRoot;
            List<File> files = FileUtils.getFiles(new File(srcRoot), "**/*.java", null, true);
            for (File file : files) {
                String path = file.getPath();
                sourcePathElements.add(path);
            }
        }
    } catch (Exception e) {
        throw new InvalidPluginDescriptorException("Failed to get source files from " + srcRoot, e);
    }
    List<String> argsList = new ArrayList<String>();
    argsList.add("-nocompile");
    argsList.add("-cp");
    StringBuilder cp = new StringBuilder();
    //Add the compile classpath
    List<String> compileClasspathElements;
    try {
        compileClasspathElements = project.getCompileClasspathElements();
    } catch (DependencyResolutionRequiredException e) {
        throw new InvalidPluginDescriptorException("Failed to get compileClasspathElements.", e);
    }
    for (String ccpe : compileClasspathElements) {
        appendToPath(cp, ccpe);
    }

    //Add the current CL classptah
    URL[] urls = ((URLClassLoader) getClass().getClassLoader()).getURLs();
    for (URL url : urls) {
        String path;
        try {
            path = url.getPath();
        } catch (Exception e) {
            throw new InvalidPluginDescriptorException("Failed to get classpath files from " + url, e);
        }
        appendToPath(cp, path);
    }

    // Attempts to add dependencies to the classpath so that parameters inherited from abstract mojos in other
    // projects will be processed.
    Set s = project.getDependencyArtifacts();
    if (s != null) {
        for (Object untypedArtifact : project.getDependencyArtifacts()) {
            if (untypedArtifact instanceof Artifact) {
                Artifact artifact = (Artifact) untypedArtifact;
                File artifactFile = artifact.getFile();
                if (artifactFile != null) {
                    appendToPath(cp, artifactFile.getAbsolutePath());
                }
            }
        }
    }

    String classpath = cp.toString();
    debug("cl=" + classpath);
    argsList.add(classpath);
    argsList.addAll(sourcePathElements);
    String[] args = argsList.toArray(new String[argsList.size()]);
    List<MojoDescriptor> descriptors = new ArrayList<MojoDescriptor>();
    MojoDescriptorTls.setDescriptors(descriptors);
    try {
        Main.process(new MojoApf(pluginDescriptor), new PrintWriter(System.out), args);
    } catch (Throwable t) {
        //TODO: [by yl] This is never caught - apt swallows the exception.
        //Use the TLS to hold thrown exception
        throw new InvalidPluginDescriptorException("Failed to extract plugin descriptor.", t);
    }
    return MojoDescriptorTls.getDescriptors();
}