compilerOptions;
81 |
82 | /**
83 | * A list of inclusion package filters for the apt processor.
84 | *
85 | * If not specified all sources will be used for apt processor
86 | *
87 | *
88 | * e.g.:
89 | * <includes>
90 | * <include>com.mypackge.**.bo.**</include>
91 | * </includes>
92 | *
93 | *
94 | * will include all files which match com/mypackge/ ** /bo/ ** / *.java
95 | *
96 | * @parameter
97 | */
98 | private Set includes = new HashSet();
99 |
100 | /**
101 | * @parameter
102 | */
103 | private boolean showWarnings = false;
104 |
105 | /**
106 | * @parameter
107 | */
108 | private boolean logOnlyOnError = false;
109 |
110 | /**
111 | * @parameter expression="${plugin.artifacts}" readonly=true required=true
112 | */
113 | private List pluginArtifacts;
114 |
115 | /**
116 | * A list of additional source roots for the apt processor
117 | *
118 | * @parameter required=false
119 | */
120 | private List additionalSourceRoots;
121 |
122 | /**
123 | * A list of additional test source roots for the apt processor
124 | *
125 | * @parameter required=false
126 | */
127 | private List additionalTestSourceRoots;
128 |
129 | /**
130 | * @parameter
131 | */
132 | private boolean ignoreDelta = true;
133 |
134 | @SuppressWarnings("unchecked")
135 | private String buildCompileClasspath() {
136 | List pathElements = null;
137 | try {
138 | if (isForTest()) {
139 | pathElements = project.getTestClasspathElements();
140 | } else {
141 | pathElements = project.getCompileClasspathElements();
142 | }
143 | } catch (DependencyResolutionRequiredException e) {
144 | super.getLog().warn("exception calling getCompileClasspathElements", e);
145 | return null;
146 | }
147 |
148 | if (pluginArtifacts != null) {
149 | for (Artifact a : pluginArtifacts) {
150 | if (a.getFile() != null) {
151 | pathElements.add(a.getFile().getAbsolutePath());
152 | }
153 | }
154 | }
155 |
156 | if (pathElements.isEmpty()) {
157 | return null;
158 | }
159 |
160 | StringBuilder result = new StringBuilder();
161 | int i = 0;
162 | for (i = 0; i < pathElements.size() - 1; ++i) {
163 | result.append(pathElements.get(i)).append(File.pathSeparatorChar);
164 | }
165 | result.append(pathElements.get(i));
166 | return result.toString();
167 | }
168 |
169 | private String buildProcessor() {
170 | if (processors != null) {
171 | StringBuilder result = new StringBuilder();
172 | for (String processor : processors) {
173 | if (result.length() > 0) {
174 | result.append(",");
175 | }
176 | result.append(processor);
177 | }
178 | return result.toString();
179 | } else if (processor != null) {
180 | return processor;
181 | } else {
182 | String error = "Either processor or processors need to be given";
183 | getLog().error(error);
184 | throw new IllegalArgumentException(error);
185 | }
186 | }
187 |
188 | private List buildCompilerOptions(String processor, String compileClassPath,
189 | String outputDirectory) throws IOException {
190 | Map compilerOpts = new LinkedHashMap();
191 |
192 | // Default options
193 | compilerOpts.put("cp", compileClassPath);
194 |
195 | if (sourceEncoding != null) {
196 | compilerOpts.put("encoding", sourceEncoding);
197 | }
198 |
199 | compilerOpts.put("proc:only", null);
200 | compilerOpts.put("processor", processor);
201 |
202 | if (options != null) {
203 | for (Map.Entry entry : options.entrySet()) {
204 | if (entry.getValue() != null) {
205 | compilerOpts.put("A" + entry.getKey() + "=" + entry.getValue(), null);
206 | } else {
207 | compilerOpts.put("A" + entry.getKey() + "=", null);
208 | }
209 |
210 | }
211 | }
212 |
213 | if (outputDirectory != null) {
214 | compilerOpts.put("s", outputDirectory);
215 | }
216 |
217 | if (!showWarnings) {
218 | compilerOpts.put("nowarn", null);
219 | }
220 |
221 | StringBuilder builder = new StringBuilder();
222 | for (File file : getSourceDirectories()) {
223 | if (builder.length() > 0) {
224 | builder.append(";");
225 | }
226 | builder.append(file.getCanonicalPath());
227 | }
228 | compilerOpts.put("sourcepath", builder.toString());
229 |
230 | // User options override default options
231 | if (compilerOptions != null) {
232 | compilerOpts.putAll(compilerOptions);
233 | }
234 |
235 | List opts = new ArrayList(compilerOpts.size() * 2);
236 |
237 | for (Map.Entry compilerOption : compilerOpts.entrySet()) {
238 | opts.add("-" + compilerOption.getKey());
239 | String value = compilerOption.getValue();
240 | if (StringUtils.isNotBlank(value)) {
241 | opts.add(value);
242 | }
243 | }
244 | return opts;
245 | }
246 |
247 | /**
248 | * Filter files for apt processing based on the {@link #includes} filter and
249 | * also taking into account m2e {@link BuildContext} to filter-out unchanged
250 | * files when invoked as incremental build
251 | *
252 | * @param directories
253 | * source directories in which files are located for apt processing
254 | *
255 | * @return files for apt processing. Returns empty set when there is no
256 | * files to process
257 | */
258 | private Set filterFiles(Set directories) {
259 | String[] filters = ALL_JAVA_FILES_FILTER;
260 | if (includes != null && !includes.isEmpty()) {
261 | filters = includes.toArray(new String[includes.size()]);
262 | for (int i = 0; i < filters.length; i++) {
263 | filters[i] = filters[i].replace('.', '/') + JAVA_FILE_FILTER;
264 | }
265 | }
266 |
267 | Set files = new HashSet();
268 | for (File directory : directories) {
269 | // support for incremental build in m2e context
270 | Scanner scanner = buildContext.newScanner(directory, false);
271 | scanner.setIncludes(filters);
272 | scanner.scan();
273 | String[] includedFiles = scanner.getIncludedFiles();
274 |
275 | // check also for possible deletions
276 | if (buildContext.isIncremental() && (includedFiles == null || includedFiles.length == 0)) {
277 | scanner = buildContext.newDeleteScanner(directory);
278 | scanner.setIncludes(filters);
279 | scanner.scan();
280 | includedFiles = scanner.getIncludedFiles();
281 | }
282 |
283 | // get all sources if ignoreDelta and at least one source file has changed
284 | if (ignoreDelta && buildContext.isIncremental() && includedFiles != null && includedFiles.length > 0) {
285 | scanner = buildContext.newScanner(directory, true);
286 | scanner.setIncludes(filters);
287 | scanner.scan();
288 | includedFiles = scanner.getIncludedFiles();
289 | }
290 |
291 | if (includedFiles != null) {
292 | for (String includedFile : includedFiles) {
293 | files.add(new File(scanner.getBasedir(), includedFile));
294 | }
295 | }
296 | }
297 | return files;
298 | }
299 |
300 | /**
301 | * Add messages through the buildContext:
302 | *
303 | * - cli build creates log output
304 | * - m2e build creates markers for eclipse
305 | *
306 | * @param diagnostics
307 | */
308 | private void processDiagnostics(final List> diagnostics) {
309 | for (Diagnostic extends JavaFileObject> diagnostic : diagnostics) {
310 | JavaFileObject javaFileObject = diagnostic.getSource();
311 | if (javaFileObject != null) { // message was created without element parameter
312 | File file = new File(javaFileObject.toUri().getPath());
313 | Kind kind = diagnostic.getKind();
314 | int lineNumber = (int) diagnostic.getLineNumber();
315 | int columnNumber = (int) diagnostic.getColumnNumber();
316 | String message = diagnostic.getMessage(Locale.getDefault());
317 | switch (kind) {
318 | case ERROR:
319 | buildContext.addMessage(file, lineNumber, columnNumber, message, BuildContext.SEVERITY_ERROR, null);
320 | break;
321 | case WARNING:
322 | case MANDATORY_WARNING:
323 | buildContext.addMessage(file, lineNumber, columnNumber, message, BuildContext.SEVERITY_WARNING, null);
324 | break;
325 | case NOTE:
326 | case OTHER:
327 | default:
328 | break;
329 | }
330 | }
331 | }
332 | }
333 |
334 | public void execute() throws MojoExecutionException {
335 | if (getOutputDirectory() == null) {
336 | return;
337 | }
338 | if ("true".equals(System.getProperty("maven.apt.skip"))) {
339 | return;
340 | }
341 |
342 | if (!getOutputDirectory().exists()) {
343 | getOutputDirectory().mkdirs();
344 | }
345 |
346 | // make sure to add compileSourceRoots also during configuration build in m2e context
347 | if (isForTest()) {
348 | project.addTestCompileSourceRoot(getOutputDirectory().getAbsolutePath());
349 | } else {
350 | project.addCompileSourceRoot(getOutputDirectory().getAbsolutePath());
351 | }
352 |
353 | Set sourceDirectories = getSourceDirectories();
354 |
355 | getLog().debug("Using build context: " + buildContext);
356 |
357 | StandardJavaFileManager fileManager = null;
358 |
359 | try {
360 | JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
361 | if (compiler == null) {
362 | throw new MojoExecutionException("You need to run build with JDK or have tools.jar on the classpath."
363 | + "If this occures during eclipse build make sure you run eclipse under JDK as well");
364 | }
365 |
366 | Set files = filterFiles(sourceDirectories);
367 | if (files.isEmpty()) {
368 | getLog().debug("No Java sources found (skipping)");
369 | return;
370 | }
371 |
372 | fileManager = compiler.getStandardFileManager(null, null, null);
373 | Iterable extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(files);
374 | // clean all markers
375 | for (JavaFileObject javaFileObject : compilationUnits1) {
376 | buildContext.removeMessages(new File(javaFileObject.toUri().getPath()));
377 | }
378 |
379 | String compileClassPath = buildCompileClasspath();
380 |
381 | String processor = buildProcessor();
382 |
383 | String outputDirectory = getOutputDirectory().getPath();
384 | File tempDirectory = null;
385 |
386 | if (buildContext.isIncremental()) {
387 | tempDirectory = new File(project.getBuild().getDirectory(), "apt"+System.currentTimeMillis());
388 | tempDirectory.mkdirs();
389 | outputDirectory = tempDirectory.getAbsolutePath();
390 | }
391 |
392 | List compilerOptions = buildCompilerOptions(processor, compileClassPath, outputDirectory);
393 |
394 | Writer out = null;
395 | if (logOnlyOnError) {
396 | out = new StringWriter();
397 | }
398 | ExecutorService executor = Executors.newSingleThreadExecutor();
399 | try {
400 | DiagnosticCollector diagnosticCollector = new DiagnosticCollector();
401 | CompilationTask task = compiler.getTask(out, fileManager, diagnosticCollector, compilerOptions, null, compilationUnits1);
402 | Future future = executor.submit(task);
403 | Boolean rv = future.get();
404 |
405 | if (Boolean.FALSE.equals(rv) && logOnlyOnError) {
406 | getLog().error(out.toString());
407 | }
408 | processDiagnostics(diagnosticCollector.getDiagnostics());
409 | } finally {
410 | executor.shutdown();
411 | if (tempDirectory != null) {
412 | FileSync.syncFiles(tempDirectory, getOutputDirectory());
413 | FileUtils.deleteDirectory(tempDirectory);
414 | }
415 | }
416 |
417 | buildContext.refresh(getOutputDirectory());
418 | } catch (Exception e1) {
419 | getLog().error("execute error", e1);
420 | throw new MojoExecutionException(e1.getMessage(), e1);
421 |
422 | } finally {
423 | if (fileManager != null) {
424 | try {
425 | fileManager.close();
426 | } catch (Exception e) {
427 | getLog().warn("Unable to close fileManager", e);
428 | }
429 | }
430 | }
431 | }
432 |
433 | protected abstract File getOutputDirectory();
434 |
435 | @SuppressWarnings("unchecked")
436 | protected Set getSourceDirectories() {
437 | File outputDirectory = getOutputDirectory();
438 | String outputPath = outputDirectory.getAbsolutePath();
439 | Set directories = new HashSet();
440 | List directoryNames = isForTest() ? getTestCompileSourceRoots()
441 | : getCompileSourceRoots();
442 | for (String name : directoryNames) {
443 | File file = new File(name);
444 | if (!file.getAbsolutePath().equals(outputPath) && file.exists() && file.isDirectory()) {
445 | directories.add(file);
446 | }
447 | }
448 | return directories;
449 | }
450 |
451 |
452 | private List getTestCompileSourceRoots() {
453 | @SuppressWarnings("unchecked")
454 | final List testCompileSourceRoots = project.getTestCompileSourceRoots();
455 | if (additionalTestSourceRoots == null) {
456 | return testCompileSourceRoots;
457 | }
458 | if (getLog().isDebugEnabled()) {
459 | getLog().debug("Adding additional test source roots: " + Joiner.on(", ").skipNulls().join(additionalTestSourceRoots));
460 | }
461 | List sourceRoots = new ArrayList(testCompileSourceRoots);
462 | sourceRoots.addAll(additionalTestSourceRoots);
463 | return sourceRoots;
464 | }
465 |
466 | private List getCompileSourceRoots() {
467 | @SuppressWarnings("unchecked")
468 | final List compileSourceRoots = project.getCompileSourceRoots();
469 | if (additionalSourceRoots == null) {
470 | return compileSourceRoots;
471 | }
472 | if (getLog().isDebugEnabled()) {
473 | getLog().debug("Adding additional source roots: " + Joiner.on(", ").skipNulls().join(additionalSourceRoots));
474 | }
475 | List sourceRoots = new ArrayList(compileSourceRoots);
476 | sourceRoots.addAll(additionalSourceRoots);
477 | return sourceRoots;
478 | }
479 |
480 | protected boolean isForTest() {
481 | return false;
482 | }
483 |
484 | public void setBuildContext(BuildContext buildContext) {
485 | this.buildContext = buildContext;
486 | }
487 |
488 | public void setProject(MavenProject project) {
489 | this.project = project;
490 | }
491 |
492 | public void setProcessors(String[] processors) {
493 | this.processors = processors;
494 | }
495 |
496 | public void setProcessor(String processor) {
497 | this.processor = processor;
498 | }
499 |
500 | public void setSourceEncoding(String sourceEncoding) {
501 | this.sourceEncoding = sourceEncoding;
502 | }
503 |
504 | public void setOptions(Map options) {
505 | this.options = options;
506 | }
507 |
508 | public void setCompilerOptions(Map compilerOptions) {
509 | this.compilerOptions = compilerOptions;
510 | }
511 |
512 | public void setIncludes(Set includes) {
513 | this.includes = includes;
514 | }
515 |
516 | public void setShowWarnings(boolean showWarnings) {
517 | this.showWarnings = showWarnings;
518 | }
519 |
520 | public void setLogOnlyOnError(boolean logOnlyOnError) {
521 | this.logOnlyOnError = logOnlyOnError;
522 | }
523 |
524 | public void setPluginArtifacts(List pluginArtifacts) {
525 | this.pluginArtifacts = pluginArtifacts;
526 | }
527 |
528 | }
529 |
--------------------------------------------------------------------------------
/src/main/java/com/mysema/maven/apt/AddTestCompileSourceRootMojo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2012 Mysema Ltd.
3 | * All rights reserved.
4 | *
5 | */
6 | package com.mysema.maven.apt;
7 |
8 | import java.io.File;
9 |
10 | import org.apache.maven.plugin.AbstractMojo;
11 | import org.apache.maven.plugin.MojoExecutionException;
12 | import org.apache.maven.plugin.MojoFailureException;
13 | import org.apache.maven.project.MavenProject;
14 |
15 | /**
16 | * AddTestCompileSourceRootMojo adds the folder for generated tests sources to the POM
17 | *
18 | * @goal add-test-sources
19 | * @phase generate-sources
20 | * @threadSafe true
21 | */
22 | public class AddTestCompileSourceRootMojo extends AbstractMojo {
23 |
24 | /**
25 | * @parameter expression="${project}" readonly=true required=true
26 | */
27 | private MavenProject project;
28 |
29 | /**
30 | * @parameter
31 | */
32 | private File outputDirectory;
33 |
34 | /**
35 | * @parameter
36 | */
37 | private File testOutputDirectory;
38 |
39 | @Override
40 | public void execute() throws MojoExecutionException, MojoFailureException {
41 | File directory = testOutputDirectory != null ? testOutputDirectory : outputDirectory;
42 | if (!directory.exists()) {
43 | directory.mkdirs();
44 | }
45 | project.addTestCompileSourceRoot(directory.getAbsolutePath());
46 | }
47 |
48 | public void setProject(MavenProject project) {
49 | this.project = project;
50 | }
51 |
52 | public void setOutputDirectory(File outputDirectory) {
53 | this.outputDirectory = outputDirectory;
54 | }
55 |
56 | public void setTestOutputDirectory(File testOutputDirectory) {
57 | this.testOutputDirectory = testOutputDirectory;
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/com/mysema/maven/apt/AnnotationProcessorMojo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2009 Mysema Ltd.
3 | * All rights reserved.
4 | *
5 | */
6 | package com.mysema.maven.apt;
7 |
8 | import java.io.File;
9 |
10 | /**
11 | * AnnotationProcessorMojo calls APT processors for code generation
12 | *
13 | * @goal process
14 | * @phase generate-sources
15 | * @requiresDependencyResolution compile
16 | * @threadSafe true
17 | */
18 | public class AnnotationProcessorMojo extends AbstractProcessorMojo {
19 |
20 | /**
21 | * @parameter
22 | */
23 | private File outputDirectory;
24 |
25 | @Override
26 | public File getOutputDirectory() {
27 | return outputDirectory;
28 | }
29 |
30 | public void setOutputDirectory(File outputDirectory) {
31 | this.outputDirectory = outputDirectory;
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/mysema/maven/apt/FileSync.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2014 Timo Westkämper
3 | * All rights reserved.
4 | *
5 | */
6 | package com.mysema.maven.apt;
7 |
8 | import java.io.File;
9 | import java.io.IOException;
10 | import java.util.Set;
11 |
12 | import com.google.common.collect.Sets;
13 | import com.google.common.io.Files;
14 | import org.apache.commons.io.FileUtils;
15 |
16 | /**
17 | *
18 | */
19 | public class FileSync {
20 |
21 | public static void syncFiles(File source, File target) throws IOException {
22 | Set sourceFiles = Sets.newHashSet(source.list());
23 | Set targetFiles = Sets.newHashSet(target.list());
24 |
25 | // remove files from target that are not in source
26 | for (String targetFile : targetFiles) {
27 | if (!sourceFiles.contains(targetFile)) {
28 | deleteFile(new File(target, targetFile));
29 | }
30 | }
31 |
32 | for (String sourceFile : sourceFiles) {
33 | File file = new File(source, sourceFile);
34 | File file2 = new File(target, sourceFile);
35 | if (file.isFile()) {
36 | copyIfChanged(file, file2);
37 | } else {
38 | file2.mkdir();
39 | syncFiles(file, file2);
40 | }
41 | }
42 | }
43 |
44 | private static void copyIfChanged(File source, File target) throws IOException {
45 | if (target.exists()) {
46 | if (source.length() == target.length() && FileUtils.checksumCRC32(source) == FileUtils.checksumCRC32(target)) {
47 | return;
48 | } else {
49 | target.delete();
50 | }
51 | }
52 | if (!source.renameTo(target)) {
53 | Files.move(source, target);
54 | }
55 | }
56 |
57 | private static void deleteFile(File file) throws IOException {
58 | if (file.isDirectory()) {
59 | FileUtils.deleteDirectory(file);
60 | } else {
61 | file.delete();
62 | }
63 | }
64 |
65 | private FileSync() {}
66 |
67 |
68 | }
69 |
70 |
71 |
--------------------------------------------------------------------------------
/src/main/java/com/mysema/maven/apt/TestAnnotationProcessorMojo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2009 Mysema Ltd.
3 | * All rights reserved.
4 | *
5 | */
6 | package com.mysema.maven.apt;
7 |
8 | import java.io.File;
9 |
10 | /**
11 | * TestAnnotationProcessorMojo calls APT processors for code generation
12 | *
13 | * @goal test-process
14 | * @phase generate-test-sources
15 | * @requiresDependencyResolution test
16 | * @threadSafe true
17 | */
18 | public class TestAnnotationProcessorMojo extends AbstractProcessorMojo {
19 |
20 | /**
21 | * @parameter
22 | */
23 | private File outputDirectory;
24 |
25 | /**
26 | * @parameter
27 | */
28 | private File testOutputDirectory;
29 |
30 | @Override
31 | public File getOutputDirectory() {
32 | return testOutputDirectory != null ? testOutputDirectory : outputDirectory;
33 | }
34 |
35 | @Override
36 | protected boolean isForTest(){
37 | return true;
38 | }
39 |
40 | public void setOutputDirectory(File outputDirectory) {
41 | this.outputDirectory = outputDirectory;
42 | }
43 |
44 | public void setTestOutputDirectory(File testOutputDirectory) {
45 | this.testOutputDirectory = testOutputDirectory;
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/resources/META-INF/m2e/lifecycle-mapping-metadata.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | process
8 | test-process
9 |
10 |
11 |
12 |
13 | true
14 | true
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/src/test/java/com/mysema/maven/apt/AddTestCompileSourceRootMojoTest.java:
--------------------------------------------------------------------------------
1 | package com.mysema.maven.apt;
2 |
3 | import static org.junit.Assert.assertTrue;
4 |
5 | import java.io.File;
6 |
7 | import org.apache.maven.plugin.MojoExecutionException;
8 | import org.apache.maven.plugin.MojoFailureException;
9 | import org.apache.maven.project.MavenProject;
10 | import org.junit.Test;
11 |
12 | public class AddTestCompileSourceRootMojoTest {
13 |
14 | @Test
15 | public void Execute() throws MojoExecutionException, MojoFailureException {
16 | File output = new File("target/generated-sources/java");
17 | MavenProject project = new MavenProject();
18 | AddTestCompileSourceRootMojo mojo = new AddTestCompileSourceRootMojo();
19 |
20 | mojo.setProject(project);
21 | mojo.setOutputDirectory(output);
22 | mojo.execute();
23 |
24 | assertTrue(project.getTestCompileSourceRoots().contains(output.getAbsolutePath()));
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/com/mysema/maven/apt/AnnotationProcessorMojoTest.java:
--------------------------------------------------------------------------------
1 | package com.mysema.maven.apt;
2 |
3 | import static org.junit.Assert.*;
4 | import static org.junit.Assert.assertTrue;
5 |
6 | import java.io.File;
7 | import java.io.IOException;
8 | import java.net.URLClassLoader;
9 | import java.util.Collections;
10 | import java.util.List;
11 | import java.util.Map;
12 |
13 | import org.apache.maven.artifact.Artifact;
14 | import org.apache.maven.artifact.DefaultArtifact;
15 | import org.apache.maven.artifact.DependencyResolutionRequiredException;
16 | import org.apache.maven.artifact.versioning.VersionRange;
17 | import org.apache.maven.plugin.MojoExecutionException;
18 | import org.apache.maven.plugin.logging.Log;
19 | import org.apache.maven.project.MavenProject;
20 | import org.easymock.EasyMock;
21 | import org.junit.After;
22 | import org.junit.Before;
23 | import org.junit.Ignore;
24 | import org.junit.Test;
25 | import org.sonatype.plexus.build.incremental.BuildContext;
26 | import org.sonatype.plexus.build.incremental.DefaultBuildContext;
27 |
28 | import com.google.common.collect.Lists;
29 | import com.google.common.collect.Maps;
30 | import com.google.common.collect.Sets;
31 | import com.mysema.query.apt.QuerydslAnnotationProcessor;
32 | import com.mysema.util.FileUtils;
33 |
34 |
35 | public class AnnotationProcessorMojoTest {
36 |
37 | private File outputDir;
38 |
39 | private MavenProject project;
40 |
41 | private AnnotationProcessorMojo mojo;
42 |
43 | @Before
44 | public void setUp() throws DependencyResolutionRequiredException {
45 | outputDir = new File("target/generated-sources/java");
46 | Log log = EasyMock.createMock(Log.class);
47 | BuildContext buildContext = new DefaultBuildContext();
48 | project = EasyMock.createMock(MavenProject.class);
49 | List sourceRoots = Lists.newArrayList("src/test/resources/project-to-test/src/main/java", "notExisting/sourceRoot/folder");
50 | URLClassLoader loader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
51 | List classpath = ClassPathUtils.getClassPath(loader);
52 | EasyMock.expect(project.getCompileSourceRoots()).andReturn(sourceRoots);
53 | EasyMock.expect(project.getCompileSourceRoots()).andReturn(sourceRoots);
54 | EasyMock.expect(project.getCompileClasspathElements()).andReturn(classpath);
55 | project.addCompileSourceRoot(outputDir.getAbsolutePath());
56 | EasyMock.expectLastCall();
57 | EasyMock.replay(project);
58 |
59 | mojo = new AnnotationProcessorMojo();
60 | mojo.setBuildContext(buildContext);
61 | mojo.setCompilerOptions(Maps.newHashMap());
62 | mojo.setIncludes(Sets.newHashSet());
63 | mojo.setLog(log);
64 | mojo.setLogOnlyOnError(false);
65 | mojo.setOptions(Maps.newHashMap());
66 | mojo.setProcessor(QuerydslAnnotationProcessor.class.getName());
67 | mojo.setProject(project);
68 | mojo.setSourceEncoding("UTF-8");
69 | mojo.setOutputDirectory(outputDir);
70 | }
71 |
72 | @After
73 | public void tearDown() throws IOException {
74 | FileUtils.delete(outputDir);
75 | System.setProperty("maven.apt.skip", "");
76 | }
77 |
78 | @Test
79 | public void Execute() throws MojoExecutionException {
80 | mojo.execute();
81 | EasyMock.verify(project);
82 | assertTrue(new File(outputDir, "com/example/QEntity.java").exists());
83 | }
84 |
85 | @Test
86 | public void Skip() throws MojoExecutionException {
87 | System.setProperty("maven.apt.skip", "true");
88 | mojo.execute();
89 | assertFalse(new File(outputDir, "com/example/QEntity.java").exists());
90 | }
91 |
92 | @Test
93 | public void Processors() throws MojoExecutionException {
94 | mojo.setProcessor(null);
95 | mojo.setProcessors(new String[]{QuerydslAnnotationProcessor.class.getName()});
96 | mojo.execute();
97 | EasyMock.verify(project);
98 | assertTrue(new File(outputDir, "com/example/QEntity.java").exists());
99 | }
100 |
101 | @Test
102 | public void Includes() throws MojoExecutionException {
103 | mojo.setIncludes(Sets.newHashSet("com/example/**"));
104 | mojo.execute();
105 | EasyMock.verify(project);
106 | assertTrue(new File(outputDir, "com/example/QEntity.java").exists());
107 | }
108 |
109 | @Test
110 | public void Options() throws MojoExecutionException {
111 | mojo.setOptions(Collections.singletonMap("querydsl.packageSuffix", ".query"));
112 | mojo.execute();
113 | EasyMock.verify(project);
114 | assertTrue(new File(outputDir, "com/example/query/QEntity.java").exists());
115 | }
116 |
117 | @Test
118 | @Ignore
119 | public void NullOptions() throws MojoExecutionException {
120 | Map options = Maps.newHashMap();
121 | options.put("querydsl.packageSuffix", ".query");
122 | options.put("querydsl.prefix", null);
123 | mojo.setOptions(options);
124 | mojo.execute();
125 | EasyMock.verify(project);
126 | assertTrue(new File(outputDir, "com/example/query/Entity.java").exists());
127 | }
128 |
129 | @Test
130 | public void NoSources() throws MojoExecutionException {
131 | mojo.setIncludes(Sets.newHashSet("xxx"));
132 | mojo.execute();
133 | //EasyMock.verify(project);
134 | assertTrue(outputDir.list() == null || outputDir.list().length == 0);
135 | }
136 |
137 | @Test
138 | public void LogOnlyOnError() throws MojoExecutionException {
139 | mojo.setLogOnlyOnError(true);
140 | mojo.execute();
141 | EasyMock.verify(project);
142 | assertTrue(new File(outputDir, "com/example/QEntity.java").exists());
143 | }
144 |
145 | @Test
146 | public void Artifacts() throws MojoExecutionException {
147 | DefaultArtifact artifact = new DefaultArtifact("a", "b", VersionRange.createFromVersion("0.1"),
148 | "compile", "jar", "", null);
149 | artifact.setFile(new File("target/classes"));
150 | mojo.setPluginArtifacts(Lists.newArrayList(artifact));
151 | mojo.execute();
152 | EasyMock.verify(project);
153 | assertTrue(new File(outputDir, "com/example/QEntity.java").exists());
154 | }
155 |
156 | }
157 |
--------------------------------------------------------------------------------
/src/test/java/com/mysema/maven/apt/AptIntegrationTest.java:
--------------------------------------------------------------------------------
1 | package com.mysema.maven.apt;
2 |
3 | import static org.junit.Assert.assertTrue;
4 |
5 | import java.io.File;
6 | import java.util.Arrays;
7 | import java.util.List;
8 |
9 | import org.apache.maven.it.VerificationException;
10 | import org.apache.maven.it.Verifier;
11 | import org.junit.Test;
12 |
13 | public class AptIntegrationTest {
14 |
15 | @Test
16 | public void exportSources() throws VerificationException {
17 | String projectPath = getProjectPath("project-to-test");
18 | runProject(projectPath, Arrays.asList("clean", "generate-sources"));
19 | assertFileExists(projectPath + "/target/generated-sources/java/com/example/QEntity.java");
20 | }
21 |
22 | @Test
23 | public void exportTestSources() throws VerificationException {
24 | String projectPath = getProjectPath("project-to-test");
25 | runProject(projectPath, Arrays.asList("clean", "generate-test-sources"));
26 | assertFileExists(projectPath + "/target/generated-test-sources/java/com/example/QEntity2.java");
27 | }
28 |
29 | private void runProject(String path, List goals) throws VerificationException {
30 | Verifier verifier = new Verifier(path);
31 | verifier.executeGoals(goals);
32 | verifier.verifyErrorFreeLog();
33 | verifier.resetStreams();
34 | }
35 |
36 | private String getProjectPath(String project) {
37 | return new File("target/test-classes/" + project).getAbsolutePath();
38 | }
39 |
40 | private void assertFileExists(String path) {
41 | assertTrue(new File(path).exists());
42 | }
43 |
44 | }
--------------------------------------------------------------------------------
/src/test/java/com/mysema/maven/apt/ClassPathUtils.java:
--------------------------------------------------------------------------------
1 | package com.mysema.maven.apt;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.io.UnsupportedEncodingException;
6 | import java.net.URL;
7 | import java.net.URLClassLoader;
8 | import java.net.URLDecoder;
9 | import java.util.ArrayList;
10 | import java.util.List;
11 | import java.util.jar.Manifest;
12 |
13 | import com.mysema.codegen.CodegenException;
14 |
15 | public final class ClassPathUtils {
16 |
17 | public static List getClassPath(URLClassLoader cl) {
18 | try {
19 | List paths = new ArrayList();
20 | if (cl.getURLs().length == 1 && cl.getURLs()[0].getPath().contains("surefirebooter")) {
21 | // extract MANIFEST.MF Class-Path entry, since the Java Compiler doesn't handle
22 | // manifest only jars in the classpath correctly
23 | URL url = cl.findResource("META-INF/MANIFEST.MF");
24 | Manifest manifest = new Manifest(url.openStream());
25 | String classpath = (String) manifest.getMainAttributes().getValue("Class-Path");
26 | for (String entry : classpath.split(" ")) {
27 | URL entryUrl = new URL(entry);
28 | String decodedPath = URLDecoder.decode(entryUrl.getPath(), "UTF-8");
29 | paths.add(new File(decodedPath).getAbsolutePath());
30 | }
31 | } else {
32 | for (URL url : cl.getURLs()) {
33 | String decodedPath = URLDecoder.decode(url.getPath(), "UTF-8");
34 | paths.add(new File(decodedPath).getAbsolutePath());
35 | }
36 | }
37 | return paths;
38 | } catch (UnsupportedEncodingException e) {
39 | throw new CodegenException(e);
40 | } catch (IOException e) {
41 | throw new CodegenException(e);
42 | }
43 | }
44 |
45 | private ClassPathUtils() {}
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/test/java/com/mysema/maven/apt/FileSyncTest.java:
--------------------------------------------------------------------------------
1 | package com.mysema.maven.apt;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.nio.file.Paths;
6 |
7 | import com.google.common.base.Charsets;
8 | import com.google.common.io.Files;
9 | import org.junit.Test;
10 | import static org.junit.Assert.*;
11 |
12 | public class FileSyncTest {
13 |
14 | @Test
15 | public void sync1() throws IOException {
16 | File source = Files.createTempDir();
17 | File sourceFile = new File(source, "inSource");
18 | sourceFile.createNewFile();
19 | File sourceFolder = new File(source, "inSourceFolder");
20 | sourceFolder.mkdir();
21 | File sourceFile2 = new File(sourceFolder, "inSource");
22 | sourceFile2.createNewFile();
23 |
24 | File target = Files.createTempDir();
25 | File targetFile = new File(target, "inTarget");
26 | targetFile.createNewFile();
27 |
28 | FileSync.syncFiles(source, target);
29 | assertTrue(new File(target, "inSource").exists());
30 | assertTrue(new File(target, "inSourceFolder" + File.separator + "inSource").exists());
31 | assertFalse(targetFile.exists());
32 |
33 | FileSync.syncFiles(source, target);
34 | }
35 |
36 | @Test
37 | public void sync2() throws IOException {
38 | File source = Files.createTempDir();
39 | File sourceFile = new File(source, "file");
40 | Files.write("abc", sourceFile, Charsets.UTF_8);
41 | File target = Files.createTempDir();
42 | File targetFile = new File(target, "file");
43 | Files.write("abc", targetFile, Charsets.UTF_8);
44 | long modified = targetFile.lastModified();
45 |
46 | FileSync.syncFiles(source, target);
47 | assertEquals(modified, targetFile.lastModified());
48 | }
49 |
50 | @Test
51 | public void sync3() throws IOException {
52 | File source = Files.createTempDir();
53 | File target = Files.createTempDir();
54 | File sourceFile1 = Paths.get(source.getAbsolutePath(), "com","mysema","querydsl","Query.java").toFile();
55 | File sourceFile2 = Paths.get(source.getAbsolutePath(), "com","mysema","Entity.java").toFile();
56 | File targetFile1 = Paths.get(target.getAbsolutePath(), "com","mysema","querydsl","OldQuery.java").toFile();
57 | File targetFile2 = Paths.get(target.getAbsolutePath(), "com","mysema","querydsl","support","Example.java").toFile();
58 | sourceFile1.getParentFile().mkdirs();
59 | sourceFile2.getParentFile().mkdirs();
60 | targetFile1.getParentFile().mkdirs();
61 | targetFile2.getParentFile().mkdirs();
62 | Files.write("abc", sourceFile1, Charsets.UTF_8);
63 | Files.write("def", sourceFile2, Charsets.UTF_8);
64 | Files.write("ghi", targetFile1, Charsets.UTF_8);
65 | Files.write("jkl", targetFile2, Charsets.UTF_8);
66 |
67 | FileSync.syncFiles(source, target);
68 | assertFalse(targetFile1.exists());
69 | assertFalse(targetFile2.exists());
70 | assertFalse(targetFile2.getParentFile().exists());
71 | assertTrue(Paths.get(target.getAbsolutePath(), "com","mysema","querydsl","Query.java").toFile().exists());
72 | assertTrue(Paths.get(target.getAbsolutePath(), "com","mysema","Entity.java").toFile().exists());
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/src/test/java/com/mysema/maven/apt/TestAnnotationProcessorMojoTest.java:
--------------------------------------------------------------------------------
1 | package com.mysema.maven.apt;
2 |
3 | import static org.junit.Assert.assertTrue;
4 |
5 | import java.io.File;
6 | import java.net.URLClassLoader;
7 | import java.util.List;
8 |
9 | import org.apache.maven.artifact.DependencyResolutionRequiredException;
10 | import org.apache.maven.plugin.MojoExecutionException;
11 | import org.apache.maven.plugin.logging.Log;
12 | import org.apache.maven.project.MavenProject;
13 | import org.easymock.EasyMock;
14 | import org.junit.Test;
15 | import org.sonatype.plexus.build.incremental.BuildContext;
16 | import org.sonatype.plexus.build.incremental.DefaultBuildContext;
17 |
18 | import com.google.common.collect.Lists;
19 | import com.google.common.collect.Maps;
20 | import com.google.common.collect.Sets;
21 | import com.mysema.query.apt.QuerydslAnnotationProcessor;
22 |
23 |
24 | public class TestAnnotationProcessorMojoTest {
25 |
26 | @Test
27 | public void Execute() throws MojoExecutionException, DependencyResolutionRequiredException {
28 | File outputDir = new File("target/generated-test-sources/java");
29 | Log log = EasyMock.createMock(Log.class);
30 | BuildContext buildContext = new DefaultBuildContext();
31 | MavenProject project = EasyMock.createMock(MavenProject.class);
32 | List sourceRoots = Lists.newArrayList("src/test/resources/project-to-test/src/test/java");
33 | URLClassLoader loader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
34 | List classpath = ClassPathUtils.getClassPath(loader);
35 | EasyMock.expect(project.getTestCompileSourceRoots()).andReturn(sourceRoots);
36 | EasyMock.expect(project.getTestCompileSourceRoots()).andReturn(sourceRoots);
37 | EasyMock.expect(project.getTestClasspathElements()).andReturn(classpath);
38 | project.addTestCompileSourceRoot(outputDir.getAbsolutePath());
39 | EasyMock.expectLastCall();
40 | EasyMock.replay(project);
41 |
42 | TestAnnotationProcessorMojo mojo = new TestAnnotationProcessorMojo();
43 | mojo.setBuildContext(buildContext);
44 | mojo.setCompilerOptions(Maps.newHashMap());
45 | mojo.setIncludes(Sets.newHashSet());
46 | mojo.setLog(log);
47 | mojo.setLogOnlyOnError(false);
48 | mojo.setOptions(Maps.newHashMap());
49 | mojo.setProcessor(QuerydslAnnotationProcessor.class.getName());
50 | mojo.setProject(project);
51 | mojo.setSourceEncoding("UTF-8");
52 | mojo.setOutputDirectory(outputDir);
53 | mojo.execute();
54 |
55 | EasyMock.verify(project);
56 |
57 | assertTrue(new File(outputDir, "com/example/QEntity2.java").exists());
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/src/test/resources/project-to-test/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | com.mysema.test
6 | version-maven-plugin-test
7 | pom
8 | 0.1.0
9 | Maven - Version plugin
10 |
11 |
12 | 3.6.3
13 |
14 |
15 |
16 |
17 |
18 | com.mysema.maven
19 | apt-maven-plugin
20 | 1.1.3
21 |
22 |
23 |
24 | process
25 |
26 |
27 | target/generated-sources/java
28 | com.mysema.query.apt.QuerydslAnnotationProcessor
29 |
30 |
31 |
32 | test-sources
33 | generate-test-sources
34 |
35 | test-process
36 |
37 |
38 | target/generated-test-sources/java
39 | com.mysema.query.apt.QuerydslAnnotationProcessor
40 |
41 |
42 |
43 |
44 |
45 | com.mysema.querydsl
46 | querydsl-apt
47 | ${querydsl.version}
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
--------------------------------------------------------------------------------
/src/test/resources/project-to-test/src/main/java/com/example/Entity.java:
--------------------------------------------------------------------------------
1 | package com.example;
2 |
3 | import com.mysema.query.annotations.QueryEntity;
4 |
5 | @QueryEntity
6 | public class Entity {
7 |
8 | }
9 |
--------------------------------------------------------------------------------
/src/test/resources/project-to-test/src/test/java/com/example/Entity2.java:
--------------------------------------------------------------------------------
1 | package com.example;
2 |
3 | import com.mysema.query.annotations.QueryEntity;
4 |
5 | @QueryEntity
6 | public class Entity2 {
7 |
8 | }
9 |
--------------------------------------------------------------------------------