├── .gitignore ├── .travis.yml ├── LICENSE.txt ├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── mysema │ │ └── maven │ │ └── apt │ │ ├── AbstractProcessorMojo.java │ │ ├── AddTestCompileSourceRootMojo.java │ │ ├── AnnotationProcessorMojo.java │ │ ├── FileSync.java │ │ └── TestAnnotationProcessorMojo.java └── resources │ └── META-INF │ └── m2e │ └── lifecycle-mapping-metadata.xml └── test ├── java └── com │ └── mysema │ └── maven │ └── apt │ ├── AddTestCompileSourceRootMojoTest.java │ ├── AnnotationProcessorMojoTest.java │ ├── AptIntegrationTest.java │ ├── ClassPathUtils.java │ ├── FileSyncTest.java │ └── TestAnnotationProcessorMojoTest.java └── resources └── project-to-test ├── pom.xml └── src ├── main └── java │ └── com │ └── example │ └── Entity.java └── test └── java └── com └── example └── Entity2.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .idea 3 | .DS_Store 4 | target 5 | bin 6 | test-output 7 | *.iml 8 | .idea 9 | .classpath 10 | .project 11 | .settings 12 | /.metadata 13 | .cache 14 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 4 | - oraclejdk7 5 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## apt-maven-plugin 2 | 3 | apt-maven-plugin provides Maven integration of the Java 6 APT functionality. 4 | 5 | [![Build Status](https://travis-ci.org/querydsl/apt-maven-plugin.svg?branch=master)](https://travis-ci.org/querydsl/apt-maven-plugin) 6 | 7 | The supported goals are 8 | 9 | process - to process main sources 10 | test-process - to process test sources 11 | 12 | Here is an example of a configuration 13 | 14 | 15 | com.mysema.maven 16 | apt-maven-plugin 17 | 1.1.3 18 | 19 | 20 | 21 | process 22 | 23 | 24 | target/generated-sources/java 25 | com.mysema.query.apt.jpa.JPAAnnotationProcessor 26 | 27 | 28 | 29 | 30 | 31 | Here is an example for usage with the m2e plugin https://github.com/querydsl/apt-maven-plugin/wiki/m2e-usage 32 | 33 | If you're using AspectJ to introduce artifacts into classes (fields, methods or annotations), then 34 | `apt-maven-plugin` will not work properly and classpath inspecting tools need to be used, such as GenericExporter, 35 | if you use Querydsl. 36 | 37 | 38 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | 6 | com.mysema.home 7 | mysema-source 8 | 0.3.1 9 | 10 | 11 | com.mysema.maven 12 | apt-maven-plugin 13 | maven-plugin 14 | 1.1.4.BUILD-SNAPSHOT 15 | Maven - APT plugin 16 | 17 | 18 | 19 | Apache License, Version 2.0 20 | http://www.apache.org/licenses/LICENSE-2.0.txt 21 | 22 | 23 | 24 | 25 | scm:git:git@github.com:querydsl/maven-apt-plugin.git 26 | git@github.com:querydsl/maven-apt-plugin.git 27 | 28 | 29 | 30 | 2.2.1 31 | 3.6.3 32 | 33 | 34 | 35 | 36 | org.sonatype.plexus 37 | plexus-build-api 38 | 0.0.7 39 | 40 | 41 | org.codehaus.plexus 42 | plexus-utils 43 | 3.0.22 44 | 45 | 46 | 47 | org.apache.maven 48 | maven-plugin-api 49 | ${mvn.version} 50 | 51 | 52 | org.apache.maven 53 | maven-model 54 | ${mvn.version} 55 | 56 | 57 | org.apache.maven 58 | maven-project 59 | ${mvn.version} 60 | 61 | 62 | org.apache.maven.shared 63 | maven-verifier 64 | 1.5 65 | test 66 | 67 | 68 | commons-io 69 | commons-io 70 | 2.4 71 | 72 | 73 | com.google.guava 74 | guava 75 | 18.0 76 | 77 | 78 | 79 | 80 | org.easymock 81 | easymock 82 | 3.3.1 83 | test 84 | 85 | 86 | junit 87 | junit 88 | 4.12 89 | test 90 | 91 | 92 | 93 | com.mysema.querydsl 94 | querydsl-collections 95 | ${querydsl.version} 96 | test 97 | 98 | 99 | com.mysema.querydsl 100 | querydsl-apt 101 | ${querydsl.version} 102 | test 103 | 104 | 105 | 106 | 107 | 108 | 109 | 1.8 110 | 111 | 112 | -Xdoclint:none 113 | 114 | 115 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /src/main/java/com/mysema/maven/apt/AbstractProcessorMojo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009 Mysema Ltd. 3 | * All rights reserved. 4 | * 5 | */ 6 | package com.mysema.maven.apt; 7 | 8 | import javax.tools.Diagnostic; 9 | import javax.tools.Diagnostic.Kind; 10 | import javax.tools.JavaCompiler; 11 | import javax.tools.JavaCompiler.CompilationTask; 12 | import javax.tools.DiagnosticCollector; 13 | import javax.tools.JavaFileObject; 14 | import javax.tools.StandardJavaFileManager; 15 | import javax.tools.ToolProvider; 16 | import java.io.File; 17 | import java.io.IOException; 18 | import java.io.StringWriter; 19 | import java.io.Writer; 20 | import java.util.*; 21 | import java.util.concurrent.ExecutorService; 22 | import java.util.concurrent.Executors; 23 | import java.util.concurrent.Future; 24 | 25 | import com.google.common.base.Joiner; 26 | import org.apache.commons.io.FileUtils; 27 | import org.apache.maven.artifact.Artifact; 28 | import org.apache.maven.artifact.DependencyResolutionRequiredException; 29 | import org.apache.maven.plugin.AbstractMojo; 30 | import org.apache.maven.plugin.MojoExecutionException; 31 | import org.apache.maven.project.MavenProject; 32 | import org.codehaus.plexus.util.Scanner; 33 | import org.codehaus.plexus.util.StringUtils; 34 | import org.sonatype.plexus.build.incremental.BuildContext; 35 | 36 | /** 37 | * Base class for AnnotationProcessorMojo implementations 38 | * 39 | * @author tiwe 40 | * 41 | */ 42 | public abstract class AbstractProcessorMojo extends AbstractMojo { 43 | 44 | private static final String JAVA_FILE_FILTER = "/*.java"; 45 | private static final String[] ALL_JAVA_FILES_FILTER = new String[] { "**" + JAVA_FILE_FILTER }; 46 | 47 | /** 48 | * @component 49 | */ 50 | private BuildContext buildContext; 51 | 52 | /** 53 | * @parameter expression="${project}" readonly=true required=true 54 | */ 55 | private MavenProject project; 56 | 57 | /** 58 | * @parameter 59 | */ 60 | private String[] processors; 61 | 62 | /** 63 | * @parameter 64 | */ 65 | private String processor; 66 | 67 | /** 68 | * @parameter expression="${project.build.sourceEncoding}" required=true 69 | */ 70 | private String sourceEncoding; 71 | 72 | /** 73 | * @parameter 74 | */ 75 | private Map options; 76 | 77 | /** 78 | * @parameter 79 | */ 80 | private Map 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 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 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 | --------------------------------------------------------------------------------