Source Code Cross Referenced for RKUtil.java in  » Database-Client » SQLMinus » util » 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 Client » SQLMinus » util 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        package util;
002:
003:        import java.text.*;
004:        import java.util.*;
005:        import java.sql.*;
006:
007:        /**
008:         * utility class for some frontend checks and conversions.
009:         * @author Rahul Kumar
010:         *
011:         * RK modified on 20021217 04:48:42
012:         * Added methods for next month,date,year etc
013:         */
014:        public class RKUtil {
015:
016:            /** converts a string that contains a date to a Date.
017:             * The entry string should not be null else a Nullpointer will be thrown
018:             * @param String in date format
019:             * @return java.util.Date
020:             * @throws ParseException if date is invalid or wrong format
021:             * @throws NullPointer if  input is blank We can probably formally throw a BlankString
022:             * exception in a future version so that the callers dont suffer NPE's.
023:             */
024:            public static java.util.Date DateStringToDate(String d)
025:                    throws ParseException {
026:                // added on 22/09
027:                d.replace('-', '/');
028:                d.replace('.', '/');
029:
030:                SimpleDateFormat sdf = new SimpleDateFormat("dd'/'MM'/'yyyy");
031:                sdf.setLenient(false); // this is required else it will convert
032:                java.util.Date dt = sdf.parse(d);
033:                return dt;
034:            }
035:
036:            /** Converts a given date string to a date. A user may enter only a year, 
037:             * this would get converted to the first day of the year.
038:             * User may enter only date, and the current month and year would be added.
039:             * User may enter only date and month, and year would be added.
040:             */
041:            public static java.util.Date FriendlyDateStringToDate(String d)
042:                    throws ParseException {
043:                if (d == null)
044:                    return new java.util.Date();
045:
046:                d.replace('-', '/');
047:                d.replace('.', '/');
048:                int len = d.length();
049:                if (d.indexOf('/') != -1) {
050:                    if (len == 4) // 4 numbers could be a year
051:                        d = "01/01/" + d;
052:                    else {
053:                        Calendar cal = Calendar.getInstance();
054:                        cal.setTime((new java.util.Date()));
055:                        String month = String.valueOf(cal.get(Calendar.MONTH));
056:                        String year = String.valueOf(cal.get(Calendar.YEAR));
057:                        if (len < 3) // 1 or 2 numbers could be a day
058:                            d += '/' + month + '/' + year;
059:                    }
060:                } else if (len < 6) {
061:                    Calendar cal = Calendar.getInstance();
062:                    cal.setTime((new java.util.Date()));
063:                    //String month = String.valueOf(cal.get(Calendar.MONTH));
064:                    String year = String.valueOf(cal.get(Calendar.YEAR));
065:                    d += '/' + year;
066:                }
067:                return DateStringToDate(d);
068:            }
069:
070:            /**
071:             * Takes a date string (that a user has entered) and returns a java.sql.Date.
072:             * The return date can be carried all the way through to the backend.
073:             * Please start using this and avoid util dates !!!
074:             * @param String date string from HTML form
075:             * @return java.sql.Date date for the given string
076:             * @throws ParseException if string contains invalid date
077:             *
078:             */
079:            public static java.sql.Date DateStringToSQLDate(String d)
080:                    throws ParseException {
081:
082:                SimpleDateFormat sdf = new SimpleDateFormat("dd'/'MM'/'yyyy");
083:                sdf.setLenient(false); // this is required else it will convert
084:                java.util.Date dt = sdf.parse(d);
085:                java.sql.Date sqldt = new java.sql.Date(dt.getTime());
086:                return sqldt;
087:            }
088:
089:            /** converts date to a string in indian format
090:             * @param Date to be converted
091:             * @return String in Indian Format
092:             *
093:             *
094:             */
095:            public static String DateToDateString(java.util.Date d) {
096:                if (d == null)
097:                    return ""; // HACK for webapps
098:
099:                SimpleDateFormat sdf = new SimpleDateFormat("dd'/'MM'/'yyyy");
100:                sdf.setLenient(false); // this is required else it will convert
101:                String dateString = sdf.format(d);
102:                return dateString;
103:            }
104:
105:            /** converts date to a string in indian format
106:             * @param Date to be converted
107:             * @return String in Indian Format
108:             * differs from the above in that it does not throw an exception
109:             * the date is considered to be valid since it is a util date
110:             *
111:             */
112:            public static String DateToString(java.util.Date d) {
113:
114:                String dateString = null;
115:                try {
116:                    SimpleDateFormat sdf = new SimpleDateFormat(
117:                            "dd'/'MM'/'yyyy");
118:                    sdf.setLenient(false); // this is required else it will convert
119:                    dateString = sdf.format(d);
120:                } catch (Exception pe) {
121:                }
122:                return dateString;
123:            }
124:
125:            /** Validates whether the input string is blank.
126:             * @param text String to be checked
127:             * @return boolean is null true, is not null false
128:             * The caller should use this method prior to validating a date or doing a
129:             * parseInt
130:             */
131:            public static boolean isNullString(String text) {
132:                //System.err.println("isnull got :" + text +".");
133:                if (text == null)
134:                    return true;
135:                if (text.trim().length() == 0)
136:                    return true;
137:                return false;
138:            }
139:
140:            /** returns current date in Indian format - UGH it returns date
141:             * only, not time.
142:             *
143:             */
144:            public static String CurrentDateString() {
145:                java.util.Date mydate = new java.util.Date();
146:                SimpleDateFormat sdf = new SimpleDateFormat("dd'/'MM'/'yyyy");
147:                String dateString = sdf.format(mydate);
148:                return dateString;
149:            }
150:
151:            /**
152:             * Returns a JDBC compliant date string for the current date
153:             * Time is blanked out in the result.
154:             * Use this to update tables with system date.
155:             */
156:            public static String CurrentSQLDateString() {
157:                return (new java.sql.Date(System.currentTimeMillis()))
158:                        .toString();
159:            }
160:
161:            /**
162:             * Returns a JDBC compliant datetime string for the current date
163:             * This includes the current time.
164:             * Use this to update tables with system timestamp.
165:             */
166:            public static String CurrentSQLTimeString() {
167:                return (new java.sql.Timestamp(System.currentTimeMillis()))
168:                        .toString();
169:                /**
170:                 * Converts a java.util Date to a JDBC compliant SQL Date
171:                 * You may use this to convert frontend dates to SQL dates before storing
172:                 * in database.
173:                 * Please use a java.sql.Date henceforth and avoid using this.
174:                 */
175:            }
176:
177:            public static String UtilDateToSQLDate(java.util.Date UtilDate) {
178:                return (new java.sql.Date(UtilDate.getTime())).toString();
179:            }
180:
181:            /**
182:             * Converts a java.sql Date to a date string in Indian format
183:             */
184:
185:            public static String SQLDateToDateString(java.sql.Date d) {
186:                //			System.out.println(d);
187:                SimpleDateFormat sdf = new SimpleDateFormat("dd'/'MM'/'yyyy");
188:                sdf.setLenient(false); // this is required else it will convert
189:                String dateString = sdf.format(d);
190:                //            System.out.println(dateString);
191:                return dateString;
192:            }
193:
194:            /**
195:             * @deprecated
196:             */
197:            public static Connection OLDgetConnection() {
198:                String username = "root";
199:                String password = "root";
200:                String url;
201:                Connection dbConnection = null;
202:
203:                // The URL that will connect to TECFA's MySQL server
204:                // Syntax: jdbc:TYPE:machine:port/DB_NAME
205:                url = "jdbc:mysql://localhost:3306/test";
206:                // ---- configure END
207:
208:                // INSTALL/load the Driver (Vendor specific Code)
209:                try {
210:                    Class.forName("org.gjt.mm.mysql.Driver");
211:                } catch (java.lang.ClassNotFoundException e) {
212:                    System.err.print("ClassNotFoundException: ");
213:                    System.err.println(e.getMessage());
214:                }
215:
216:                try {
217:                    //Connection con;
218:
219:                    // Establish Connection to the database at URL with usename and password
220:                    dbConnection = DriverManager.getConnection(url, username,
221:                            password);
222:                    //Statement stmt;
223:                }
224:                // print out decent erreur messages
225:                // this exception should go to caller program so that he doesnt go ahead
226:                catch (SQLException ex) {
227:                    System.err.println("==> SQLException: ");
228:                    while (ex != null) {
229:                        System.out.println("Message:   " + ex.getMessage());
230:                        System.out.println("SQLState:  " + ex.getSQLState());
231:                        System.out.println("ErrorCode: " + ex.getErrorCode());
232:                        ex = ex.getNextException();
233:                    } // ex
234:
235:                } //catch
236:                return dbConnection;
237:            } // getConnection
238:
239:            /**
240:             * checks for existence of "at" and "dot" in email in that order.
241:             * @param String email
242:             * @return true if valid, false if invalid
243:             */
244:            public static boolean isEmailValid(String text) {
245:                if (RKUtil.isNullString(text))
246:                    return false;
247:                int at = 0;
248:                int dot = 0;
249:                at = text.indexOf("@");
250:                dot = text.indexOf(".");
251:                if (at != -1 && dot != -1 && (dot - at) > 1)
252:                    return true;
253:                return false;
254:            }
255:
256:            public static String printErrors(List errstr) {
257:                int size = errstr.size();
258:                String out = new String("");
259:                if (size > 0) {
260:                    out = out
261:                            + "<table width='80%' border='0' cellspacing='0' cellpadding='0'>"
262:                            + "<tr>"
263:                            + "<td>"
264:                            + "<table width='100%' cellpadding='1' cellspacing='1' align='center' border='0' >"
265:                            + "<tr bgcolor='#98BDEB'><td>You have " + size
266:                            + " errors.</td></tr>";
267:                } else
268:                    return "<h3>No errors.</h3>";
269:                for (int i = 0; i < size; i++) {
270:                    String s = (String) errstr.get(i);
271:                    out = out + "<tr bgcolor='#cccccc'><td>" + (i + 1) + ".  "
272:                            + s + "</td></tr>";
273:                }
274:                out = out + "</table></td></tr></table><BR>Please Enter Again";
275:                return out;
276:            }
277:
278:            //This method generates a random password
279:            public static String GenerateNewPassword() {
280:                String Password = new String();
281:                for (int i = 1; i <= 10; i++) {
282:                    double number = java.lang.Math.random() * 100;
283:                    int num = (int) number;
284:                    if (num < 65 || num > 90) {
285:                        Password = Password + num;
286:                    } else {
287:                        Password = Password + (char) num;
288:                    }
289:                }
290:                return Password;
291:            }
292:
293:            /** if a string is null returns a blank else the string itself
294:             * more for use in JSPs to cut down code.
295:             */
296:            public static String NullToString(String astring) {
297:                return (astring == null) ? "" : astring;
298:            }
299:
300:            //Added By Puneet.
301:            /**	converts a string that contains a date and time to a Date.
302:             * The entry string should not be null else a Nullpointer will be thrown
303:             * @param String in date format
304:             * @return java.util.Date
305:             * @throws ParseException if date is invalid or wrong format
306:             * @throws NullPointer if  input is blank We can probably formally throw a BlankString
307:             * exception in a future version so that the callers dont suffer NPE's.
308:             */
309:            public static java.sql.Date DateStringToSQLDateTime(String d)
310:                    throws ParseException {
311:                if (d == null)
312:                    return null;
313:                SimpleDateFormat sdf = new SimpleDateFormat(
314:                        "dd'/'MM'/'yyyy HH:mm:ss");
315:                sdf.setLenient(false);
316:                java.sql.Date date = new java.sql.Date(sdf.parse(d).getTime());
317:                return date;
318:            }
319:
320:            public static java.sql.Timestamp DateStringToSQLTimestamp(String d)
321:                    throws ParseException {
322:                if (d == null)
323:                    return null;
324:                SimpleDateFormat sdf = new SimpleDateFormat(
325:                        "dd'/'MM'/'yyyy HH:mm:ss");
326:                sdf.setLenient(false);
327:                java.sql.Timestamp date = new java.sql.Timestamp(sdf.parse(d)
328:                        .getTime());
329:                return date;
330:            }
331:
332:            /** converts date to a string in indian format
333:             * @param Date to be converted - can be sql date or timestamp
334:             * @return String in Indian Format
335:             *
336:             *
337:             */
338:            public static String DateTimeToDateString(java.util.Date d) {
339:
340:                // hack for web XXX
341:                if (d == null)
342:                    return "";
343:                SimpleDateFormat sdf = new SimpleDateFormat(
344:                        "dd'/'MM'/'yyyy HH':'mm':'ss");
345:                sdf.setLenient(false); // this is required else it will convert
346:                String dateString = sdf.format(d);
347:                return dateString;
348:            }
349:
350:            public static String DateTimeToDateString(java.sql.Timestamp d) {
351:
352:                // hack for web XXX
353:                return DateTimeToDateString((java.util.Date) d);
354:            }
355:
356:            public static String DateToTimeString(java.util.Date d) {
357:
358:                // hack for web XXX
359:                if (d == null)
360:                    return "";
361:                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
362:                sdf.setLenient(false); // this is required else it will convert
363:                String dateString = sdf.format(d);
364:                return dateString;
365:            }
366:
367:            //public String[] split (String st) {}
368:
369:            /** splits a given string on given character separator returning
370:             * an array of strings.
371:             * @author Rahul Kumar June 17, 2001
372:             * How to deal with consecutive delimiters - i am returning blank
373:             * strings.
374:             */
375:            public static String[] split(String st, char sep) {
376:
377:                ArrayList alist = new ArrayList();
378:
379:                int len = st.length();
380:                int pos = 0;
381:                int fin = 0;
382:
383:                // while not end of string, and you can find a match
384:                while (pos < len && (fin = st.indexOf(sep, pos)) != -1) {
385:                    alist.add(st.substring(pos, fin));
386:                    pos = fin + 1;
387:                }
388:                // Push remainder if it's not empty
389:                String remainder = st.substring(pos);
390:                if (remainder.length() != 0) {
391:                    alist.add(remainder);
392:                }
393:
394:                // Return list as an array of strings
395:                String[] ret = new String[alist.size()];
396:                alist.toArray(ret);
397:                return ret;
398:            }
399:
400:            /** returns (full date for) months after or before given date, if no date passed
401:             * then current date used.
402:             * int month can be negative or positive
403:             * This can be used along with CurrentTimeString to give default
404:             * dates in textboxes to user.
405:             */
406:            public static String NextMonthString(java.util.Date base, int month) {
407:                return NextDateString(base, Calendar.MONTH, month);
408:            }
409:
410:            /** returns full date for years from the given date. 
411:             * @param year  int how man years from current +-.
412:             */
413:            public static String NextYearString(java.util.Date base, int year) {
414:                return NextDateString(base, Calendar.YEAR, year);
415:            }
416:
417:            /** int unit is Calendar.MONTH, YEAR or DATE 
418:             * int period is plus or minus months, days etc.
419:             */
420:            public static String NextDateString(java.util.Date base, int unit,
421:                    int period) {
422:                java.util.Date mydate = null;
423:                if (base == null)
424:                    mydate = new java.util.Date();
425:                else
426:                    mydate = base;
427:                Calendar cal = Calendar.getInstance();
428:                cal.setTime(mydate);
429:                cal.add(unit, period);
430:                mydate = cal.getTime();
431:                SimpleDateFormat sdf = new SimpleDateFormat("dd'/'MM'/'yyyy");
432:                String dateString = sdf.format(mydate);
433:                return dateString;
434:            }
435:
436:            public static int NextPeriod(java.util.Date base, int unit,
437:                    int period) {
438:                java.util.Date mydate = null;
439:                if (base == null)
440:                    mydate = new java.util.Date();
441:                else
442:                    mydate = base;
443:                Calendar cal = Calendar.getInstance();
444:                cal.setTime(mydate);
445:                cal.add(unit, period);
446:                return cal.get(unit);
447:            }
448:
449:            /** returns the year part as int given a base date and how many
450:             * years from base.
451:             */
452:            public static int NextYear(java.util.Date base, int period) {
453:                return NextPeriod(base, Calendar.YEAR, period);
454:            }
455:
456:            /** returns the month part as int given a base date and how many
457:             * month from base.
458:             */
459:            public static int NextMonth(java.util.Date base, int period) {
460:                return NextPeriod(base, Calendar.MONTH, period) + 1;
461:            }
462:
463:            /** returns the day part as int given a base date and how many
464:             * day from base.
465:             */
466:            public static int NextDay(java.util.Date base, int period) {
467:                return NextPeriod(base, Calendar.DATE, period);
468:            }
469:
470:            public static String findFileInClassPath(String name) {
471:
472:                String path = System.getProperty("java.class.path");
473:                String[] dirs = split(path, (System
474:                        .getProperty("path.separator")).charAt(0));
475:                String fullname = null;
476:                java.io.File f, g;
477:                for (int i = 0; i < dirs.length; i++) {
478:                    f = new java.io.File(dirs[i]);
479:                    if (f.isDirectory()) {
480:                        fullname = dirs[i]
481:                                + System.getProperty("file.separator") + name;
482:                        g = new java.io.File(fullname);
483:                        if (g.exists())
484:                            return fullname;
485:                        g = null;
486:                    } // if directory
487:                    f = null;
488:                } // for i
489:                return null;
490:            } // findFileInClassPath
491:
492:            public static void main(String args[]) {
493:
494:                System.out.println(findFileInClassPath("ini.xml"));
495:                System.out.println(findFileInClassPath("labels.props"));
496:                System.out.println(findFileInClassPath("log4j.properties"));
497:                System.out.println("CurrentDateString:" + CurrentDateString());
498:                System.out.println("CurrentSQLDateString:"
499:                        + CurrentSQLDateString());
500:                System.out.println("CurrentSQLTimeString:"
501:                        + CurrentSQLTimeString());
502:            }
503:
504:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.