Source Code Cross Referenced for Util.java in  » Database-JDBC-Connection-Pool » mysql-connector-java-5.1.3 » com » mysql » jdbc » 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 JDBC Connection Pool » mysql connector java 5.1.3 » com.mysql.jdbc 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         Copyright (C) 2002-2007 MySQL AB
003:
004:         This program is free software; you can redistribute it and/or modify
005:         it under the terms of version 2 of the GNU General Public License as 
006:         published by the Free Software Foundation.
007:
008:         There are special exceptions to the terms and conditions of the GPL 
009:         as it is applied to this software. View the full text of the 
010:         exception in file EXCEPTIONS-CONNECTOR-J in the directory of this 
011:         software distribution.
012:
013:         This program is distributed in the hope that it will be useful,
014:         but WITHOUT ANY WARRANTY; without even the implied warranty of
015:         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
016:         GNU General Public License for more details.
017:
018:         You should have received a copy of the GNU General Public License
019:         along with this program; if not, write to the Free Software
020:         Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
021:
022:
023:
024:         */
025:        package com.mysql.jdbc;
026:
027:        import java.io.ObjectInputStream;
028:        import java.io.PrintWriter;
029:        import java.io.StringWriter;
030:        import java.lang.reflect.Constructor;
031:        import java.lang.reflect.InvocationTargetException;
032:        import java.lang.reflect.Method;
033:        import java.math.BigDecimal;
034:        import java.math.BigInteger;
035:        import java.sql.SQLException;
036:        import java.util.HashMap;
037:        import java.util.Iterator;
038:        import java.util.Map;
039:        import java.util.TimeZone;
040:
041:        /**
042:         * Various utility methods for the driver.
043:         * 
044:         * @author Mark Matthews
045:         */
046:        public class Util {
047:            protected static Method systemNanoTimeMethod;
048:
049:            static {
050:                try {
051:                    systemNanoTimeMethod = System.class.getMethod("nanoTime",
052:                            null);
053:                } catch (SecurityException e) {
054:                    systemNanoTimeMethod = null;
055:                } catch (NoSuchMethodException e) {
056:                    systemNanoTimeMethod = null;
057:                }
058:            }
059:
060:            protected static boolean nanoTimeAvailable() {
061:                return systemNanoTimeMethod != null;
062:            }
063:
064:            private static Method CAST_METHOD;
065:
066:            // cache this ourselves, as the method call is statically-synchronized in
067:            // all but JDK6!
068:
069:            private static final TimeZone DEFAULT_TIMEZONE = TimeZone
070:                    .getDefault();
071:
072:            static final TimeZone getDefaultTimeZone() {
073:                return (TimeZone) DEFAULT_TIMEZONE.clone();
074:            }
075:
076:            class RandStructcture {
077:                long maxValue;
078:
079:                double maxValueDbl;
080:
081:                long seed1;
082:
083:                long seed2;
084:            }
085:
086:            private static Util enclosingInstance = new Util();
087:
088:            private static boolean isJdbc4 = false;
089:
090:            private static boolean isColdFusion = false;
091:
092:            static {
093:                try {
094:                    CAST_METHOD = Class.class.getMethod("cast",
095:                            new Class[] { Object.class });
096:                } catch (Throwable t) {
097:                    // ignore - not available in this VM
098:                }
099:
100:                try {
101:                    Class.forName("java.sql.NClob");
102:                    isJdbc4 = true;
103:                } catch (Throwable t) {
104:                    isJdbc4 = false;
105:                }
106:
107:                //
108:                // Detect the ColdFusion MX environment
109:                // 
110:                // Unfortunately, no easy-to-discern classes are available
111:                // to our classloader to check...
112:                //
113:
114:                String loadedFrom = stackTraceToString(new Throwable());
115:
116:                if (loadedFrom != null) {
117:                    isColdFusion = loadedFrom.indexOf("coldfusion") != -1;
118:                } else {
119:                    isColdFusion = false;
120:                }
121:            }
122:
123:            // ~ Methods
124:            // ----------------------------------------------------------------
125:
126:            public static boolean isJdbc4() {
127:                return isJdbc4;
128:            }
129:
130:            public static boolean isColdFusion() {
131:                return isColdFusion;
132:            }
133:
134:            // Right from Monty's code
135:            static String newCrypt(String password, String seed) {
136:                byte b;
137:                double d;
138:
139:                if ((password == null) || (password.length() == 0)) {
140:                    return password;
141:                }
142:
143:                long[] pw = newHash(seed);
144:                long[] msg = newHash(password);
145:                long max = 0x3fffffffL;
146:                long seed1 = (pw[0] ^ msg[0]) % max;
147:                long seed2 = (pw[1] ^ msg[1]) % max;
148:                char[] chars = new char[seed.length()];
149:
150:                for (int i = 0; i < seed.length(); i++) {
151:                    seed1 = ((seed1 * 3) + seed2) % max;
152:                    seed2 = (seed1 + seed2 + 33) % max;
153:                    d = (double) seed1 / (double) max;
154:                    b = (byte) java.lang.Math.floor((d * 31) + 64);
155:                    chars[i] = (char) b;
156:                }
157:
158:                seed1 = ((seed1 * 3) + seed2) % max;
159:                seed2 = (seed1 + seed2 + 33) % max;
160:                d = (double) seed1 / (double) max;
161:                b = (byte) java.lang.Math.floor(d * 31);
162:
163:                for (int i = 0; i < seed.length(); i++) {
164:                    chars[i] ^= (char) b;
165:                }
166:
167:                return new String(chars);
168:            }
169:
170:            static long[] newHash(String password) {
171:                long nr = 1345345333L;
172:                long add = 7;
173:                long nr2 = 0x12345671L;
174:                long tmp;
175:
176:                for (int i = 0; i < password.length(); ++i) {
177:                    if ((password.charAt(i) == ' ')
178:                            || (password.charAt(i) == '\t')) {
179:                        continue; // skip spaces
180:                    }
181:
182:                    tmp = (0xff & password.charAt(i));
183:                    nr ^= ((((nr & 63) + add) * tmp) + (nr << 8));
184:                    nr2 += ((nr2 << 8) ^ nr);
185:                    add += tmp;
186:                }
187:
188:                long[] result = new long[2];
189:                result[0] = nr & 0x7fffffffL;
190:                result[1] = nr2 & 0x7fffffffL;
191:
192:                return result;
193:            }
194:
195:            static String oldCrypt(String password, String seed) {
196:                long hp;
197:                long hm;
198:                long s1;
199:                long s2;
200:                long max = 0x01FFFFFF;
201:                double d;
202:                byte b;
203:
204:                if ((password == null) || (password.length() == 0)) {
205:                    return password;
206:                }
207:
208:                hp = oldHash(seed);
209:                hm = oldHash(password);
210:
211:                long nr = hp ^ hm;
212:                nr %= max;
213:                s1 = nr;
214:                s2 = nr / 2;
215:
216:                char[] chars = new char[seed.length()];
217:
218:                for (int i = 0; i < seed.length(); i++) {
219:                    s1 = ((s1 * 3) + s2) % max;
220:                    s2 = (s1 + s2 + 33) % max;
221:                    d = (double) s1 / max;
222:                    b = (byte) java.lang.Math.floor((d * 31) + 64);
223:                    chars[i] = (char) b;
224:                }
225:
226:                return new String(chars);
227:            }
228:
229:            static long oldHash(String password) {
230:                long nr = 1345345333;
231:                long nr2 = 7;
232:                long tmp;
233:
234:                for (int i = 0; i < password.length(); i++) {
235:                    if ((password.charAt(i) == ' ')
236:                            || (password.charAt(i) == '\t')) {
237:                        continue;
238:                    }
239:
240:                    tmp = password.charAt(i);
241:                    nr ^= ((((nr & 63) + nr2) * tmp) + (nr << 8));
242:                    nr2 += tmp;
243:                }
244:
245:                return nr & ((1L << 31) - 1L);
246:            }
247:
248:            private static RandStructcture randomInit(long seed1, long seed2) {
249:                RandStructcture randStruct = enclosingInstance.new RandStructcture();
250:
251:                randStruct.maxValue = 0x3FFFFFFFL;
252:                randStruct.maxValueDbl = randStruct.maxValue;
253:                randStruct.seed1 = seed1 % randStruct.maxValue;
254:                randStruct.seed2 = seed2 % randStruct.maxValue;
255:
256:                return randStruct;
257:            }
258:
259:            /**
260:             * Given a ResultSet and an index into the columns of that ResultSet, read
261:             * binary data from the column which represents a serialized object, and
262:             * re-create the object.
263:             * 
264:             * @param resultSet
265:             *            the ResultSet to use.
266:             * @param index
267:             *            an index into the ResultSet.
268:             * @return the object if it can be de-serialized
269:             * @throws Exception
270:             *             if an error occurs
271:             */
272:            public static Object readObject(java.sql.ResultSet resultSet,
273:                    int index) throws Exception {
274:                ObjectInputStream objIn = new ObjectInputStream(resultSet
275:                        .getBinaryStream(index));
276:                Object obj = objIn.readObject();
277:                objIn.close();
278:
279:                return obj;
280:            }
281:
282:            private static double rnd(RandStructcture randStruct) {
283:                randStruct.seed1 = ((randStruct.seed1 * 3) + randStruct.seed2)
284:                        % randStruct.maxValue;
285:                randStruct.seed2 = (randStruct.seed1 + randStruct.seed2 + 33)
286:                        % randStruct.maxValue;
287:
288:                return ((randStruct.seed1) / randStruct.maxValueDbl);
289:            }
290:
291:            /**
292:             * DOCUMENT ME!
293:             * 
294:             * @param message
295:             *            DOCUMENT ME!
296:             * @param password
297:             *            DOCUMENT ME!
298:             * 
299:             * @return DOCUMENT ME!
300:             */
301:            public static String scramble(String message, String password) {
302:                long[] hashPass;
303:                long[] hashMessage;
304:                byte[] to = new byte[8];
305:                String val = ""; //$NON-NLS-1$
306:
307:                message = message.substring(0, 8);
308:
309:                if ((password != null) && (password.length() > 0)) {
310:                    hashPass = newHash(password);
311:                    hashMessage = newHash(message);
312:
313:                    RandStructcture randStruct = randomInit(hashPass[0]
314:                            ^ hashMessage[0], hashPass[1] ^ hashMessage[1]);
315:
316:                    int msgPos = 0;
317:                    int msgLength = message.length();
318:                    int toPos = 0;
319:
320:                    while (msgPos++ < msgLength) {
321:                        to[toPos++] = (byte) (Math.floor(rnd(randStruct) * 31) + 64);
322:                    }
323:
324:                    /* Make it harder to break */
325:                    byte extra = (byte) (Math.floor(rnd(randStruct) * 31));
326:
327:                    for (int i = 0; i < to.length; i++) {
328:                        to[i] ^= extra;
329:                    }
330:
331:                    val = new String(to);
332:                }
333:
334:                return val;
335:            }
336:
337:            // ~ Inner Classes
338:            // ----------------------------------------------------------
339:
340:            /**
341:             * Converts a nested exception into a nicer message
342:             * 
343:             * @param ex
344:             *            the exception to expand into a message.
345:             * 
346:             * @return a message containing the exception, the message (if any), and a
347:             *         stacktrace.
348:             */
349:            public static String stackTraceToString(Throwable ex) {
350:                StringBuffer traceBuf = new StringBuffer();
351:                traceBuf.append(Messages.getString("Util.1")); //$NON-NLS-1$
352:
353:                if (ex != null) {
354:                    traceBuf.append(ex.getClass().getName());
355:
356:                    String message = ex.getMessage();
357:
358:                    if (message != null) {
359:                        traceBuf.append(Messages.getString("Util.2")); //$NON-NLS-1$
360:                        traceBuf.append(message);
361:                    }
362:
363:                    StringWriter out = new StringWriter();
364:
365:                    PrintWriter printOut = new PrintWriter(out);
366:
367:                    ex.printStackTrace(printOut);
368:
369:                    traceBuf.append(Messages.getString("Util.3")); //$NON-NLS-1$
370:                    traceBuf.append(out.toString());
371:                }
372:
373:                traceBuf.append(Messages.getString("Util.4")); //$NON-NLS-1$
374:
375:                return traceBuf.toString();
376:            }
377:
378:            public static Object getInstance(String className,
379:                    Class[] argTypes, Object[] args) throws SQLException {
380:
381:                try {
382:                    return handleNewInstance(Class.forName(className)
383:                            .getConstructor(argTypes), args);
384:                } catch (SecurityException e) {
385:                    throw SQLError.createSQLException(
386:                            "Can't instantiate required class",
387:                            SQLError.SQL_STATE_GENERAL_ERROR, e);
388:                } catch (NoSuchMethodException e) {
389:                    throw SQLError.createSQLException(
390:                            "Can't instantiate required class",
391:                            SQLError.SQL_STATE_GENERAL_ERROR, e);
392:                } catch (ClassNotFoundException e) {
393:                    throw SQLError.createSQLException(
394:                            "Can't instantiate required class",
395:                            SQLError.SQL_STATE_GENERAL_ERROR, e);
396:                }
397:            }
398:
399:            /**
400:             * Handles constructing new instance with the given constructor and wrapping
401:             * (or not, as required) the exceptions that could possibly be generated
402:             */
403:            public static final Object handleNewInstance(Constructor ctor,
404:                    Object[] args) throws SQLException {
405:                try {
406:
407:                    return ctor.newInstance(args);
408:                } catch (IllegalArgumentException e) {
409:                    throw SQLError.createSQLException(
410:                            "Can't instantiate required class",
411:                            SQLError.SQL_STATE_GENERAL_ERROR, e);
412:                } catch (InstantiationException e) {
413:                    throw SQLError.createSQLException(
414:                            "Can't instantiate required class",
415:                            SQLError.SQL_STATE_GENERAL_ERROR, e);
416:                } catch (IllegalAccessException e) {
417:                    throw SQLError.createSQLException(
418:                            "Can't instantiate required class",
419:                            SQLError.SQL_STATE_GENERAL_ERROR, e);
420:                } catch (InvocationTargetException e) {
421:                    Throwable target = e.getTargetException();
422:
423:                    if (target instanceof  SQLException) {
424:                        throw (SQLException) target;
425:                    }
426:
427:                    if (target instanceof  ExceptionInInitializerError) {
428:                        target = ((ExceptionInInitializerError) target)
429:                                .getException();
430:                    }
431:
432:                    throw SQLError.createSQLException(target.toString(),
433:                            SQLError.SQL_STATE_GENERAL_ERROR);
434:                }
435:            }
436:
437:            /**
438:             * Does a network interface exist locally with the given hostname?
439:             * 
440:             * @param hostname
441:             *            the hostname (or IP address in string form) to check
442:             * @return true if it exists, false if no, or unable to determine due to VM
443:             *         version support of java.net.NetworkInterface
444:             */
445:            public static boolean interfaceExists(String hostname) {
446:                try {
447:                    Class networkInterfaceClass = Class
448:                            .forName("java.net.NetworkInterface");
449:                    return networkInterfaceClass.getMethod("getByName", null)
450:                            .invoke(networkInterfaceClass,
451:                                    new Object[] { hostname }) != null;
452:                } catch (Throwable t) {
453:                    return false;
454:                }
455:            }
456:
457:            /**
458:             * Reflexive access on JDK-1.5's Class.cast() method so we don't have to
459:             * move that out into separate classes built for JDBC-4.0.
460:             * 
461:             * @param invokeOn
462:             * @param toCast
463:             * @return
464:             */
465:            public static Object cast(Object invokeOn, Object toCast) {
466:                if (CAST_METHOD != null) {
467:                    try {
468:                        return CAST_METHOD.invoke(invokeOn,
469:                                new Object[] { toCast });
470:                    } catch (Throwable t) {
471:                        return null;
472:                    }
473:                }
474:
475:                return null;
476:            }
477:
478:            public static long getCurrentTimeNanosOrMillis() {
479:                if (systemNanoTimeMethod != null) {
480:                    try {
481:                        return ((Long) systemNanoTimeMethod.invoke(null, null))
482:                                .longValue();
483:                    } catch (IllegalArgumentException e) {
484:                        // ignore - fall through to currentTimeMillis()
485:                    } catch (IllegalAccessException e) {
486:                        // ignore - fall through to currentTimeMillis()
487:                    } catch (InvocationTargetException e) {
488:                        // ignore - fall through to currentTimeMillis()
489:                    }
490:                }
491:
492:                return System.currentTimeMillis();
493:            }
494:
495:            public static void resultSetToMap(Map mappedValues,
496:                    java.sql.ResultSet rs) throws SQLException {
497:                while (rs.next()) {
498:                    mappedValues.put(rs.getObject(1), rs.getObject(2));
499:                }
500:            }
501:
502:            public static Map calculateDifferences(Map map1, Map map2) {
503:                Map diffMap = new HashMap();
504:
505:                Iterator map1Entries = map1.entrySet().iterator();
506:
507:                while (map1Entries.hasNext()) {
508:                    Map.Entry entry = (Map.Entry) map1Entries.next();
509:                    Object key = entry.getKey();
510:
511:                    Number value1 = null;
512:                    Number value2 = null;
513:
514:                    if (entry.getValue() instanceof  Number) {
515:
516:                        value1 = (Number) entry.getValue();
517:                        value2 = (Number) map2.get(key);
518:                    } else {
519:                        try {
520:                            value1 = new Double(entry.getValue().toString());
521:                            value2 = new Double(map2.get(key).toString());
522:                        } catch (NumberFormatException nfe) {
523:                            continue;
524:                        }
525:                    }
526:
527:                    if (value1.equals(value2)) {
528:                        continue;
529:                    }
530:
531:                    if (value1 instanceof  Byte) {
532:                        diffMap.put(key, new Byte((byte) (((Byte) value2)
533:                                .byteValue() - ((Byte) value1).byteValue())));
534:                    } else if (value1 instanceof  Short) {
535:                        diffMap
536:                                .put(key, new Short((short) (((Short) value2)
537:                                        .shortValue() - ((Short) value1)
538:                                        .shortValue())));
539:                    } else if (value1 instanceof  Integer) {
540:                        diffMap.put(key, new Integer((((Integer) value2)
541:                                .intValue() - ((Integer) value1).intValue())));
542:                    } else if (value1 instanceof  Long) {
543:                        diffMap.put(key, new Long(
544:                                (((Long) value2).longValue() - ((Long) value1)
545:                                        .longValue())));
546:                    } else if (value1 instanceof  Float) {
547:                        diffMap.put(key, new Float(((Float) value2)
548:                                .floatValue()
549:                                - ((Float) value1).floatValue()));
550:                    } else if (value1 instanceof  Double) {
551:                        diffMap
552:                                .put(key, new Double((((Double) value2)
553:                                        .shortValue() - ((Double) value1)
554:                                        .shortValue())));
555:                    } else if (value1 instanceof  BigDecimal) {
556:                        diffMap.put(key, ((BigDecimal) value2)
557:                                .subtract((BigDecimal) value1));
558:                    } else if (value1 instanceof  BigInteger) {
559:                        diffMap.put(key, ((BigInteger) value2)
560:                                .subtract((BigInteger) value1));
561:                    }
562:                }
563:
564:                return diffMap;
565:            }
566:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.