-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
MavenEnhancePlugin.java
380 lines (334 loc) · 12.4 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/*
* 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.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.util.*;
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.plugin.logging.Log;
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.hibernate.bytecode.enhance.spi.UnloadedClass;
import org.hibernate.bytecode.enhance.spi.UnloadedField;
import org.hibernate.bytecode.spi.BytecodeProvider;
import org.sonatype.plexus.build.incremental.BuildContext;
import static org.hibernate.bytecode.internal.BytecodeProviderInitiator.buildDefaultBytecodeProvider;
/**
* This plugin will enhance Entity objects.
*
* @author Jeremy Whiting
* @author Luis Barreiro
*/
@Mojo(name = "enhance", defaultPhase = LifecyclePhase.COMPILE, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME)
public class MavenEnhancePlugin extends AbstractMojo {
/**
* The contexts to use during enhancement.
*/
private List<File> sourceSet = new ArrayList<File>();
@Component
private BuildContext buildContext;
@Parameter(property = "base", defaultValue = "${project.build.outputDirectory}")
private String base;
@Parameter(property = "dir", defaultValue = "${project.build.outputDirectory}")
private String dir;
@Parameter(property = "classNames", defaultValue = "")
private String classNames;
@Parameter(property = "failOnError", defaultValue = "true")
private boolean failOnError = true;
@Parameter(property = "enableLazyInitialization", defaultValue = "true")
private boolean enableLazyInitialization;
@Parameter(property = "enableDirtyTracking", defaultValue = "true")
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;
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
final Log log = getLog();
if ( !shouldApply() ) {
log.warn( "Skipping Hibernate bytecode enhancement plugin execution since no feature is enabled" );
return;
}
if ( !dir.startsWith( base ) ) {
throw new MojoExecutionException( "The enhancement directory 'dir' (" + dir + ") is no subdirectory of 'base' (" + base + ")" );
}
// Perform a depth first search for sourceSet
File root = new File( this.dir );
if ( !root.exists() ) {
log.info( "Skipping Hibernate enhancement plugin execution since there is no classes dir " + dir );
return;
}
walkDir( root );
if ( sourceSet.isEmpty() ) {
log.info( "Skipping Hibernate enhancement plugin execution since there are no classes to enhance on " + dir );
return;
}
List<String> classesToEnhance = new ArrayList<>();
if(classNames != null && classNames.length() >= 1) {
classesToEnhance = Arrays.asList(classNames.split(","));
}
log.info( "Starting Hibernate enhancement for classes on " + dir );
final ClassLoader classLoader = toClassLoader( Collections.singletonList( new File( base ) ) );
EnhancementContext enhancementContext = new DefaultEnhancementContext() {
@Override
public ClassLoader getLoadingClassLoader() {
return classLoader;
}
@Override
public boolean doBiDirectionalAssociationManagement(UnloadedField field) {
return enableAssociationManagement;
}
@Override
public boolean doDirtyCheckingInline(UnloadedClass classDescriptor) {
return enableDirtyTracking;
}
@Override
public boolean hasLazyLoadableAttributes(UnloadedClass classDescriptor) {
return enableLazyInitialization;
}
@Override
public boolean isLazyLoadable(UnloadedField field) {
return enableLazyInitialization;
}
@Override
public boolean doExtendedEnhancement(UnloadedClass classDescriptor) {
return enableExtendedEnhancement;
}
};
if ( !enableLazyInitialization ) {
log.warn( "The 'enableLazyInitialization' configuration is deprecated and will be removed. Set the value to 'true' to get rid of this warning" );
}
if ( !enableDirtyTracking ) {
log.warn( "The 'enableDirtyTracking' configuration is deprecated and will be removed. Set the value to 'true' to get rid of this warning" );
}
if ( enableExtendedEnhancement ) {
log.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." );
}
//TODO allow the Maven plugin to configure the bytecode enhancer?
final BytecodeProvider bytecodeProvider = buildDefaultBytecodeProvider();
try {
final Enhancer enhancer = bytecodeProvider.getEnhancer( enhancementContext );
for ( File file : sourceSet ) {
discoverTypes( file, enhancer );
if ( log.isDebugEnabled() ) {
log.debug( "Successfully discovered types for class [" + file + "]" );
}
}
for ( File file : sourceSet ) {
String className = determineClassName(root, file);
if(! (classesToEnhance.size()==0 || classesToEnhance.contains(className))) {
continue;
}
final byte[] enhancedBytecode = doEnhancement( file, enhancer );
if ( enhancedBytecode == null ) {
continue;
}
writeOutEnhancedClass( enhancedBytecode, file );
if ( log.isDebugEnabled() ) {
log.debug( "Successfully enhanced class [" + file + "]" );
}
}
}
finally {
bytecodeProvider.resetCaches();
}
}
private ClassLoader toClassLoader(List<File> runtimeClasspath) throws MojoExecutionException {
List<URL> urls = new ArrayList<URL>( runtimeClasspath.size() );
final Log log = getLog();
for ( File file : runtimeClasspath ) {
try {
urls.add( file.toURI().toURL() );
if ( log.isDebugEnabled() ) {
log.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 );
}
log.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() );
log.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 );
}
log.warn( msg );
}
}
}
}
return new URLClassLoader( urls.toArray( new URL[urls.size()] ), Enhancer.class.getClassLoader() );
}
private byte[] doEnhancement(File javaClassFile, Enhancer enhancer) throws MojoExecutionException {
try {
String className = javaClassFile.getAbsolutePath().substring(
base.length() + 1,
javaClassFile.getAbsolutePath().length() - ".class".length()
).replace( File.separatorChar, '.' );
ByteArrayOutputStream originalBytes = new ByteArrayOutputStream();
FileInputStream fileInputStream = new FileInputStream( javaClassFile );
try {
byte[] buffer = new byte[1024];
int length;
while ( ( length = fileInputStream.read( buffer ) ) != -1 ) {
originalBytes.write( buffer, 0, length );
}
}
finally {
fileInputStream.close();
}
return enhancer.enhance( className, originalBytes.toByteArray() );
}
catch (Exception e) {
String msg = "Unable to enhance class: " + javaClassFile.getName();
if ( failOnError ) {
throw new MojoExecutionException( msg, e );
}
buildContext.addMessage( javaClassFile, 0, 0, msg, BuildContext.SEVERITY_WARNING, e );
return null;
}
}
private void discoverTypes(File javaClassFile, Enhancer enhancer) throws MojoExecutionException {
try {
String className = javaClassFile.getAbsolutePath().substring(
base.length() + 1,
javaClassFile.getAbsolutePath().length() - ".class".length()
).replace( File.separatorChar, '.' );
ByteArrayOutputStream originalBytes = new ByteArrayOutputStream();
FileInputStream fileInputStream = new FileInputStream( javaClassFile );
try {
byte[] buffer = new byte[1024];
int length;
while ( ( length = fileInputStream.read( buffer ) ) != -1 ) {
originalBytes.write( buffer, 0, length );
}
}
finally {
fileInputStream.close();
}
enhancer.discoverTypes( className, originalBytes.toByteArray() );
}
catch (Exception e) {
String msg = "Unable to discover types for class: " + javaClassFile.getName();
if ( failOnError ) {
throw new MojoExecutionException( msg, e );
}
buildContext.addMessage( javaClassFile, 0, 0, msg, BuildContext.SEVERITY_WARNING, e );
}
}
/**
* 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, File file) throws MojoExecutionException {
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();
}
}
catch (IOException ignore) {
}
}
}
private String determineClassName(File root, File javaClassFile) {
final Path relativeClassPath = root.toPath().relativize( javaClassFile.toPath() );
final String relativeClassPathString = relativeClassPath.toString();
final String classNameBase = relativeClassPathString.substring(
0,
relativeClassPathString.length() - ".class".length()
);
return classNameBase.replace( File.separatorChar, '.' );
}
}