forked from hibernate/hibernate-tools
/
Cfg2JavaTool.java
445 lines (374 loc) · 12.7 KB
/
Cfg2JavaTool.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/*
* Created on 02-Dec-2004
*
*/
package org.hibernate.tool.hbm2x;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.cfg.reveng.ReverseEngineeringStrategyUtil;
import org.hibernate.mapping.Array;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.IndexedCollection;
import org.hibernate.mapping.MetaAttributable;
import org.hibernate.mapping.MetaAttribute;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.Value;
import org.hibernate.tool.hbm2x.pojo.ComponentPOJOClass;
import org.hibernate.tool.hbm2x.pojo.EntityPOJOClass;
import org.hibernate.tool.hbm2x.pojo.ImportContext;
import org.hibernate.tool.hbm2x.pojo.NoopImportContext;
import org.hibernate.tool.hbm2x.pojo.POJOClass;
import org.hibernate.tool.hbm2x.visitor.JavaTypeFromValueVisitor;
import org.hibernate.type.PrimitiveType;
import org.hibernate.type.Type;
import org.hibernate.type.TypeResolver;
import org.hibernate.util.StringHelper;
/**
* Helper methods for javacode generation.
* <p/>
*
*
* @author max
*/
public class Cfg2JavaTool {
private static final Log log = LogFactory.getLog( Cfg2JavaTool.class );
public Cfg2JavaTool() {
}
public POJOClass getPOJOClass(Component comp) {
return new ComponentPOJOClass(comp, this);
}
public POJOClass getPOJOClass(PersistentClass comp) {
return new EntityPOJOClass(comp, this);
}
public String unqualify(String name) {
return StringHelper.unqualify( name );
}
/**
* Returns all meta items as one large string.
*
*/
public String getMetaAsString(MetaAttributable pc, String attribute) {
MetaAttribute c = pc.getMetaAttribute( attribute );
return MetaAttributeHelper.getMetaAsString( c );
}
public boolean hasMetaAttribute(MetaAttributable pc, String attribute) {
return pc.getMetaAttribute( attribute ) != null;
}
public String getMetaAsString(MetaAttributable pc, String attribute, String seperator) {
return MetaAttributeHelper.getMetaAsString( pc.getMetaAttribute( attribute ), seperator );
}
public boolean getMetaAsBool(MetaAttributable ma, String attribute) {
return getMetaAsBool( ma, attribute, false );
}
public boolean getMetaAsBool(MetaAttributable pc, String attribute, boolean defaultValue) {
return MetaAttributeHelper.getMetaAsBool( pc.getMetaAttribute( attribute ), defaultValue );
}
/**
* Convert string into something that can be rendered nicely into a javadoc
* comment.
* Prefix each line with a star ('*').
*
* @param string
*/
public String toJavaDoc(String string, int indent) {
StringBuffer result = new StringBuffer();
if ( string != null ) {
String[] lines = StringUtils.split( string, "\n\r\f" );
for ( int i = 0; i < lines.length ; i++ ) {
String docline = " * " + lines[i];
if ( i < lines.length - 1 ) docline += "\n";
result.append( StringUtils.leftPad( docline, docline.length() + indent ) );
}
}
return result.toString();
}
public String getClassModifiers(MetaAttributable pc) {
String classModifiers = null;
// Get scope (backwards compatibility)
if ( pc.getMetaAttribute( "scope-class" ) != null ) {
classModifiers = getMetaAsString( pc, "scope-class" ).trim();
}
// Get modifiers
if ( pc.getMetaAttribute( "class-modifier" ) != null ) {
classModifiers = getMetaAsString( pc, "class-modifier" ).trim();
}
return classModifiers == null ? "public" : classModifiers;
}
private String toName(Class c) {
if ( c.isArray() ) {
Class a = c.getComponentType();
return a.getName() + "[]";
}
else {
return c.getName();
}
}
/**
* Method that tries to get the typename for a property WITHOUT reflection.
*/
/*public String getJavaTypeName(Property p) {
String javaTypeName = getJavaTypeName( p, false );
return javaTypeName;
}*/
/**
* Returns the typename for a property, using generics if this is a Set type and useGenerics is set to true.
*/
public String getJavaTypeName(Property p, boolean useGenerics) {
return getJavaTypeName(p, useGenerics, new NoopImportContext());
}
public String getJavaTypeName(Property p, boolean useGenerics, ImportContext importContext) {
String overrideType = getMetaAsString( p, "property-type" );
if ( !StringHelper.isEmpty( overrideType ) ) {
String importType = importContext.importType(overrideType);
if ( useGenerics && importType.indexOf( "<" )<0) {
if ( p.getValue() instanceof Collection ) {
String decl = getGenericCollectionDeclaration( (Collection) p.getValue(), true, importContext );
return importType + decl;
}
}
return importType;
}
else {
String rawType = getRawTypeName( p, useGenerics, true, importContext );
if(rawType==null) {
throw new IllegalStateException("getJavaTypeName *must* return a value");
}
return importContext.importType(rawType);
}
}
private static final Map PRIMITIVES = new HashMap();
static {
PRIMITIVES.put( "char", "Character" );
PRIMITIVES.put( "byte", "Byte" );
PRIMITIVES.put( "short", "Short" );
PRIMITIVES.put( "int", "Integer" );
PRIMITIVES.put( "long", "Long" );
PRIMITIVES.put( "boolean", "Boolean" );
PRIMITIVES.put( "float", "Float" );
PRIMITIVES.put( "double", "Double" );
}
private static Set NONPRIMITIVETYPES = null;
static public boolean isNonPrimitiveTypeName(String typeName) {
if ( NONPRIMITIVETYPES == null ) {
NONPRIMITIVETYPES = new HashSet();
Field[] fields = Hibernate.class.getFields();
for ( int i = 0; i < fields.length ; i++ ) {
Field field = fields[i];
if ( Modifier.isStatic( field.getModifiers() ) ) {
if ( Type.class.isAssignableFrom( field.getType() ) ) {
try {
Type type = (Type) field.get( Hibernate.class );
if ( !PRIMITIVES.containsKey( type.getName() ) ) {
NONPRIMITIVETYPES.add( type.getName() );
}
}
catch (IllegalArgumentException e) {
throw new ExporterException( "Could not create list of basic hibernate types", e );
}
catch (IllegalAccessException e) {
throw new ExporterException( "Could not create list of basic hibernate types", e );
}
}
}
}
}
return NONPRIMITIVETYPES.contains( typeName );
}
private String getRawTypeName(Property p, boolean useGenerics, boolean preferRawTypeNames, ImportContext importContext) {
Value value = p.getValue();
try {
if ( value instanceof Array ) { // array has a string rep.inside.
Array a = (Array) value;
if ( a.isPrimitiveArray() ) {
return toName( value.getType().getReturnedClass() );
}
else if (a.getElementClassName()!=null){
return a.getElementClassName() + "[]";
} else {
return getJavaTypeName(a.getElement(), preferRawTypeNames) + "[]";
}
}
if ( value instanceof Component ) { // same for component.
Component component = ( (Component) value );
if(component.isDynamic()) return "java.util.Map";
return component.getComponentClassName();
}
if ( useGenerics ) {
if ( value instanceof Collection ) {
String decl = getGenericCollectionDeclaration( (Collection) value, preferRawTypeNames, importContext );
return getJavaTypeName(value, preferRawTypeNames) + decl;
}
}
return getJavaTypeName( value, preferRawTypeNames );
}
catch (Exception e) {
//e.printStackTrace();
String msg = "Could not resolve type without exception for " + p + " Value: " + value;
if ( value != null && value.isSimpleValue() ) {
String typename = ( (SimpleValue) value ).getTypeName();
log.warn( msg + ". Falling back to typename: " + typename );
return typename;
}
else {
throw new ExporterException( msg, e );
}
}
}
public String getGenericCollectionDeclaration(Collection collection, boolean preferRawTypeNames, ImportContext importContext) {
Value element = collection.getElement();
String elementType = importContext.importType(getJavaTypeName(element, preferRawTypeNames));
String genericDecl = elementType;
if(collection.isIndexed()) {
IndexedCollection idxCol = (IndexedCollection) collection;
if(!idxCol.isList()) {
Value idxElement = idxCol.getIndex();
String indexType = importContext.importType(getJavaTypeName(idxElement, preferRawTypeNames));
genericDecl = indexType + "," + elementType;
}
}
String decl = "<" + genericDecl + ">";
return decl;
}
/**
* @param simpleValue
* @return
*/
public Properties getFilteredIdentifierGeneratorProperties(SimpleValue simpleValue) {
Properties p = simpleValue.getIdentifierGeneratorProperties();
return Cfg2HbmTool.getFilteredIdentifierGeneratorProperties(p);
}
private String getJavaTypeName(Value value, boolean preferRawTypeNames) {
return (String) value.accept( new JavaTypeFromValueVisitor() );
}
public String asParameterList(Iterator fields, boolean useGenerics, ImportContext ic) {
StringBuffer buf = new StringBuffer();
while ( fields.hasNext() ) {
Property field = (Property) fields.next();
buf.append( getJavaTypeName( field, useGenerics, ic ) )
.append( " " )
.append( field.getName() );
if ( fields.hasNext() ) {
buf.append( ", " );
}
}
return buf.toString();
}
/**
* @param fields iterator on Property elements.
* @return "name, number, ..." for a property list, usable for method calls.
* <p/>
* TODO: handle this in a template ?
*/
public String asArgumentList(Iterator fields) {
StringBuffer buf = new StringBuffer();
while ( fields.hasNext() ) {
Property field = (Property) fields.next();
buf.append( field.getName() );
if ( fields.hasNext() ) {
buf.append( ", " );
}
}
return buf.toString();
}
/**
* @param clazz persistent class.
* @return "String name, int number, ..." for a property list, usable for method declarations.
* <p/>
* TODO: handle this in a template ?
*/
public String asNaturalIdParameterList(PersistentClass clazz) {
Iterator fields = clazz.getRootClass().getPropertyIterator();
StringBuffer buf = new StringBuffer();
while ( fields.hasNext() ) {
Property field = (Property) fields.next();
if ( field.isNaturalIdentifier() ) {
buf.append( getJavaTypeName( field, false ) )
.append( " " )
.append( field.getName() )
.append( ", " );
}
}
return buf.substring( 0, buf.length() - 2 );
}
public String asParameterList(List fields, boolean useGenerics, ImportContext ic) {
return asParameterList( fields.iterator(), useGenerics, ic );
}
public String asArgumentList(List fields) {
return asArgumentList( fields.iterator() );
}
public String asFinderArgumentList(Map parameterTypes, ImportContext ctx) {
StringBuffer buf = new StringBuffer();
Iterator iter = parameterTypes.entrySet().iterator();
while ( iter.hasNext() ) {
Map.Entry entry = (Map.Entry) iter.next();
String typename = null;
Type type = null;
if(entry.getValue() instanceof String) {
try {
type = new TypeResolver().heuristicType((String) entry.getValue());
} catch(Throwable t) {
type = null;
typename = (String) entry.getValue();
}
}
if(type!=null) {
Class typeClass;
if ( type instanceof PrimitiveType ) {
typeClass = ( (PrimitiveType) type ).getPrimitiveClass();
}
else {
typeClass = type.getReturnedClass();
}
typename = typeClass.getName();
}
buf.append( ctx.importType( typename ))
.append( " " )
.append( entry.getKey() );
if ( iter.hasNext() ) buf.append( ", " );
}
return buf.toString();
}
public boolean isPrimitive(String typeName) {
return PRIMITIVES.containsKey(typeName);
}
public boolean isComponent(Property property) {
return isComponent(property.getValue());
}
public boolean isComponent(Value value) {
return ( value instanceof Component );
}
// TODO: should consult exporter/cfg2java tool for cached POJOEntities....or maybe not since they
// have their own state...
public Iterator getPOJOIterator(final Iterator persistentClasses) {
return new Iterator() {
public Object next() {
return getPOJOClass((PersistentClass)persistentClasses.next());
}
public boolean hasNext() {
return persistentClasses.hasNext();
}
public void remove() {
persistentClasses.remove();
}
};
}
public String simplePluralize(String str) {
return ReverseEngineeringStrategyUtil.simplePluralize(str);
}
public boolean isArray(String typeName) {
return typeName!=null && typeName.endsWith("[]");
}
}