Example usage for org.eclipse.jdt.apt.core.util AptConfig setEnabled

List of usage examples for org.eclipse.jdt.apt.core.util AptConfig setEnabled

Introduction

In this page you can find the example usage for org.eclipse.jdt.apt.core.util AptConfig setEnabled.

Prototype

public static void setEnabled(IJavaProject jproject, boolean enabled) 

Source Link

Document

Turn annotation processing on or off for this project.

Usage

From source file:org.jboss.tools.m2e.extras.AptProjectConfigurator.java

License:Open Source License

@Override
public void configure(ProjectConfigurationRequest request, IProgressMonitor monitor) throws CoreException {
    assertHasNature(request.getProject(), JavaCore.NATURE_ID);

    boolean hasUser = false;
    boolean useEclipseApt = true;
    List<MojoExecution> executions = getMojoExecutions(request, monitor);
    for (MojoExecution execution : executions) {
        boolean temp = useEclipseApt(
                Util.getPluginExecutionMetadata(CONFIGURATOR_ID, request.getMavenProjectFacade(), execution));
        useEclipseApt = temp && useEclipseApt;
        hasUser = hasUser || temp;/*  w  w w. java  2 s.c om*/
    }
    if (!useEclipseApt) {
        if (hasUser) {
            Activator.getDefault().getLog().log(new Status(Status.WARNING, Activator.PLUGIN_ID,
                    "Project has executions configured to use Eclipse APT and Maven APT.  Eclipse APT not configured for project: "
                            + request.getProject().toString()));
        }
        return;
    }

    // configure Eclipse APT builder
    IMavenProjectFacade facade = request.getMavenProjectFacade();
    boolean configured = false;
    for (MojoExecution execution : executions) {
        File sourceOutputDirectory = getParameterValue(SOURCE_OUTPUT_DIRECTORY, File.class,
                request.getMavenSession(), execution);
        if (sourceOutputDirectory == null) {
            continue;
        }
        IPath sourceOutputPath = getFullPath(facade, sourceOutputDirectory);
        IJavaProject project = JavaCore.create(request.getProject());
        AptConfig.setEnabled(project, true);
        AptConfig.setGenSrcDir(project, sourceOutputPath.toPortableString());
        configured = true;
        break;
    }
    if (configured) {
        return;
    }
    Activator.getDefault().getLog().log(new Status(Status.ERROR, Activator.PLUGIN_ID,
            "Unable to configure APT settings for project: " + request.getProject().toString()));
}

From source file:org.jboss.tools.maven.apt.AptProjectConfigurator.java

License:Open Source License

/**
 * Configures APT for the specified Maven project.
 * /*from  w  w w .j av a2s  .  c om*/
 * @param eclipseProject an {@link IProject} reference to the Eclipse project being configured
 * @param mavenProject {@link IMavenProjectFacade} reference to the Maven project being configured
 * @param monitor the {@link IProgressMonitor} to use
 * @throws CoreException Any {@link CoreException}s thrown will be passed through.
 */
private void configureAptForProject(IProject eclipseProject, MavenSession mavenSession,
        IMavenProjectFacade mavenProjectFacade, IProgressMonitor monitor) throws CoreException {
    IJavaProject javaProject = JavaCore.create(eclipseProject);
    File generatedSourcesDirectory = getGeneratedSourcesDirectory(mavenSession, mavenProjectFacade, monitor);

    // If this isn't a Java project, we have nothing to do
    if (!eclipseProject.hasNature(JavaCore.NATURE_ID))
        return;

    // If this project has no valid compiler plugin config, we have nothing to do
    if (generatedSourcesDirectory == null)
        return;

    // Get the project's dependencies
    List<Artifact> artifacts = getProjectArtifacts(mavenProjectFacade);
    List<File> resolvedJarArtifacts = filterToResolvedJars(artifacts);

    // Inspect the dependencies to see if any contain APT processors
    boolean isAnnotationProcessingEnabled = isAnnotationProcessingEnabled(mavenSession, mavenProjectFacade,
            monitor)
            //Will be ignored when org.bsc.maven:maven-processor-plugin is used
            && containsAptProcessors(resolvedJarArtifacts);

    // Enable/Disable APT (depends on whether APT processors were found)
    AptConfig.setEnabled(javaProject, isAnnotationProcessingEnabled);

    //If no annotation processor were found, we should leave.
    if (!isAnnotationProcessingEnabled) {
        return;
    }

    // Configure APT output path
    File generatedSourcesRelativeDirectory = convertToProjectRelativePath(eclipseProject,
            generatedSourcesDirectory);
    String generatedSourcesRelativeDirectoryPath = generatedSourcesRelativeDirectory.getPath();
    AptConfig.setGenSrcDir(javaProject, generatedSourcesRelativeDirectoryPath);

    /* 
     * Add all of the compile-scoped JAR artifacts to a new IFactoryPath (in 
     * addition to the workspace's default entries).
     * 
     * Please note that--until JDT-APT supports project factory path entries 
     * (as opposed to just JARs)--this will be a bit wonky. Specifically, any
     * project dependencies will be excluded, but their transitive JAR
     * dependencies will be included.
     * 
     * Also note: we add the artifacts in reverse order as 
     * IFactoryPath.addExternalJar(File) adds items to the top of the factory 
     * list.
     */
    List<File> resolvedJarArtifactsInReverseOrder = new ArrayList<File>(resolvedJarArtifacts);
    Collections.reverse(resolvedJarArtifactsInReverseOrder);
    IFactoryPath factoryPath = AptConfig.getDefaultFactoryPath(javaProject);
    for (File resolvedJarArtifact : resolvedJarArtifactsInReverseOrder) {
        factoryPath.addExternalJar(resolvedJarArtifact);
    }

    // Apply that IFactoryPath to the project
    AptConfig.setFactoryPath(javaProject, factoryPath);

    // Apply and processor option found on the compiler plugins
    Map<String, String> processorOptions = getProcessorOptions(mavenSession, mavenProjectFacade, monitor);
    if (!processorOptions.isEmpty()) {
        AptConfig.setProcessorOptions(processorOptions, javaProject);
    }
}

From source file:org.jboss.tools.maven.apt.internal.AbstractAptConfiguratorDelegate.java

License:Open Source License

/**
 * Configures APT for the specified Maven project.
 *///from   ww w  . jav a2s  .  c o  m
public void configureProject(IProgressMonitor monitor) throws CoreException {

    IProject eclipseProject = mavenFacade.getProject();

    AnnotationProcessorConfiguration configuration = getAnnotationProcessorConfiguration(monitor);
    if (configuration == null) {
        return;
    }

    // In case the Javaconfigurator was not called yet (eg. maven-processor-plugin being bound to process-sources, 
    // that project configurator runs first) We need to add the Java Nature before setting the APT config.
    if (!eclipseProject.hasNature(JavaCore.NATURE_ID)) {
        AbstractProjectConfigurator.addNature(eclipseProject, JavaCore.NATURE_ID, monitor);
    }

    File generatedSourcesDirectory = configuration.getOutputDirectory();

    // If this project has no valid generatedSourcesDirectory, we have nothing to do
    if (generatedSourcesDirectory == null)
        return;

    IJavaProject javaProject = JavaCore.create(eclipseProject);

    //The plugin dependencies are added first to the classpath
    LinkedHashSet<File> resolvedJarArtifacts = new LinkedHashSet<File>(configuration.getDependencies());
    // Get the project's dependencies
    List<Artifact> artifacts = getProjectArtifacts(mavenFacade);
    resolvedJarArtifacts.addAll(filterToResolvedJars(artifacts));

    // Inspect the dependencies to see if any contain APT processors
    boolean isAnnotationProcessingEnabled = configuration.isAnnotationProcessingEnabled()
            && containsAptProcessors(resolvedJarArtifacts);

    // Enable/Disable APT (depends on whether APT processors were found)
    AptConfig.setEnabled(javaProject, isAnnotationProcessingEnabled);

    //If no annotation processor is disabled, we can leave.
    if (!isAnnotationProcessingEnabled) {
        return;
    }
    LOG.debug("Enabling APT support on {}", eclipseProject.getName());
    // Configure APT output path
    File generatedSourcesRelativeDirectory = convertToProjectRelativePath(eclipseProject,
            generatedSourcesDirectory);
    String generatedSourcesRelativeDirectoryPath = generatedSourcesRelativeDirectory.getPath();

    AptConfig.setGenSrcDir(javaProject, generatedSourcesRelativeDirectoryPath);

    /* 
     * Add all of the compile-scoped JAR artifacts to a new IFactoryPath (in 
     * addition to the workspace's default entries).
     * 
     * Please note that--until JDT-APT supports project factory path entries 
     * (as opposed to just JARs)--this will be a bit wonky. Specifically, any
     * project dependencies will be excluded, but their transitive JAR
     * dependencies will be included.
     * 
     * Also note: we add the artifacts in reverse order as 
     * IFactoryPath.addExternalJar(File) adds items to the top of the factory 
     * list.
     */
    List<File> resolvedJarArtifactsInReverseOrder = new ArrayList<File>(resolvedJarArtifacts);
    Collections.reverse(resolvedJarArtifactsInReverseOrder);
    IFactoryPath factoryPath = AptConfig.getDefaultFactoryPath(javaProject);

    IPath m2RepoPath = JavaCore.getClasspathVariable(M2_REPO);

    for (File resolvedJarArtifact : resolvedJarArtifactsInReverseOrder) {
        IPath absolutePath = new Path(resolvedJarArtifact.getAbsolutePath());
        //reference jars in a portable way
        if (m2RepoPath != null && m2RepoPath.isPrefixOf(absolutePath)) {
            IPath relativePath = absolutePath.removeFirstSegments(m2RepoPath.segmentCount()).makeRelative()
                    .setDevice(null);
            IPath variablePath = new Path(M2_REPO).append(relativePath);
            factoryPath.addVarJar(variablePath);
        } else {
            //fall back on using absolute references.
            factoryPath.addExternalJar(resolvedJarArtifact);
        }
    }

    Map<String, String> currentOptions = AptConfig.getProcessorOptions(javaProject);
    Map<String, String> newOptions = configuration.getAnnotationProcessorOptions();
    if (!currentOptions.equals(newOptions)) {
        AptConfig.setProcessorOptions(newOptions, javaProject);
    }

    // Apply that IFactoryPath to the project
    AptConfig.setFactoryPath(javaProject, factoryPath);
}

From source file:org.jboss.tools.maven.apt.internal.utils.ProjectUtils.java

License:Open Source License

/**
 * Disable JDT APT on this project/* w w w  . ja v a  2  s  .c o  m*/
 */
public static void disableApt(IProject project) {
    if (project == null) {
        return;
    }

    IJavaProject javaProject = JavaCore.create(project);
    if (javaProject != null && AptConfig.isEnabled(javaProject)) {
        AptConfig.setEnabled(javaProject, false);
    }
}

From source file:org.jboss.tools.maven.apt.tests.M2eAptProjectconfiguratorTest.java

License:Open Source License

public void testDisableAnnotationProcessingFromProject() throws Exception {
    IProject p = importProject("projects/p1/pom.xml");
    waitForJobsToComplete();// ww  w.  j ava2  s  .  c om
    IJavaProject javaProject = JavaCore.create(p);
    assertTrue("JDT APT support was not enabled", AptConfig.isEnabled(javaProject));

    //Manually disable APT support 
    AptConfig.setEnabled(javaProject, false);

    //Disable m2e-apt on the project
    IPreferencesManager preferencesManager = MavenJdtAptPlugin.getDefault().getPreferencesManager();
    preferencesManager.setAnnotationProcessorMode(p, AnnotationProcessingMode.disabled);

    //Update Maven Configuration
    updateProject(p);

    //Check APT support is still disabled
    assertFalse("JDT APT support was enabled", AptConfig.isEnabled(javaProject));

}

From source file:org.maven.ide.eclipse.annotations.AptConfigurator.java

License:Open Source License

/**
 * Configures maven project with associated annotation processors.
 *
 * Limitations:/*from ww  w.j  av  a2  s . c om*/
 * <ul>
 *  <li>There can be only one outputDirectory.</li>
 *  <li>There can be only one configuration per project.</li>
 *  <li>Might not work for processors that must be run in batch mode.</li>
 * </ul>
 *
 * @author Ivica Loncar
 */
@Override
public void configure(final ProjectConfigurationRequest p_request, final IProgressMonitor p_monitor)
        throws CoreException {
    super.configure(p_request, p_monitor);

    IProject project = p_request.getProject();
    if (project.hasNature(JavaCore.NATURE_ID)) {
        // enable annotation processing
        IJavaProject javaProject = JavaCore.create(project);
        AptConfig.setEnabled(javaProject, true);

        // Associate jars containing annotation processors.
        ProcessorConfiguration processorConfiguration = getProcessorConfiguration(p_request, p_monitor);

        List<ArtifactRepository> remoteArtifactRepositories = p_request.getMavenProject()
                .getRemoteArtifactRepositories();
        IMaven maven = MavenPlugin.getMaven();

        IFactoryPath factoryPath = AptConfig.getFactoryPath(javaProject);

        ArtifactMetadata[] artifactsMetadata = processorConfiguration.getProcessorArtifacts();
        for (ArtifactMetadata artifactMetadata : artifactsMetadata) {
            // Q: what about transitive dependencies?
            Artifact artifact = maven.resolve(artifactMetadata.getGroupId(), artifactMetadata.getArtifactId(),
                    artifactMetadata.getVersion(), artifactMetadata.getType(), artifactMetadata.getClassifier(),
                    remoteArtifactRepositories, p_monitor);

            File file = artifact.getFile();
            if ((file == null) || !file.exists() || !file.canRead()) {
                throw new IllegalStateException("Cannot find file for artifact " + artifact + " file:" + file);
            }

            factoryPath.addExternalJar(file);
        }

        AptConfig.setFactoryPath(javaProject, factoryPath);

        Map<String, String> optionMap = processorConfiguration.getOptionMap();
        // we would like to override existing files
        optionMap.put("defaultOverride", "true");
        AptConfig.setProcessorOptions(optionMap, javaProject);

        // output directory for generated sources
        AptConfig.setGenSrcDir(javaProject, processorConfiguration.getOutputDirectory());
        // From http://www.eclipse.org/forums/index.php?t=rview&goto=533747:
        //
        // Batch mode is mainly intended to support processors that can't handle incremental processing:
        // for example, that rely on static variables being properly initialized at the beginning of the run,
        // or that rely on being able to process all the files in a single round rather than one at a time,
        // or that make assumptions about how many rounds of processing will occur before  they exit.
        // Sun's JPA processors do, I think, need to be run in batch mode;
    }
}

From source file:org.maven.ide.querydsl.AptConfigurator.java

License:Open Source License

/**
 * @author Ivica Loncar/*w  ww.j a  va 2s .c  om*/
 */
@Override
public void configure(final ProjectConfigurationRequest p_request, final IProgressMonitor p_monitor)
        throws CoreException {
    super.configure(p_request, p_monitor);

    IProject project = p_request.getProject();
    if (project.hasNature(JavaCore.NATURE_ID)) {
        // enable annotation processing
        IJavaProject javaProject = JavaCore.create(project);
        AptConfig.setEnabled(javaProject, true);

        MavenFacade mavenFacade = new MavenFacade(p_request, p_monitor);
        // Associate annotation processor jar. Since querydsl doesn't use generic apt plugin nor specifies extra dependencies we have to hardcode it.
        QueryDslConfiguration queryDslConfiguration = getQueryDslConfiguration(mavenFacade);
        // IRepositoryRegistry repositoryRegistry = MavenPlugin.getRepositoryRegistry();
        // List<IRepository> repositories = repositoryRegistry.getRepositories(IRepositoryRegistry.SCOPE_LOCAL | IRepositoryRegistry.SCOPE_SETTINGS | IRepositoryRegistry.SCOPE_PROJECT);

        IMaven maven = MavenPlugin.getMaven();

        IPath m2RepoVar = JavaCore.getClasspathVariable(M2_REPO);
        IFactoryPath factoryPath = AptConfig.getFactoryPath(javaProject);

        ArtifactMetadata[] artifactsMetadata = queryDslConfiguration.getProcessorArtifacts();
        for (ArtifactMetadata artifactMetadata : artifactsMetadata) {
            Artifact artifact = mavenFacade.resolve(artifactMetadata);

            File file = artifact.getFile();
            if ((file == null) || !file.exists() || !file.canRead()) {
                throw new IllegalStateException("Cannot find file for artifact " + artifact + " file:" + file);
            }
            String filePath = file.getAbsolutePath();
            IPath path = Path.fromOSString(filePath);

            IPath relativeToM2Repo = path.makeRelativeTo(m2RepoVar);

            IPath jarPath = Path.fromOSString("M2_REPO").append(relativeToM2Repo);

            factoryPath.addVarJar(jarPath);
        }

        AptConfig.setFactoryPath(javaProject, factoryPath);

        Map<String, String> options = new HashMap<String, String>() {
            {
                // we would like to override existing files
                put("defaultOverride", "true");
            }
        };
        AptConfig.setProcessorOptions(options, javaProject);

        AptConfig.setGenSrcDir(javaProject, queryDslConfiguration.getOutputDirectory());
    }
}

From source file:org.springframework.ide.eclipse.boot.properties.editor.util.AptUtils.java

License:Open Source License

/**
 * Enable's JDT APT on a JavaProject. Note: if the project's classpath contains
 * no APT services in jar-dependencies then this does nothing.
 *///w ww .j a  v  a  2  s.  c  o m
public static void configureApt(IJavaProject jp) {
    boolean shouldEnable = false; //becomes true if we find at least one annotation processor.
    try {
        IFactoryPath factoryPath = AptConfig.getDefaultFactoryPath(jp);
        for (File jarFile : JavaProjectUtil.getNonSystemJarDependencies(jp, true)) {
            if (!AnnotationServiceLocator.getAptServiceEntries(jarFile).isEmpty()) {
                shouldEnable = true;
            }
            IPath absolutePath = new Path(jarFile.getAbsolutePath());
            IPath variablePath = useClasspathVariable(absolutePath);
            if (variablePath != null) {
                factoryPath.addVarJar(variablePath);
            } else {
                factoryPath.addExternalJar(jarFile);
            }
        }
        if (shouldEnable) {
            AptConfig.setEnabled(jp, true);
            AptConfig.setFactoryPath(jp, factoryPath);
        } else {
            AptConfig.setEnabled(jp, false);
        }
    } catch (Exception e) {
        SpringPropertiesEditorPlugin.log(e);
    }
}