-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
MavenEnhancePlugin.java
321 lines (281 loc) · 9.92 KB
/
MavenEnhancePlugin.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.orm.tooling.maven;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Execute;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.hibernate.bytecode.enhance.spi.DefaultEnhancementContext;
import org.hibernate.bytecode.enhance.spi.EnhancementContext;
import org.hibernate.bytecode.enhance.spi.Enhancer;
import org.sonatype.plexus.build.incremental.BuildContext;
/**
* This plugin will enhance Entity objects.
*
* @author Jeremy Whiting
* @author Luis Barreiro
*/
@Mojo(name = "enhance", defaultPhase = LifecyclePhase.COMPILE, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME)
@Execute(goal = "enhance", phase = LifecyclePhase.COMPILE)
public class MavenEnhancePlugin extends AbstractMojo {
/**
* The contexts to use during enhancement.
*/
private List<File> sourceSet = new ArrayList<File>();
@Component
private BuildContext buildContext;
@Parameter(property = "dir", defaultValue = "${project.build.outputDirectory}")
private String dir;
@Parameter(property = "failOnError", defaultValue = "true")
private boolean failOnError = true;
@Parameter(property = "enableLazyInitialization", defaultValue = "false")
private boolean enableLazyInitialization;
@Parameter(property = "enableDirtyTracking", defaultValue = "false")
private boolean enableDirtyTracking;
@Parameter(property = "enableAssociationManagement", defaultValue = "false")
private boolean enableAssociationManagement;
@Parameter(property = "enableExtendedEnhancement", defaultValue = "false")
private boolean enableExtendedEnhancement;
private boolean shouldApply() {
return enableLazyInitialization || enableDirtyTracking || enableAssociationManagement || enableExtendedEnhancement;
}
public void execute() throws MojoExecutionException, MojoFailureException {
if ( !shouldApply() ) {
getLog().warn( "Skipping Hibernate bytecode enhancement plugin execution since no feature is enabled" );
return;
}
// Perform a depth first search for sourceSet
File root = new File( this.dir );
if ( !root.exists() ) {
getLog().info( "Skipping Hibernate enhancement plugin execution since there is no classes dir " + dir );
return;
}
walkDir( root );
if ( sourceSet.isEmpty() ) {
getLog().info( "Skipping Hibernate enhancement plugin execution since there are no classes to enhance on " + dir );
return;
}
getLog().info( "Starting Hibernate enhancement for classes on " + dir );
final ClassLoader classLoader = toClassLoader( Collections.singletonList( root ) );
EnhancementContext enhancementContext = new DefaultEnhancementContext() {
@Override
public ClassLoader getLoadingClassLoader() {
return classLoader;
}
@Override
public boolean doBiDirectionalAssociationManagement(CtField field) {
return enableAssociationManagement;
}
@Override
public boolean doDirtyCheckingInline(CtClass classDescriptor) {
return enableDirtyTracking;
}
@Override
public boolean hasLazyLoadableAttributes(CtClass classDescriptor) {
return enableLazyInitialization;
}
@Override
public boolean isLazyLoadable(CtField field) {
return enableLazyInitialization;
}
@Override
public boolean doExtendedEnhancement(CtClass classDescriptor) {
return enableExtendedEnhancement;
}
};
if ( enableExtendedEnhancement ) {
getLog().warn( "Extended enhancement is enabled. Classes other than entities may be modified. You should consider access the entities using getter/setter methods and disable this property. Use at your own risk." );
}
final Enhancer enhancer = new Enhancer( enhancementContext );
final ClassPool classPool = new ClassPool( false );
for ( File file : sourceSet ) {
final CtClass ctClass = toCtClass( file, classPool );
if ( ctClass == null ) {
continue;
}
byte[] enhancedBytecode = doEnhancement( file, ctClass, enhancer );
writeOutEnhancedClass( enhancedBytecode, ctClass, file );
getLog().info( "Successfully enhanced class [" + ctClass.getName() + "]" );
}
}
private ClassLoader toClassLoader(List<File> runtimeClasspath) throws MojoExecutionException {
List<URL> urls = new ArrayList<URL>();
for ( File file : runtimeClasspath ) {
try {
urls.add( file.toURI().toURL() );
getLog().debug( "Adding classpath entry for classes root " + file.getAbsolutePath() );
}
catch (MalformedURLException e) {
String msg = "Unable to resolve classpath entry to URL: " + file.getAbsolutePath();
if ( failOnError ) {
throw new MojoExecutionException( msg, e );
}
getLog().warn( msg );
}
}
// HHH-10145 Add dependencies to classpath as well - all but the ones used for testing purposes
MavenProject project = ( (MavenProject) getPluginContext().get( "project" ) );
Set<Artifact> artifacts = project.getArtifacts();
if ( artifacts != null) {
for ( Artifact a : artifacts ) {
if ( !Artifact.SCOPE_TEST.equals( a.getScope() ) ) {
try {
urls.add( a.getFile().toURI().toURL() );
getLog().debug( "Adding classpath entry for dependency " + a.getId() );
}
catch (MalformedURLException e) {
String msg = "Unable to resolve URL for dependency " + a.getId() + " at " + a.getFile().getAbsolutePath();
if ( failOnError ) {
throw new MojoExecutionException( msg, e );
}
getLog().warn( msg );
}
}
}
}
return new URLClassLoader( urls.toArray( new URL[urls.size()] ), Enhancer.class.getClassLoader() );
}
private CtClass toCtClass(File file, ClassPool classPool) throws MojoExecutionException {
try {
final InputStream is = new FileInputStream( file.getAbsolutePath() );
try {
return classPool.makeClass( is );
}
catch (IOException e) {
String msg = "Javassist unable to load class in preparation for enhancing: " + file.getAbsolutePath();
if ( failOnError ) {
throw new MojoExecutionException( msg, e );
}
getLog().warn( msg );
return null;
}
finally {
try {
is.close();
}
catch (IOException e) {
getLog().info( "Was unable to close InputStream : " + file.getAbsolutePath(), e );
}
}
}
catch (FileNotFoundException e) {
// should never happen, but...
String msg = "Unable to locate class file for InputStream: " + file.getAbsolutePath();
if ( failOnError ) {
throw new MojoExecutionException( msg, e );
}
getLog().warn( msg );
return null;
}
}
private byte[] doEnhancement(File javaClassFile, CtClass ctClass, Enhancer enhancer) throws MojoExecutionException {
try {
return enhancer.enhance( ctClass.getName(), ctClass.toBytecode() );
}
catch (Exception e) {
String msg = "Unable to enhance class: " + ctClass.getName();
if ( failOnError ) {
throw new MojoExecutionException( msg, e );
}
buildContext.addMessage( javaClassFile, 0, 0, msg, BuildContext.SEVERITY_WARNING, e );
return null;
}
}
/**
* Expects a directory.
*/
private void walkDir(File dir) {
walkDir(
dir,
new FileFilter() {
@Override
public boolean accept(File pathname) {
return ( pathname.isFile() && pathname.getName().endsWith( ".class" ) );
}
},
new FileFilter() {
@Override
public boolean accept(File pathname) {
return ( pathname.isDirectory() );
}
}
);
}
private void walkDir(File dir, FileFilter classesFilter, FileFilter dirFilter) {
File[] dirs = dir.listFiles( dirFilter );
for ( File dir1 : dirs ) {
walkDir( dir1, classesFilter, dirFilter );
}
File[] files = dir.listFiles( classesFilter );
Collections.addAll( this.sourceSet, files );
}
private void writeOutEnhancedClass(byte[] enhancedBytecode, CtClass ctClass, File file) throws MojoExecutionException{
if ( enhancedBytecode == null ) {
return;
}
try {
if ( file.delete() ) {
if ( !file.createNewFile() ) {
buildContext.addMessage( file, 0, 0, "Unable to recreate class file", BuildContext.SEVERITY_ERROR, null );
}
}
else {
buildContext.addMessage( file, 0, 0, "Unable to delete class file", BuildContext.SEVERITY_ERROR, null );
}
}
catch (IOException e) {
buildContext.addMessage( file, 0, 0, "Problem preparing class file for writing out enhancements", BuildContext.SEVERITY_WARNING, e );
}
OutputStream outputStream = null;
try {
outputStream = buildContext.newFileOutputStream( file );
outputStream.write( enhancedBytecode );
outputStream.flush();
}
catch (IOException e) {
String msg = String.format( "Error writing to enhanced class [%s] to file [%s]", file.getName(), file.getAbsolutePath() );
if ( failOnError ) {
throw new MojoExecutionException( msg, e );
}
buildContext.addMessage( file, 0, 0, msg, BuildContext.SEVERITY_WARNING, e );
}
finally {
try {
if( outputStream != null ) {
outputStream.close();
ctClass.detach();
}
}
catch (IOException ignore) {
}
}
}
}