This repository has been archived by the owner on Feb 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
AbstractAptConfiguratorDelegate.java
369 lines (312 loc) · 15.2 KB
/
AbstractAptConfiguratorDelegate.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/*******************************************************************************
* Copyright (c) 2012-2018 Red Hat, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*******************************************************************************/
package org.jboss.tools.maven.apt.internal;
import static org.jboss.tools.maven.apt.internal.utils.ProjectUtils.containsAptProcessors;
import static org.jboss.tools.maven.apt.internal.utils.ProjectUtils.convertToProjectRelativePath;
import static org.jboss.tools.maven.apt.internal.utils.ProjectUtils.filterToResolvedJars;
import static org.jboss.tools.maven.apt.internal.utils.ProjectUtils.getProjectArtifacts;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import org.jboss.tools.maven.apt.internal.utils.ProjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.apt.core.internal.util.FactoryContainer;
import org.eclipse.jdt.apt.core.internal.util.FactoryContainer.FactoryType;
import org.eclipse.jdt.apt.core.internal.util.FactoryPath;
import org.eclipse.jdt.apt.core.util.AptConfig;
import org.eclipse.jdt.apt.core.util.IFactoryPath;
import org.eclipse.jdt.core.IClasspathAttribute;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.PluginExecution;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.project.MavenProject;
import org.eclipse.m2e.core.MavenPlugin;
import org.eclipse.m2e.core.embedder.IMaven;
import org.eclipse.m2e.core.project.IMavenProjectFacade;
import org.eclipse.m2e.core.project.configurator.AbstractBuildParticipant;
import org.eclipse.m2e.core.project.configurator.AbstractProjectConfigurator;
import org.eclipse.m2e.jdt.IClasspathDescriptor;
import org.eclipse.m2e.jdt.IClasspathEntryDescriptor;
/**
* AbstractAptConfiguratorDelegate
*
* @author Fred Bricon
*/
@SuppressWarnings("restriction")
public abstract class AbstractAptConfiguratorDelegate implements AptConfiguratorDelegate {
private static final String M2E_APT_KEY = "m2e-apt";
private static final String M2_REPO = "M2_REPO";
private static final Logger LOG = LoggerFactory.getLogger(AbstractAptConfiguratorDelegate.class);
private static Method setGenTestSrcDirMethod = null;
static {
try {
setGenTestSrcDirMethod = AptConfig.class.getMethod("setGenTestSrcDir", IJavaProject.class, String.class);
} catch(NoSuchMethodException | SecurityException ex) {
// ignore
}
}
protected IMavenProjectFacade mavenFacade;
protected MavenSession mavenSession;
protected IMaven maven;
public AbstractAptConfiguratorDelegate() {
maven = MavenPlugin.getMaven();
}
@Override
public void setSession(MavenSession mavenSession) {
this.mavenSession = mavenSession;
}
@Override
public void setFacade(IMavenProjectFacade mavenProjectFacade) {
this.mavenFacade = mavenProjectFacade;
}
@Override
public boolean isIgnored(IProgressMonitor monitor) throws CoreException {
return false;
}
@Override
public AbstractBuildParticipant getMojoExecutionBuildParticipant(MojoExecution execution) {
return null;
}
/**
* Configures APT for the specified Maven project.
*/
@Override
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();
File generatedTestSourcesDirectory = configuration.getTestOutputDirectory();
// If this project has no valid generatedSourcesDirectory, we have nothing to do
if(generatedSourcesDirectory == null && generatedTestSourcesDirectory == null) {
return;
}
IJavaProject javaProject = JavaCore.create(eclipseProject);
//The plugin dependencies are added first to the classpath
LinkedHashSet<File> resolvedJarArtifacts = new LinkedHashSet<>(getJars(configuration.getDependencies()));
// Get the project's dependencies
if(configuration.isAddProjectDependencies()) {
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());
if(generatedSourcesDirectory != null) {
// Configure APT output path
File generatedSourcesRelativeDirectory = convertToProjectRelativePath(eclipseProject, generatedSourcesDirectory);
String generatedSourcesRelativeDirectoryPath = generatedSourcesRelativeDirectory.getPath();
AptConfig.setGenSrcDir(javaProject, generatedSourcesRelativeDirectoryPath);
}
if(generatedTestSourcesDirectory != null && setGenTestSrcDirMethod != null) {
// Configure APT output path
File generatedTestSourcesRelativeDirectory = convertToProjectRelativePath(eclipseProject, generatedTestSourcesDirectory);
String generatedTestSourcesRelativeDirectoryPath = generatedTestSourcesRelativeDirectory.getPath();
try {
setGenTestSrcDirMethod.invoke(null, javaProject, generatedTestSourcesRelativeDirectoryPath);
} catch(IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
}
}
/*
* 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<>(resolvedJarArtifacts);
Collections.reverse(resolvedJarArtifactsInReverseOrder);
IFactoryPath factoryPath = AptConfig.getDefaultFactoryPath(javaProject);
//Quick fix for https://github.com/jbosstools/m2e-apt/issues/65: Disable all plugins APs.
//Since they're unknown to Maven, they represent a configuration mismatch between Maven and Eclipse
for ( FactoryContainer fc : ((FactoryPath)factoryPath).getEnabledContainers().keySet()) {
if (FactoryType.PLUGIN.equals(fc.getType())) {
factoryPath.disablePlugin(fc.getId());
}
}
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.getRawProcessorOptions(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);
}
private List<File> getJars(List<File> files) {
if (files == null || files.isEmpty()) {
return Collections.emptyList();
}
List<File> jars = new ArrayList<>(files);
Iterator<File> ite = jars.iterator();
while(ite.hasNext()) {
File jar = ite.next();
if (!ProjectUtils.isJar(jar)){
ite.remove();
}
}
return jars;
}
@Override
public void configureClasspath(IClasspathDescriptor classpath, IProgressMonitor monitor) throws CoreException {
AnnotationProcessorConfiguration configuration = getAnnotationProcessorConfiguration(monitor);
if((configuration == null) || !configuration.isAnnotationProcessingEnabled()) {
return;
}
//Add generated source directory to classpath
File generatedSourcesDirectory = configuration.getOutputDirectory();
MavenProject mavenProject = mavenFacade.getMavenProject();
IProject eclipseProject = mavenFacade.getProject();
if(generatedSourcesDirectory != null) {
addToClassPath(eclipseProject, generatedSourcesDirectory, null /* targetdirectory */, classpath, false);
}
//Add generated test source directory to classpath
File generatedTestSourcesDirectory = configuration.getTestOutputDirectory();
if(generatedTestSourcesDirectory != null) {
File outputFolder = new File(mavenProject.getBuild().getTestOutputDirectory());
addToClassPath(eclipseProject, generatedTestSourcesDirectory, outputFolder, classpath, true);
}
}
protected abstract AnnotationProcessorConfiguration getAnnotationProcessorConfiguration(IProgressMonitor monitor)
throws CoreException;
private void addToClassPath(IProject project, File sourceDirectory, File targetDirectory,
IClasspathDescriptor classpath, boolean isTest) {
// Get the generated annotation sources directory as an IFolder
File generatedSourcesRelativeDirectory = convertToProjectRelativePath(project, sourceDirectory);
String generatedSourcesRelativeDirectoryPath = generatedSourcesRelativeDirectory.getPath();
IFolder generatedSourcesFolder = project.getFolder(generatedSourcesRelativeDirectoryPath);
// Get the output folder to use as an IPath
IPath outputPath = null;
if(targetDirectory != null) {
File outputRelativeFile = convertToProjectRelativePath(project, targetDirectory);
IFolder outputFolder = project.getFolder(outputRelativeFile.getPath());
outputPath = outputFolder.getFullPath();
}
// Create the includes & excludes specifiers
IPath[] includes = new IPath[] {};
IPath[] excludes = new IPath[] {};
// If the source folder is non-nested, add it
if((generatedSourcesFolder != null) && generatedSourcesFolder.getProject().equals(project)) {
IClasspathEntryDescriptor enclosing = getEnclosingEntryDescriptor(classpath,
generatedSourcesFolder.getFullPath());
if((enclosing == null) || (getEntryDescriptor(classpath, generatedSourcesFolder.getFullPath()) != null)) {
IClasspathEntryDescriptor entry = classpath.addSourceEntry(generatedSourcesFolder.getFullPath(), outputPath,
includes, excludes, true);
entry.setClasspathAttribute(IClasspathAttribute.IGNORE_OPTIONAL_PROBLEMS, "true"); //$NON-NLS-1$
entry.setClasspathAttribute(M2E_APT_KEY, "true"); //$NON-NLS-1$
if(isTest && setGenTestSrcDirMethod != null) {
for(IClasspathEntry classpathEntry : classpath.getEntries()) {
// test source folder should be found with test attribute, unless the property m2e.disableTestClasspathFlag is in effect.
// (don't directly check for the property because only newer m2e versions handle it)
for(IClasspathAttribute attribute : classpathEntry.getExtraAttributes()) {
if("test".equals(attribute.getName()) && "true".equals(attribute.getValue())) { //$NON-NLS-1$ //$NON-NLS-2$
entry.setClasspathAttribute("test", "true"); //$NON-NLS-1$ //$NON-NLS-2$
break;
}
}
}
}
}
} else {
if(generatedSourcesFolder != null) {
classpath.removeEntry(generatedSourcesFolder.getFullPath());
}
}
}
/**
* Returns the {@link IClasspathEntryDescriptor} in the specified {@link IClasspathDescriptor} that is a prefix of the
* specified {@link IPath}.
*
* @param classpath the {@link IClasspathDescriptor} to be searched for a matching {@link IClasspathEntryDescriptor}
* @param path the {@link IPath} to find a matching {@link IClasspathEntryDescriptor} for
* @return the {@link IClasspathEntryDescriptor} in the specified {@link IClasspathDescriptor} that is a prefix of the
* specified {@link IPath}
*/
private static IClasspathEntryDescriptor getEnclosingEntryDescriptor(IClasspathDescriptor classpath, IPath path) {
for(IClasspathEntryDescriptor cped : classpath.getEntryDescriptors()) {
if(cped.getPath().isPrefixOf(path)) {
return cped;
}
}
return null;
}
private IClasspathEntryDescriptor getEntryDescriptor(IClasspathDescriptor classpath, IPath fullPath) {
List<IPath> stalePaths = new ArrayList<>();
IClasspathEntryDescriptor matchingDescriptor = null;
for(IClasspathEntryDescriptor cped : classpath.getEntryDescriptors()) {
if(cped.getPath().equals(fullPath)) {
matchingDescriptor = cped;
} else if(Boolean.valueOf(cped.getClasspathAttributes().get(M2E_APT_KEY))) {
stalePaths.add(cped.getPath());
}
}
for(IPath stalePath : stalePaths) {
classpath.removeEntry(stalePath);
}
return matchingDescriptor;
}
protected <T> T getParameterValue(String parameter, Class<T> asType, MavenSession session,
MojoExecution mojoExecution) throws CoreException {
PluginExecution execution = new PluginExecution();
execution.setConfiguration(mojoExecution.getConfiguration());
return maven.getMojoParameterValue(parameter, asType, session, mojoExecution.getPlugin(), execution,
mojoExecution.getGoal());
}
}