Source Code Cross Referenced for DynamicBean.java in  » Database-ORM » Persist » net » sf » persist » tests » framework » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Database ORM » Persist » net.sf.persist.tests.framework 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        // $Id: DynamicBean.java 11 2007-08-19 20:05:36Z jcamaia $
002:
003:        package net.sf.persist.tests.framework;
004:
005:        import java.io.ByteArrayInputStream;
006:        import java.io.IOException;
007:        import java.io.InputStream;
008:        import java.io.Reader;
009:        import java.io.StringReader;
010:        import java.lang.reflect.Field;
011:        import java.math.BigDecimal;
012:        import java.sql.Blob;
013:        import java.sql.Clob;
014:        import java.sql.SQLException;
015:        import java.util.Arrays;
016:        import java.util.HashMap;
017:        import java.util.Map;
018:
019:        import javassist.ClassPool;
020:        import javassist.CtClass;
021:        import javassist.CtField;
022:        import javassist.CtMethod;
023:        import javassist.CtNewMethod;
024:        import javassist.NotFoundException;
025:        import javassist.bytecode.AnnotationsAttribute;
026:        import javassist.bytecode.ClassFile;
027:        import javassist.bytecode.ConstPool;
028:        import javassist.bytecode.annotation.Annotation;
029:
030:        /**
031:         * Set of helpers to build and manipulate beans at runtime.
032:         */
033:        public class DynamicBean {
034:
035:            public static Class createBeanClass(BeanMap beanMap, boolean noTable) {
036:
037:                ClassPool pool = ClassPool.getDefault();
038:                CtClass cc = pool.makeClass("net.sf.persist.tests.generated."
039:                        + beanMap.getClassName() + (noTable ? "NoTable" : ""));
040:
041:                if (noTable) {
042:                    ClassFile cf = cc.getClassFile();
043:                    ConstPool cp = cf.getConstPool();
044:                    AnnotationsAttribute attr = new AnnotationsAttribute(cp,
045:                            AnnotationsAttribute.visibleTag);
046:                    Annotation a;
047:                    try {
048:                        a = new Annotation(cp, pool
049:                                .get("net.sf.persist.annotations.NoTable"));
050:                    } catch (NotFoundException e) {
051:                        throw new RuntimeException(e);
052:                    }
053:                    attr.setAnnotation(a);
054:                    cf.addAttribute(attr);
055:                    cf.setVersionToJava5();
056:                }
057:
058:                try {
059:
060:                    for (FieldMap fieldMap : beanMap.getFields()) {
061:
062:                        String fieldName = fieldMap.getFieldName();
063:                        Class fieldType = fieldMap.getTypes().get(0);
064:
065:                        String fieldNameU = Character.toUpperCase(fieldName
066:                                .charAt(0))
067:                                + fieldName.substring(1);
068:                        String fieldTypeName = fieldType.getCanonicalName();
069:
070:                        String getterCode = "public " + fieldTypeName + " get"
071:                                + fieldNameU + "() { return " + fieldName
072:                                + "; }";
073:                        String setterCode = "public void set" + fieldNameU
074:                                + "(" + fieldTypeName + " " + fieldName
075:                                + ") { this." + fieldName + "=" + fieldName
076:                                + "; }";
077:
078:                        CtField cf = new CtField(pool.get(fieldTypeName),
079:                                fieldName, cc);
080:                        cc.addField(cf);
081:
082:                        CtMethod cm = CtNewMethod.make(getterCode, cc);
083:                        cc.addMethod(cm);
084:
085:                        cm = CtNewMethod.make(setterCode, cc);
086:                        cc.addMethod(cm);
087:                    }
088:
089:                    String toStringCode = "public String toString() { return net.sf.persist.tests.framework.DynamicBean.toString(this); }";
090:                    CtMethod cm = CtNewMethod.make(toStringCode, cc);
091:                    cc.addMethod(cm);
092:
093:                    String equalsCode = "public boolean equals(Object obj) { return net.sf.persist.tests.framework.DynamicBean.compareBeans(this,obj); }";
094:                    cm = CtNewMethod.make(equalsCode, cc);
095:                    cc.addMethod(cm);
096:
097:                    return cc.toClass();
098:
099:                } catch (Exception e) {
100:                    throw new RuntimeException(e);
101:                }
102:            }
103:
104:            public static Object createInstance(Class cls, BeanMap beanMap,
105:                    boolean useNulls) {
106:                Object obj = null;
107:                try {
108:                    obj = cls.newInstance();
109:                } catch (Exception e) {
110:                    throw new RuntimeException(e);
111:                }
112:                for (Field field : cls.getDeclaredFields()) {
113:                    FieldMap fieldMap = beanMap.getField(field.getName());
114:                    setRandomValue(obj, field, fieldMap, useNulls);
115:                }
116:                return obj;
117:            }
118:
119:            private static void setRandomValue(Object obj, Field field,
120:                    FieldMap fieldMap, boolean useNull) {
121:
122:                Class fieldType = field.getType();
123:                int size = fieldMap.getSize();
124:                double min = fieldMap.getMin();
125:                double max = fieldMap.getMax();
126:
127:                Object value = null;
128:
129:                if (fieldType == Boolean.class)
130:                    value = useNull ? null : new Boolean(randomBoolean());
131:                else if (fieldType == boolean.class)
132:                    value = useNull ? false : randomBoolean();
133:                else if (fieldType == Byte.class)
134:                    value = useNull ? null : new Byte(randomByte((byte) min,
135:                            (byte) max));
136:                else if (fieldType == byte.class)
137:                    value = useNull ? (byte) 0 : randomByte((byte) min,
138:                            (byte) max);
139:                else if (fieldType == Byte[].class)
140:                    value = useNull ? null : randomByteObjArray(size);
141:                else if (fieldType == byte[].class)
142:                    value = useNull ? null : randomByteArray(size);
143:                else if (fieldType == Short.class)
144:                    value = useNull ? null : new Short(randomShort((short) min,
145:                            (short) max));
146:                else if (fieldType == short.class)
147:                    value = useNull ? (short) 0 : randomShort((short) min,
148:                            (short) max);
149:                else if (fieldType == Integer.class)
150:                    value = useNull ? null : new Integer(randomInt((int) min,
151:                            (int) max));
152:                else if (fieldType == int.class)
153:                    value = useNull ? (int) 0 : randomInt((int) min, (int) max);
154:                else if (fieldType == Long.class)
155:                    value = useNull ? null : new Long(randomLong((long) min,
156:                            (long) max));
157:                else if (fieldType == long.class)
158:                    value = useNull ? (long) 0 : randomLong((long) min,
159:                            (long) max);
160:                else if (fieldType == Float.class)
161:                    value = useNull ? null : new Float(randomFloat((float) min,
162:                            (float) max));
163:                else if (fieldType == float.class)
164:                    value = useNull ? (float) 0 : randomFloat((float) min,
165:                            (float) max);
166:                else if (fieldType == Double.class)
167:                    value = useNull ? null : new Double(randomDouble(min, max));
168:                else if (fieldType == double.class)
169:                    value = useNull ? (double) 0 : randomDouble(min, max);
170:                else if (fieldType == Character.class)
171:                    value = useNull ? null : new Character(randomChar());
172:                else if (fieldType == char.class)
173:                    value = useNull ? ' ' : randomChar();
174:                else if (fieldType == Character[].class)
175:                    value = useNull ? null : randomCharObjArray(size);
176:                else if (fieldType == char[].class)
177:                    value = useNull ? null : randomCharArray(size);
178:                else if (fieldType == String.class)
179:                    value = useNull ? null : randomString(size);
180:                else if (fieldType == BigDecimal.class)
181:                    value = useNull ? null : new BigDecimal(randomLong(
182:                            (long) min, (long) max));
183:                else if (fieldType == java.io.Reader.class)
184:                    value = useNull ? null : new StringReader(
185:                            randomString(size));
186:                else if (fieldType == java.io.InputStream.class)
187:                    value = useNull ? null : new ByteArrayInputStream(
188:                            randomByteArray(size));
189:                else if (fieldType == java.util.Date.class)
190:                    value = useNull ? null : new java.util.Date(
191:                            randomTimestamp());
192:                else if (fieldType == java.sql.Date.class)
193:                    value = useNull ? null : new java.sql.Date(
194:                            randomTimestamp());
195:                else if (fieldType == java.sql.Time.class)
196:                    value = useNull ? null : new java.sql.Time(
197:                            randomTimestamp());
198:                else if (fieldType == java.sql.Timestamp.class)
199:                    value = useNull ? null : new java.sql.Timestamp(
200:                            randomTimestamp());
201:                else if (fieldType == java.sql.Blob.class)
202:                    value = useNull ? null : new BytesBlob(
203:                            randomByteArray(size));
204:                else if (fieldType == java.sql.Clob.class)
205:                    value = useNull ? null : new StringClob(randomString(size));
206:                else {
207:                    if (useNull)
208:                        value = null;
209:                    else {
210:                        Map m = new HashMap();
211:                        m.put(randomString(3), randomString(32));
212:                        m.put(randomString(3), randomString(32));
213:                        m.put(randomString(3), randomString(32));
214:                        value = m;
215:                    }
216:                }
217:
218:                try {
219:                    String fieldName = field.getName();
220:                    Field f = obj.getClass().getDeclaredField(fieldName);
221:                    f.setAccessible(true);
222:                    f.set(obj, value);
223:                } catch (Exception e) {
224:                    throw new RuntimeException(e);
225:                }
226:
227:            }
228:
229:            public static Object getFieldValue(Object obj, String fieldName) {
230:                try {
231:                    Field f = obj.getClass().getDeclaredField(fieldName);
232:                    f.setAccessible(true);
233:                    return f.get(obj);
234:                } catch (Exception e) {
235:                    throw new RuntimeException(e);
236:                }
237:            }
238:
239:            public static String toString(Object obj) {
240:                if (obj == null)
241:                    return "null";
242:                StringBuffer sb = new StringBuffer();
243:                sb.append("{ ");
244:                for (Field field : obj.getClass().getDeclaredFields()) {
245:                    String fieldName = field.getName();
246:
247:                    Object value = getFieldValue(obj, fieldName);
248:                    String s = value == null ? "null" : value.toString();
249:                    if (s.length() > 32)
250:                        s = s.substring(0, 32) + "...";
251:
252:                    sb.append(fieldName + "=" + s + ", ");
253:                }
254:                sb.deleteCharAt(sb.length() - 1);
255:                sb.deleteCharAt(sb.length() - 1);
256:                sb.append(" }");
257:                return sb.toString();
258:            }
259:
260:            /**
261:             * Returns true if the field is a primitive number type (byte, short, int, etc.) and its value is zero,
262:             * or if the field is an object and its value is null
263:             */
264:            public static boolean isNull(Class cls, Object obj) {
265:
266:                if (obj == null)
267:                    return true;
268:
269:                if (cls == boolean.class || cls == Boolean.class)
270:                    return ((Boolean) obj).booleanValue() == false;
271:                else if (cls == byte.class || cls == Byte.class
272:                        || cls == short.class || cls == Short.class
273:                        || cls == int.class || cls == Integer.class
274:                        || cls == long.class || cls == Long.class
275:                        || cls == float.class || cls == Float.class
276:                        || cls == double.class || cls == Double.class
277:                        || cls == BigDecimal.class) {
278:
279:                    // first cast to Number
280:                    Number n = (Number) obj;
281:                    return n.longValue() == 0;
282:                } else
283:                    return false;
284:            }
285:
286:            public static boolean compareBeans(Object o1, Object o2) {
287:
288:                if (o1 == null && o2 == null)
289:                    return true;
290:                if (o1 == o2)
291:                    return true;
292:                if (o1 == null && o2 != null)
293:                    return false;
294:                if (o1 != null && o2 == null)
295:                    return false;
296:                if (o1.getClass() != o2.getClass())
297:                    return false;
298:
299:                try {
300:
301:                    for (Field field : o1.getClass().getDeclaredFields()) {
302:                        field.setAccessible(true);
303:                        Object v1 = field.get(o1);
304:                        Object v2 = field.get(o2);
305:                        if (!compareValues(v1, v2))
306:                            return false;
307:                    }
308:
309:                } catch (Exception e) {
310:                    throw new RuntimeException(e);
311:                }
312:
313:                return true;
314:            }
315:
316:            public static boolean compareBeansFromDifferentClasses(Object o1,
317:                    Object o2) {
318:
319:                if (o1 == null && o2 == null)
320:                    return true;
321:                if (o1 == o2)
322:                    return true;
323:                if (o1 == null && o2 != null)
324:                    return false;
325:                if (o1 != null && o2 == null)
326:                    return false;
327:
328:                try {
329:
330:                    for (Field f1 : o1.getClass().getDeclaredFields()) {
331:                        f1.setAccessible(true);
332:                        Object v1 = f1.get(o1);
333:
334:                        Field f2;
335:                        try {
336:                            f2 = o2.getClass().getDeclaredField(f1.getName());
337:                        } catch (NoSuchFieldException e) {
338:                            return false;
339:                        }
340:                        f2.setAccessible(true);
341:                        Object v2 = f2.get(o2);
342:
343:                        if (!compareValues(v1, v2))
344:                            return false;
345:                    }
346:
347:                } catch (Exception e) {
348:                    throw new RuntimeException(e);
349:                }
350:
351:                return true;
352:            }
353:
354:            /**
355:             * Compare values trying to convert types if they are found to be compatible
356:             */
357:            public static boolean compareValues(Object v1, Object v2) {
358:
359:                if (v1 == null && v2 == null)
360:                    return true;
361:                if (v1 == v2)
362:                    return true;
363:                if (v1 == null && v2 != null)
364:                    return false;
365:                if (v1 != null && v2 == null)
366:                    return false;
367:
368:                // try to convert v2 into v1 type
369:                v2 = convertToType(v1.getClass(), v2);
370:
371:                if (v1.getClass() != v2.getClass())
372:                    return false;
373:
374:                Class type = v1.getClass();
375:
376:                try {
377:
378:                    if (type == Boolean.class || type == boolean.class) {
379:                        if (!((Boolean) v1).equals((Boolean) v2))
380:                            return false;
381:                    } else if (type == Byte.class || type == byte.class) {
382:                        if (!((Byte) v1).equals((Byte) v2))
383:                            return false;
384:                    } else if (type == Byte[].class) {
385:                        if (!Arrays.equals((Byte[]) v1, (Byte[]) v2))
386:                            return false;
387:                    } else if (type == byte[].class) {
388:                        if (!Arrays.equals((byte[]) v1, (byte[]) v2))
389:                            return false;
390:                    } else if (type == Short.class || type == short.class) {
391:                        if (!((Short) v1).equals((Short) v2))
392:                            return false;
393:                    } else if (type == Integer.class || type == int.class) {
394:                        if (!((Integer) v1).equals((Integer) v2))
395:                            return false;
396:                    } else if (type == Long.class || type == long.class) {
397:                        if (!((Long) v1).equals((Long) v2))
398:                            return false;
399:                    } else if (type == Float.class || type == float.class) {
400:                        Float v1f = (Float) v1;
401:                        Float v2f = (Float) v2;
402:                        if (Float.floatToIntBits(v1f) != Float
403:                                .floatToIntBits(v2f))
404:                            return false;
405:                    } else if (type == Double.class || type == double.class) {
406:                        Double v1d = (Double) v1;
407:                        Double v2d = (Double) v2;
408:                        if (Double.doubleToLongBits(v1d) != Double
409:                                .doubleToLongBits(v2d))
410:                            return false;
411:                    } else if (type == Character.class || type == char.class) {
412:                        if (!((Character) v1).equals((Character) v2))
413:                            return false;
414:                    } else if (type == Character[].class) {
415:                        if (!Arrays.equals((Character[]) v1, (Character[]) v2))
416:                            return false;
417:                    } else if (type == char[].class) {
418:                        if (!Arrays.equals((char[]) v1, (char[]) v2))
419:                            return false;
420:                    } else if (type == String.class) {
421:                        if (!((String) v1).equals((String) v2))
422:                            return false;
423:                    } else if (type == BigDecimal.class) {
424:                        if (!((BigDecimal) v1).equals((BigDecimal) v2))
425:                            return false;
426:                    } else if (type == Reader.class) {
427:                        Reader r1 = (Reader) v1;
428:                        Reader r2 = (Reader) v2;
429:                        if (!compareReaders(r1, r2))
430:                            return false;
431:                    } else if (v1 == InputStream.class) {
432:                        InputStream i1 = (InputStream) v1;
433:                        InputStream i2 = (InputStream) v2;
434:                        if (!compareInputStreams(i1, i2))
435:                            return false;
436:                    } else if (v1 instanceof  Clob) {
437:                        Clob c1 = (Clob) v1;
438:                        Clob c2 = (Clob) v2;
439:                        if (!compareReaders(c1.getCharacterStream(), c2
440:                                .getCharacterStream()))
441:                            return false;
442:                    } else if (v1 instanceof  Blob) {
443:                        Blob b1 = (Blob) v1;
444:                        Blob b2 = (Blob) v2;
445:                        if (!compareInputStreams(b1.getBinaryStream(), b2
446:                                .getBinaryStream()))
447:                            return false;
448:                    } else if (type == java.util.Date.class) {
449:                        java.util.Date d1 = (java.util.Date) v1;
450:                        java.util.Date d2 = (java.util.Date) v2;
451:                        if (!d1.toString().substring(0, 19).equals(
452:                                d2.toString().substring(0, 19)))
453:                            return false;
454:                    } else if (type == java.sql.Date.class) {
455:                        java.sql.Date d1 = (java.sql.Date) v1;
456:                        java.sql.Date d2 = (java.sql.Date) v2;
457:                        if (!d1.toString().equals(d2.toString()))
458:                            return false;
459:                    } else if (type == java.sql.Time.class) {
460:                        java.sql.Time d1 = (java.sql.Time) v1;
461:                        java.sql.Time d2 = (java.sql.Time) v2;
462:                        if (!d1.toString().equals(d2.toString()))
463:                            return false;
464:                    } else if (type == java.sql.Timestamp.class) {
465:                        java.sql.Timestamp d1 = (java.sql.Timestamp) v1;
466:                        java.sql.Timestamp d2 = (java.sql.Timestamp) v2;
467:                        // quick fix for smalldatetimes is to compare up to 15, instead of 19
468:                        if (!d1.toString().substring(0, 15).equals(
469:                                d2.toString().substring(0, 15)))
470:                            return false;
471:                    } else if (!v1.equals(v2))
472:                        return false;
473:
474:                } catch (Exception e) {
475:                    throw new RuntimeException(e);
476:                }
477:
478:                return true;
479:            }
480:
481:            /**
482:             * Try to convert the provided object to the provided class. 
483:             * The following groups of types allow for conversion among their types:
484:             * { String, char, Character, char[], Character[], Reader }
485:             * { byte[], Byte[], InputStream }
486:             * { boolean, Boolean }
487:             * { byte, Byte, short, Short, int, Integer, long, Long, float, Float, double, Double, BigDecimal }
488:             * { java.sql.Timestamp, java.sql.Date, java.sql.Time, java.util.Date }
489:             */
490:            public static Object convertToType(Class cls, Object value) {
491:
492:                if (cls == value.getClass())
493:                    return value;
494:
495:                // if cls implements Clob or Blob, upcast
496:                for (Class iface : cls.getInterfaces()) {
497:                    if (iface == Clob.class) {
498:                        cls = Clob.class;
499:                        break;
500:                    } else if (iface == Blob.class) {
501:                        cls = Blob.class;
502:                        break;
503:                    }
504:                }
505:
506:                Class clsValue = value.getClass();
507:
508:                if (cls == String.class || cls == char.class
509:                        || cls == Character.class || cls == char[].class
510:                        || cls == Character[].class || cls == Reader.class
511:                        || cls == Clob.class) {
512:
513:                    // first convert it to string
514:
515:                    String s = null;
516:
517:                    if (clsValue == String.class) {
518:                        s = (String) value;
519:                    } else if (clsValue == char.class
520:                            || clsValue == Character.class) {
521:                        s = "" + value;
522:                    } else if (clsValue == char[].class) {
523:                        s = String.copyValueOf((char[]) value);
524:                    } else if (clsValue == Character[].class) {
525:                        Character[] a = (Character[]) value;
526:                        char[] ac = new char[a.length];
527:                        for (int i = 0; i < a.length; i++)
528:                            ac[i] = a[i];
529:                        s = String.copyValueOf(ac);
530:                    } else if (value instanceof  Reader) {
531:                        Reader r2 = (Reader) value;
532:                        s = readReader(r2);
533:                    } else if (value instanceof  Clob) {
534:                        Clob c2 = (Clob) value;
535:                        try {
536:                            s = readReader(c2.getCharacterStream());
537:                        } catch (SQLException e) {
538:                            throw new RuntimeException(e);
539:                        }
540:                    } else {
541:                        return value;
542:                    }
543:
544:                    // now convert it to the target type
545:
546:                    if (cls == String.class) {
547:                        return s;
548:                    } else if (cls == char.class) {
549:                        if (s.length() == 1)
550:                            return s.charAt(0);
551:                        else
552:                            return value;
553:                    } else if (cls == Character.class) {
554:                        if (s.length() == 1)
555:                            return new Character(s.charAt(0));
556:                        else
557:                            return value;
558:                    } else if (cls == char[].class) {
559:                        return s.toCharArray();
560:                    } else if (cls == Character[].class) {
561:                        Character[] ret = new Character[s.length()];
562:                        for (int i = 0; i < s.length(); i++)
563:                            ret[i] = new Character(s.charAt(i));
564:                        return ret;
565:                    } else if (cls == Reader.class) {
566:                        return new StringReader(s);
567:                    } else if (cls == Clob.class) {
568:                        return new StringClob(s);
569:                    }
570:                }
571:
572:                else if (cls == byte[].class || cls == Byte[].class
573:                        || cls == InputStream.class || cls == Blob.class) {
574:
575:                    // first convert to byte[]
576:
577:                    byte[] a = null;
578:                    if (clsValue == byte[].class) {
579:                        a = (byte[]) value;
580:                    } else if (clsValue == Byte[].class) {
581:                        Byte[] ba = (Byte[]) value;
582:                        a = new byte[ba.length];
583:                        for (int i = 0; i < ba.length; i++)
584:                            a[i] = ba[i];
585:                    } else if (value instanceof  InputStream) {
586:                        InputStream is = (InputStream) value;
587:                        a = readInputStream(is);
588:                    } else if (value instanceof  Blob) {
589:                        Blob b = (Blob) value;
590:                        try {
591:                            a = readInputStream(b.getBinaryStream());
592:                        } catch (SQLException e) {
593:                            throw new RuntimeException(e);
594:                        }
595:                    } else
596:                        return value;
597:
598:                    // now convert to target class
599:
600:                    if (cls == byte[].class) {
601:                        return a;
602:                    } else if (cls == Byte[].class) {
603:                        Byte[] ba = new Byte[a.length];
604:                        for (int i = 0; i < a.length; i++)
605:                            ba[i] = a[i];
606:                        return ba;
607:                    } else if (cls == InputStream.class) {
608:                        return new ByteArrayInputStream(a);
609:                    } else if (cls == Blob.class) {
610:                        return new BytesBlob(a);
611:                    }
612:                }
613:
614:                else if (clsValue == java.util.Date.class) {
615:                    java.util.Date d = (java.util.Date) value;
616:                    if (cls == java.sql.Date.class) {
617:                        return new java.sql.Date(d.getTime());
618:                    }
619:                    if (cls == java.sql.Time.class) {
620:                        return new java.sql.Time(d.getTime());
621:                    }
622:                    if (cls == java.sql.Timestamp.class) {
623:                        return new java.sql.Timestamp(d.getTime());
624:                    } else
625:                        return value;
626:                }
627:
628:                else if (cls == java.util.Date.class) {
629:                    if (clsValue == java.sql.Date.class) {
630:                        return new java.util.Date(((java.sql.Date) value)
631:                                .getTime());
632:                    }
633:                    if (clsValue == java.sql.Time.class) {
634:                        return new java.util.Date(((java.util.Date) value)
635:                                .getTime());
636:                    }
637:                    if (clsValue == java.sql.Timestamp.class) {
638:                        return new java.util.Date(((java.util.Date) value)
639:                                .getTime());
640:                    } else
641:                        return value;
642:                }
643:
644:                else if (clsValue == boolean.class || clsValue == Boolean.class) {
645:                    Boolean b = (Boolean) value;
646:                    if (cls == boolean.class)
647:                        return b.booleanValue();
648:                    else if (cls == Boolean.class)
649:                        return b;
650:                    else
651:                        return value;
652:                }
653:
654:                else if (clsValue == byte.class || clsValue == Byte.class
655:                        || clsValue == short.class || clsValue == Short.class
656:                        || clsValue == int.class || clsValue == Integer.class
657:                        || clsValue == long.class || clsValue == Long.class
658:                        || clsValue == float.class || clsValue == Float.class
659:                        || clsValue == double.class || clsValue == Double.class
660:                        || clsValue == BigDecimal.class) {
661:
662:                    // first cast to Number
663:                    Number n = (Number) value;
664:
665:                    if (cls == byte.class)
666:                        return n.byteValue();
667:                    else if (cls == Byte.class)
668:                        return new Byte(n.byteValue());
669:                    else if (cls == short.class)
670:                        return n.shortValue();
671:                    else if (cls == Short.class)
672:                        return new Short(n.shortValue());
673:                    else if (cls == int.class)
674:                        return n.intValue();
675:                    else if (cls == Integer.class)
676:                        return new Integer(n.intValue());
677:                    else if (cls == long.class)
678:                        return n.longValue();
679:                    else if (cls == Long.class)
680:                        return new Long(n.longValue());
681:                    else if (cls == float.class)
682:                        return n.floatValue();
683:                    else if (cls == Float.class)
684:                        return new Float(n.floatValue());
685:                    else if (cls == double.class)
686:                        return n.doubleValue();
687:                    else if (cls == Double.class)
688:                        return new Double(n.doubleValue());
689:                    else if (cls == BigDecimal.class)
690:                        return BigDecimal.valueOf(n.doubleValue());
691:                    else
692:                        return value;
693:                }
694:
695:                return value;
696:            }
697:
698:            public static byte[] readInputStream(InputStream is) {
699:                // assumes no more than 64KB of data
700:                try {
701:                    byte[] buf = new byte[65535];
702:                    int n = is.read(buf);
703:                    if (n < 0)
704:                        n = 0;
705:                    byte[] ret = new byte[n];
706:                    for (int i = 0; i < n; i++)
707:                        ret[i] = buf[i];
708:                    return ret;
709:                } catch (IOException e) {
710:                    throw new RuntimeException(e);
711:                }
712:            }
713:
714:            public static String readReader(Reader r) {
715:                char[] buf = new char[65535];
716:                try {
717:                    int n = r.read(buf);
718:                    return new String(buf, 0, n);
719:                } catch (IOException e) {
720:                    throw new RuntimeException(e);
721:                }
722:            }
723:
724:            private static boolean compareReaders(Reader r1, Reader r2) {
725:                char[] buf1 = new char[65535];
726:                char[] buf2 = new char[65535];
727:                try {
728:                    int n1 = r1.read(buf1);
729:                    int n2 = r2.read(buf2);
730:                    return (n1 == n2 && Arrays.equals(buf1, buf2));
731:                } catch (IOException e) {
732:                    throw new RuntimeException(e);
733:                }
734:            }
735:
736:            private static boolean compareInputStreams(InputStream i1,
737:                    InputStream i2) {
738:                byte[] buf1 = new byte[65535];
739:                byte[] buf2 = new byte[65535];
740:                try {
741:                    int n1 = i1.read(buf1);
742:                    int n2 = i2.read(buf2);
743:                    return (n1 == n2 && Arrays.equals(buf1, buf2));
744:                } catch (IOException e) {
745:                    throw new RuntimeException(e);
746:                }
747:            }
748:
749:            // ---------- create random values ----------
750:
751:            public static boolean randomBoolean() {
752:                return Math.random() > 0.5;
753:            }
754:
755:            public static byte randomByte(byte min, byte max) {
756:                if (min == -1 && max == -1) {
757:                    min = Byte.MIN_VALUE;
758:                    max = Byte.MAX_VALUE;
759:                }
760:                return (byte) (min + Math.random() * (max - min));
761:            }
762:
763:            public static byte[] randomByteArray(int size) {
764:                byte[] a = new byte[size];
765:                for (int i = 0; i < size; i++)
766:                    a[i] = randomByte(Byte.MIN_VALUE, Byte.MAX_VALUE);
767:                return a;
768:            }
769:
770:            public static Byte[] randomByteObjArray(int size) {
771:                Byte[] a = new Byte[size];
772:                for (int i = 0; i < size; i++)
773:                    a[i] = new Byte(randomByte(Byte.MIN_VALUE, Byte.MAX_VALUE));
774:                return a;
775:            }
776:
777:            public static short randomShort(short min, short max) {
778:                if (min == -1 && max == -1) {
779:                    min = Short.MIN_VALUE;
780:                    max = Short.MAX_VALUE;
781:                }
782:                return (short) (min + Math.random() * (max - min));
783:            }
784:
785:            public static int randomInt(int min, int max) {
786:                if (min == -1 && max == -1) {
787:                    min = Integer.MIN_VALUE;
788:                    max = Integer.MAX_VALUE;
789:                }
790:                return (int) (min + Math.random() * (max - min));
791:            }
792:
793:            public static long randomLong(long min, long max) {
794:                if (min == -1 && max == -1) {
795:                    min = Long.MIN_VALUE;
796:                    max = Long.MAX_VALUE;
797:                }
798:                return (long) (min + Math.random() * (max - min));
799:            }
800:
801:            public static float randomFloat(float min, float max) {
802:                if (min == -1 && max == -1) {
803:                    min = Float.MIN_VALUE;
804:                    max = Float.MAX_VALUE;
805:                }
806:                //double f = (int) (Math.random() * 10);
807:                double f = 0;
808:                return (float) (((long) (min + Math.random() * (max - min))) + f / 10);
809:            }
810:
811:            public static double randomDouble(double min, double max) {
812:                if (min == -1 && max == -1) {
813:                    min = Double.MIN_VALUE;
814:                    max = Double.MAX_VALUE;
815:                }
816:                double f = (int) (Math.random() * 10);
817:                return ((long) (min + Math.random() * (max - min))) + f / 10;
818:            }
819:
820:            public static char randomChar() {
821:                byte[] b = new byte[] { (byte) (97 + (byte) (Math.random() * 26)) };
822:                return new String(b).charAt(0);
823:            }
824:
825:            public static char[] randomCharArray(int size) {
826:                return randomString(size).toCharArray();
827:            }
828:
829:            public static Character[] randomCharObjArray(int size) {
830:                Character[] a = new Character[size];
831:                int i = 0;
832:                for (char c : randomString(size).toCharArray()) {
833:                    a[i] = new Character(c);
834:                    i++;
835:                }
836:                return a;
837:            }
838:
839:            public static String randomString(int size) {
840:                byte b[] = new byte[size];
841:                for (int i = 0; i < size; i++) {
842:                    b[i] = (byte) (97 + (byte) (Math.random() * 26));
843:                }
844:                return new String(b);
845:            }
846:
847:            public static long randomTimestamp() {
848:                return (long) (Math.random() * System.currentTimeMillis());
849:            }
850:
851:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.