Example usage for org.apache.maven.plugin.descriptor PluginDescriptor getClassRealm

List of usage examples for org.apache.maven.plugin.descriptor PluginDescriptor getClassRealm

Introduction

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

Prototype

public ClassRealm getClassRealm() 

Source Link

Usage

From source file:com.github.sdedwards.m2e_nar.internal.MavenUtils.java

License:Apache License

private static <T extends AbstractMojo> T getConfiguredMojo(MavenSession session, MojoExecution mojoExecution,
        Class<T> asType, Log log) throws CoreException {
    MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor();

    PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor();

    ClassRealm pluginRealm = getMyRealm(pluginDescriptor.getClassRealm().getWorld());

    T mojo;/*from  ww  w .j  a  v  a2s  .  c om*/
    try {
        mojo = asType.newInstance();
    } catch (Exception e) {
        throw new CoreException(
                new Status(IStatus.ERROR, MavenNarPlugin.PLUGIN_ID, "Problem when creating mojo", e));
    }

    mojo.setLog(log);

    logger.debug("Configuring mojo " + mojoDescriptor.getId() + " from plugin realm " + pluginRealm);

    Xpp3Dom dom = mojoExecution.getConfiguration();

    PlexusConfiguration pomConfiguration;

    if (dom == null) {
        pomConfiguration = new XmlPlexusConfiguration("configuration");
    } else {
        pomConfiguration = new XmlPlexusConfiguration(dom);
    }

    ExpressionEvaluator expressionEvaluator = new PluginParameterExpressionEvaluator(session, mojoExecution);

    populatePluginFields(mojo, mojoDescriptor, pluginRealm, pomConfiguration, expressionEvaluator);

    return mojo;
}

From source file:com.technophobia.substeps.glossary.SubstepsGlossaryMojo.java

License:Open Source License

@Override
public void executeAfterAllConfigs(Config masterConfig) {

    setupBuildEnvironmentInfo();//from   ww w .  j  av  a  2  s  . c om

    final HashSet<String> loadedClasses = new HashSet<String>();

    final List<StepImplementationsDescriptor> classStepTags = new ArrayList<StepImplementationsDescriptor>();

    final PluginDescriptor pluginDescriptor = (PluginDescriptor) getPluginContext().get("pluginDescriptor");
    final ClassRealm classRealm = pluginDescriptor.getClassRealm();
    final File classes = new File(project.getBuild().getOutputDirectory());
    try {
        classRealm.addURL(classes.toURI().toURL());
    } catch (MalformedURLException e) {
        log.error("MalformedURLException adding outputdir", e);
    }

    if (masterConfig != null) {
        List<Config> configs = SubstepsConfigLoader.splitMasterConfig(masterConfig);

        Set<String> stepImplementationClassNames = new LinkedHashSet<>();
        Set<String> stepImplsToExclude = new LinkedHashSet<>();

        for (Config executionConfig : configs) {

            stepImplementationClassNames
                    .addAll(NewSubstepsExecutionConfig.getStepImplementationClassNames(executionConfig));

            List<String> excluded = NewSubstepsExecutionConfig
                    .getStepImplementationClassNamesGlossaryExcluded(executionConfig);

            if (excluded != null) {
                stepImplsToExclude.addAll(excluded);
            }
        }

        if (stepImplsToExclude != null) {
            stepImplementationClassNames.removeAll(stepImplsToExclude);
        }

        for (final String classToDocument : stepImplementationClassNames) {

            classStepTags.addAll(getStepTags(loadedClasses, classRealm, classToDocument));
        }
    } else {

        for (ExecutionConfig cfg : executionConfigs) {

            for (final String classToDocument : cfg.getStepImplementationClassNames()) {
                classStepTags.addAll(getStepTags(loadedClasses, classRealm, classToDocument));
            }
        }
    }

    if (!classStepTags.isEmpty()) {

        if (glossaryPublisher != null) {

            glossaryPublisher.publish(classStepTags);

        }

        saveJsonFile(classStepTags);
    } else {
        log.error("no results to write out");
    }

}

From source file:hudson.gridmaven.ExecutedMojo.java

License:Open Source License

private Class<?> getMojoClass(MojoDescriptor md, PluginDescriptor pd) throws ClassNotFoundException {
    try {//from  w  w w .java 2s  . c o m
        ClassRealm classRealm = pd.getClassRealm();
        return classRealm == null ? null : classRealm.loadClass(md.getImplementation());
    } catch (NoSuchMethodError e) {
        // maybe we are in maven2 build ClassRealm package has changed
        return getMojoClassForMaven2(md, pd);
    }
}

From source file:org.codehaus.mojo.sonar.Bootstraper.java

License:Open Source License

private void executeMojo(MavenProject project, MavenSession session) throws MojoExecutionException {
    ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    try {//from   www . j a  va  2s  . co m

        RepositoryRequest repositoryRequest = new DefaultRepositoryRequest();
        repositoryRequest.setLocalRepository(session.getLocalRepository());
        repositoryRequest.setRemoteRepositories(project.getPluginArtifactRepositories());

        Plugin plugin = createSonarPlugin();

        List<RemoteRepository> remoteRepositories = session.getCurrentProject().getRemotePluginRepositories();

        PluginDescriptor pluginDescriptor = pluginManager.getPluginDescriptor(plugin, remoteRepositories,
                session.getRepositorySession());

        String goal = "sonar";

        MojoDescriptor mojoDescriptor = pluginDescriptor.getMojo(goal);
        if (mojoDescriptor == null) {
            throw new MojoExecutionException("Unknown mojo goal: " + goal);
        }
        MojoExecution mojoExecution = new MojoExecution(plugin, goal, "sonar" + goal);

        mojoExecution.setConfiguration(convert(mojoDescriptor));

        mojoExecution.setMojoDescriptor(mojoDescriptor);

        // olamy : we exclude nothing and import nothing regarding realm import and artifacts

        DependencyFilter artifactFilter = new DependencyFilter() {
            public boolean accept(DependencyNode arg0, List<DependencyNode> arg1) {
                return true;
            }
        };

        pluginManager.setupPluginRealm(pluginDescriptor, session,
                Thread.currentThread().getContextClassLoader(), Collections.<String>emptyList(),
                artifactFilter);

        Mojo mojo = pluginManager.getConfiguredMojo(Mojo.class, session, mojoExecution);
        Thread.currentThread().setContextClassLoader(pluginDescriptor.getClassRealm());
        mojo.execute();

    } catch (Exception e) {
        throw new MojoExecutionException("Can not execute Sonar", e);
    } finally {
        Thread.currentThread().setContextClassLoader(originalClassLoader);
    }
}

From source file:org.eclipse.m2e.editor.xml.internal.mojo.DefaultMojoParameterMetadata.java

License:Open Source License

public List<MojoParameter> loadMojoParameters(PluginDescriptor desc, MojoDescriptor mojo,
        PlexusConfigHelper helper, IProgressMonitor monitor) throws CoreException {

    if (monitor.isCanceled()) {
        return Collections.emptyList();
    }//  w  ww .j  a va 2s . c  o m
    Class<?> clazz;
    try {
        clazz = mojo.getImplementationClass();
        if (clazz == null) {
            clazz = desc.getClassRealm().loadClass(mojo.getImplementation());
        }
    } catch (ClassNotFoundException | TypeNotPresentException ex) {
        log.warn(ex.getMessage());
        return Collections.emptyList();
    }

    List<Parameter> ps = mojo.getParameters();
    Map<String, Type> properties = helper.getClassProperties(clazz);

    List<MojoParameter> parameters = new ArrayList<>();

    if (ps != null) {
        for (Parameter p : ps) {
            if (monitor.isCanceled()) {
                return Collections.emptyList();
            }
            if (!p.isEditable()) {
                continue;
            }

            Type type = properties.get(p.getName());
            if (type == null) {
                continue;
            }

            helper.addParameter(desc.getClassRealm(), clazz, type, p.getName(), p.getAlias(), parameters,
                    p.isRequired(), p.getExpression(), p.getDescription(), p.getDefaultValue(), monitor);
        }
    }

    return parameters;
}

From source file:org.eclipse.m2e.editor.xml.internal.mojo.MojoParameterMetadataProvider.java

License:Open Source License

public MojoParameter getClassConfiguration(final ArtifactKey pluginKey, final String className)
        throws CoreException {

    try {//from w  w w.j  av a 2  s  .  c  om
        String key = pluginKey.toPortableString() + "/" + className;

        return cache.get(key, new Callable<MojoParameter>() {
            public MojoParameter call() throws Exception {

                return execute(pluginKey, new ICallable<MojoParameter>() {
                    public MojoParameter call(IMavenExecutionContext context, IProgressMonitor monitor)
                            throws CoreException {
                        PluginDescriptor pd = getPluginDescriptor(pluginKey, context, monitor);

                        List<MojoParameter> parameters = null;
                        if (pd != null) {
                            Class<?> clazz;
                            try {
                                clazz = pd.getClassRealm().loadClass(className);
                            } catch (ClassNotFoundException ex) {
                                return null;
                            }
                            parameters = new PlexusConfigHelper().loadParameters(pd.getClassRealm(), clazz,
                                    monitor);
                        }
                        return new MojoParameter("", className, parameters); //$NON-NLS-1$
                    }
                });
            }
        });

    } catch (ExecutionException e) {
        Throwable t = e.getCause();
        if (t instanceof CoreException) {
            throw (CoreException) t;
        }
        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        }
        throw new CoreException(new Status(IStatus.ERROR, IMavenConstants.PLUGIN_ID, -1, e.getMessage(), e));
    }
}

From source file:org.wso2.carbon.config.maven.plugin.ConfigDocumentMojo.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    // get the qualified names of all configuration bean in the project, if array is empty, return without further
    // processing and we not create any configuration document file.
    String[] configurationClasses = getConfigurationClasses();
    if (configurationClasses == null || configurationClasses.length == 0) {
        logger.info(/* w  w  w.j ava 2  s . co m*/
                "Configuration classes doesn't exist in the component, hence configuration file not create");
        return;
    }

    PluginDescriptor descriptor = (PluginDescriptor) getPluginContext().get(PLUGIN_DESCRIPTOR_KEY);
    ClassRealm realm = descriptor.getClassRealm();
    addProjectToClasspath(realm);
    addDependenciesToClasspath(realm);

    // process configuration bean to create configuration document
    for (String configClassName : configurationClasses) {
        Map<String, Object> finalMap = new LinkedHashMap<>();
        try {
            Class configClass = realm.loadClass(configClassName);
            if (configClass != null && configClass.isAnnotationPresent(Configuration.class)) {
                // read configuration annotation
                // Fix the issue #3, set the system.property before creating the object, to notify it is called
                // by maven plugin.
                System.setProperty(ConfigConstants.SYSTEM_PROPERTY_DOC_GENERATION, Boolean.toString(true));
                Configuration configuration = (Configuration) configClass.getAnnotation(Configuration.class);
                Object configObject = configClass.newInstance();
                System.clearProperty(ConfigConstants.SYSTEM_PROPERTY_DOC_GENERATION);
                // add description comment to the root node.
                finalMap.put(COMMENT_KEY_PREFIX + configuration.namespace(),
                        createDescriptionComment(configuration.description()));
                // add root node to the config Map
                finalMap.put(configuration.namespace(), readConfigurationElements(configObject, Boolean.TRUE));
                // write configuration map as a yaml file
                writeConfigurationFile(finalMap, configuration.namespace());
            } else {
                logger.error("Error while loading the configuration class : " + configClassName);
            }
        } catch (ClassNotFoundException e) {
            logger.error("Error while creating new instance of the class : " + configClassName, e);
        } catch (InstantiationException | IllegalAccessException e) {
            logger.error("Error while initializing the configuration class : " + configClassName, e);
        }
    }
}

From source file:org.wso2.carbon.extensions.configuration.maven.plugin.ConfigDocumentMojo.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    // get the qualified names of all configuration bean in the project, if array is empty, return without further
    // processing and we not create any configuration document file.
    String[] configurationClasses = getConfigurationClasses();
    if (configurationClasses == null || configurationClasses.length == 0) {
        logger.info(//from   www  .  j a va2s  . co m
                "Configuration classes doesn't exist in the component, hence configuration file not create");
        return;
    }

    List runtimeClasspathElements;
    try {
        runtimeClasspathElements = project.getRuntimeClasspathElements();
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Error while getting project classpath elements", e);
    }

    PluginDescriptor descriptor = (PluginDescriptor) getPluginContext().get(PLUGIN_DESCRIPTOR_KEY);
    ClassRealm realm = descriptor.getClassRealm();

    for (Object element : runtimeClasspathElements) {
        File elementFile = new File((String) element);
        try {
            realm.addURL(elementFile.toURI().toURL());
        } catch (MalformedURLException e) {
            logger.error("Error while adding URI: " + elementFile.toURI().toString(), e);
        }
    }

    // process configuration bean to create configuration document
    for (String configClassName : configurationClasses) {
        Map<String, Object> finalMap = new LinkedHashMap<>();
        try {
            Class configClass = realm.loadClass(configClassName);
            if (configClass != null && configClass.isAnnotationPresent(Configuration.class)) {
                // read configuration annotation
                Configuration configuration = (Configuration) configClass.getAnnotation(Configuration.class);
                Object configObject = configClass.newInstance();
                // add description comment to the root node.
                finalMap.put(COMMENT_KEY_PREFIX + configuration.namespace(),
                        createDescriptionComment(configuration.description()));
                // add root node to the config Map
                finalMap.put(configuration.namespace(), readConfigurationElements(configObject, Boolean.TRUE));
                // write configuration map as a yaml file
                writeConfigurationFile(finalMap, configuration.namespace());
            } else {
                logger.error("Error while loading the configuration class : " + configClassName);
            }
        } catch (ClassNotFoundException e) {
            logger.error("Error while creating new instance of the class : " + configClassName, e);
        } catch (InstantiationException | IllegalAccessException e) {
            logger.error("Error while initializing the configuration class : " + configClassName, e);
        }
    }
}