0001: package com.salmonllc.util;
0002:
0003: /////////////////////////
0004: //$Archive: /SOFIA/SourceCode/com/salmonllc/util/Util.java $
0005: //$Author: Dan $
0006: //$Revision: 46 $
0007: //$Modtime: 11/08/04 11:36a $
0008: /////////////////////////
0009: import java.awt.Color;
0010: import java.lang.reflect.InvocationTargetException;
0011: import java.lang.reflect.Method;
0012: import java.sql.Time;
0013: import java.sql.Timestamp;
0014: import java.sql.Date;
0015: import java.util.ArrayList;
0016: import java.util.Calendar;
0017: import java.util.GregorianCalendar;
0018: import java.util.StringTokenizer;
0019:
0020: import com.salmonllc.html.*;
0021: import com.salmonllc.sql.DataStore;
0022:
0023: /**
0024: * This class is used to hold general helper methods
0025: */
0026: public class Util {
0027:
0028: private static int NUM_MILLIS_IN_DAY = (1000 * 60 * 60 * 24);
0029:
0030: public static java.sql.Date getDateObject(int iYear, int iMonth,
0031: int iDay, int iHour, int iMinute) {
0032: GregorianCalendar greCal = new GregorianCalendar();
0033:
0034: if (iYear > 0) {
0035: greCal.set(Calendar.YEAR, iYear);
0036: }
0037:
0038: /*
0039: Claudio Pi (4-01-2003) Commented out since
0040: Util.getDateObject(2003,1-1,0,1,1).toString() returned 2003-04-01 instead of 2003-01-01
0041:
0042: srufle: greCal.MONTH ranges from 0 to 11
0043: From java.util.Calendar Javadoc
0044: public final void set(int year,
0045: int month,
0046: int date)
0047: month - the value used to set the MONTH time field. Month value is 0-based. e.g., 0 for January.
0048: */
0049: greCal.set(Calendar.MONTH, iMonth);
0050:
0051: if (iDay > 0) {
0052: greCal.set(Calendar.DAY_OF_MONTH, iDay);
0053: }
0054:
0055: if (iHour > 0) {
0056: greCal.set(Calendar.HOUR_OF_DAY, iHour);
0057: }
0058:
0059: if (iMinute > 0) {
0060: greCal.set(Calendar.MINUTE, iMinute);
0061: }
0062:
0063: java.sql.Date sqlDate = new java.sql.Date(greCal.getTime()
0064: .getTime());
0065:
0066: return sqlDate;
0067: }
0068:
0069: /**
0070: * This method checks to see if the string passed into it is a double value. It returns true if the string parses to a double.
0071: *
0072: * @param s java.lang.String
0073: *
0074: * @return boolean If the String is a double value
0075: */
0076: public static boolean isDouble(String s) {
0077: boolean ret = false;
0078:
0079: if (!isNumeric(s)) {
0080: try {
0081: Double.parseDouble(s);
0082: ret = true;
0083: } catch (Exception de) {
0084: ret = false;
0085: }
0086: } else {
0087: ret = true;
0088: }
0089:
0090: return ret;
0091: }
0092:
0093: /**
0094: * Checks a String to see if it is empty ""
0095: *
0096: * @param objToCheck - object to check
0097: *
0098: * @return boolean true if it is empty
0099: */
0100: public static boolean isEmpty(Object objToCheck) {
0101: try {
0102: if (objToCheck.toString().trim().equals("")) {
0103: return true;
0104: } else {
0105: return false;
0106: }
0107: } catch (Exception e) {
0108: return true;
0109: }
0110: }
0111:
0112: /**
0113: * This method checks to see if the string passed into it contains any letters or digits. It returns a true or false value whether or not the string has any characters in it.
0114: *
0115: * @param s java.lang.String
0116: *
0117: * @return boolean
0118: */
0119: public static boolean isFilled(String s) {
0120: return ((s != null) && !s.trim().equals(""));
0121: }
0122:
0123: /**
0124: * This method checks to see if the string passed into it is an integer value. It returns true if the string parses to an integer.
0125: *
0126: * @param s java.lang.String
0127: *
0128: * @return boolean If the String is an integer value
0129: */
0130: public static boolean isInteger(String s) {
0131: boolean ret = false;
0132:
0133: if (!isNumeric(s)) {
0134: try {
0135: Integer.parseInt(s);
0136: ret = true;
0137: } catch (Exception ie) {
0138: ret = false;
0139: }
0140: } else {
0141: ret = true;
0142: }
0143:
0144: return ret;
0145: }
0146:
0147: /**
0148: * Checks an Object to see if it is null
0149: *
0150: * @param objToCheck - object to check
0151: *
0152: * @return boolean true if it is null
0153: */
0154: public static boolean isNull(Object objToCheck) {
0155: if (objToCheck == null) {
0156: return true;
0157: } else {
0158: return false;
0159: }
0160: }
0161:
0162: /**
0163: * This method checks to see if the string passed into it contains all numeric digits. It returns true if the string contains only digits.
0164: *
0165: * @param s java.lang.String
0166: *
0167: * @return boolean If the String is numeric
0168: */
0169: public static boolean isNumeric(String s) {
0170: boolean ret = false;
0171:
0172: if (s != null) {
0173: int length = s.length();
0174:
0175: for (int i = 0; i < length; i++) {
0176: if (!Character.isDigit(s.charAt(i))) {
0177: ret = false;
0178:
0179: break;
0180: } else {
0181: ret = true;
0182: }
0183: }
0184: }
0185:
0186: return ret;
0187: }
0188:
0189: /**
0190: * This method sets the width of the passed in HtmlDataTable to 100 percent
0191: *
0192: * @param dataTable - HtmlDataTable to be sized
0193: */
0194: public static void setTo100Percent(HtmlDataTable dataTable) {
0195: dataTable.setSizeOption(HtmlTable.SIZE_PERCENT);
0196: dataTable.setWidth(100);
0197: }
0198:
0199: /**
0200: * This method sets the width of the passed in HtmlDisplayBox to 100 percent
0201: *
0202: * @param dispBox - HtmlDisplayBox to be sized
0203: */
0204: public static void setTo100Percent(HtmlDisplayBox dispBox) {
0205: dispBox.setSizeOption(HtmlTable.SIZE_PERCENT);
0206: dispBox.setWidth(100);
0207: }
0208:
0209: /**
0210: * This method sets the width of the passed in HtmlDisplayBox to 100 percent
0211: *
0212: * @param table - HtmlTable to be sized
0213: */
0214: public static void setTo100Percent(HtmlTable table) {
0215: table.setSizeOption(HtmlTable.SIZE_PERCENT);
0216: table.setWidth(100);
0217: }
0218:
0219: /**
0220: * This method was created in VisualAge.
0221: *
0222: * @param filter java.lang.String
0223: * @param add java.lang.String
0224: *
0225: * @return java.lang.String
0226: */
0227: public static String addAndFilter(String filter, String add) {
0228: if (isNull(filter) || isEmpty(filter)) {
0229: return add;
0230: } else {
0231: return filter + " AND " + add;
0232: }
0233: }
0234:
0235: /**
0236: * This method was created in VisualAge.
0237: *
0238: * @param filter java.lang.String
0239: * @param add java.lang.String
0240: */
0241: public static void addAndFilter(StringBuffer filter, String add) {
0242: //sr 12 -21-2000 if (filter.toString().equals(""))
0243: if (isNull(filter.toString()) || isEmpty(filter.toString())) {
0244: filter.append(add);
0245: } else {
0246: filter.append(" AND ").append(add);
0247: }
0248: }
0249:
0250: /**
0251: * This method returns what you passed in as a Html Comment.
0252: *
0253: * @param commentStr - String that will be wrapped in an html comment
0254: *
0255: * @return String
0256: */
0257: public static String addHtmlComment(String commentStr) {
0258: return ("<!-- " + commentStr + " -->");
0259: }
0260:
0261: /**
0262: * This method was created in VisualAge.
0263: *
0264: * @param filter java.lang.String
0265: * @param add java.lang.String
0266: *
0267: * @return java.lang.String
0268: */
0269: public static String addOrFilter(String filter, String add) {
0270: // sr 12-21-2000 if (filter == null || filter.equals(""))
0271: if (isNull(filter) || isEmpty(filter)) {
0272: return add;
0273: } else {
0274: return filter + " OR " + add;
0275: }
0276: }
0277:
0278: /**
0279: * This method was created in VisualAge.
0280: *
0281: * @param filter java.lang.String
0282: * @param add java.lang.String
0283: */
0284: public static void addOrFilter(StringBuffer filter, String add) {
0285: //sr 12 -21-2000 if (filter.toString().equals(""))
0286: if (isNull(filter.toString()) || isEmpty(filter.toString())) {
0287: filter.append(add);
0288: } else {
0289: filter.append(" OR ").append(add);
0290: }
0291: }
0292:
0293: /**
0294: * This method was created in VisualAge.
0295: *
0296: * @param paramString java.lang.String
0297: * @param add java.lang.String
0298: * @param type int type of param
0299: */
0300: public static void addSPParameter(StringBuffer paramString,
0301: String add, int type) {
0302: String commaChar = "";
0303:
0304: if (!paramString.toString().equals("")) {
0305: commaChar = ",";
0306: }
0307:
0308: switch (type) {
0309: case 0:
0310: paramString.append(commaChar).append("'").append(add)
0311: .append("'");
0312:
0313: break;
0314:
0315: default:
0316: paramString.append(commaChar).append(add);
0317:
0318: break;
0319: }
0320: }
0321:
0322: /**
0323: * This method was created in VisualAge.
0324: *
0325: * @param clause java.lang.String
0326: * @param add java.lang.String
0327: * @param type int type of param
0328: *
0329: * @return java.lang.String
0330: */
0331: public static String addToINClause(String clause, String add,
0332: int type) {
0333: String commaChar = "";
0334:
0335: if (!isEmpty(clause)) {
0336: commaChar = ",";
0337: }
0338:
0339: switch (type) {
0340: case DataStore.DATATYPE_STRING:
0341: return clause + commaChar + "'" + add + "'";
0342:
0343: default:
0344: return clause + commaChar + add;
0345: }
0346: }
0347:
0348: /**
0349: * This method will will automatically set a property value on the specified component. This can be used for example to make a component invisible or visible depending on the value in the datastore for a particular row: ex: addPropertyExpression(comp,"visible","bucket==1") will call the setVisible method on the component comp passing the results of the expression.
0350: *
0351: * @param comp The component to set the property for
0352: * @param propertyName The name of the property to set. The component must have a corresponding setProperty method or this method will throw a NoSuchMethodException
0353: * @param value - The value being passed to the method
0354: *
0355: * @exception NoSuchMethodException The exception description.
0356: */
0357: public static void executeMethod(Object comp, String propertyName,
0358: Object value) throws NoSuchMethodException {
0359: Class c = comp.getClass();
0360: Method m[] = c.getMethods();
0361: Method exe = null;
0362: String name = "set" + propertyName;
0363: Class parms[] = null;
0364:
0365: for (int i = 0; i < m.length; i++) {
0366: if (name.equalsIgnoreCase(m[i].getName())) {
0367: parms = m[i].getParameterTypes();
0368:
0369: if (parms.length == 1) {
0370: exe = m[i];
0371:
0372: break;
0373: }
0374: }
0375: }
0376:
0377: if (exe == null) {
0378: throw new NoSuchMethodException(
0379: "Couldn't find a set method for property:"
0380: + propertyName);
0381: }
0382:
0383: executeReflectedMethod(comp, exe, value);
0384: }
0385:
0386: /**
0387: * This method is used to execute set methods indirectly.
0388: *
0389: * @param comp DOCUMENT ME!
0390: * @param meth DOCUMENT ME!
0391: * @param value DOCUMENT ME!
0392: */
0393: public static void executeReflectedMethod(Object comp, Method meth,
0394: Object value) {
0395: try {
0396: Object res[] = null;
0397: Class parms[] = null;
0398: String name = null;
0399: Number n[] = null;
0400:
0401: res = new Object[1];
0402:
0403: res[0] = value;
0404:
0405: parms = meth.getParameterTypes();
0406: name = parms[0].getName().toUpperCase();
0407:
0408: if (res[0] != null) {
0409: if (name.startsWith("BOOLEAN")
0410: && res[0] instanceof Boolean) {
0411: meth.invoke(comp, res);
0412: } else if (name.endsWith("STRING")
0413: && res[0] instanceof String) {
0414: meth.invoke(comp, res);
0415: } else if (res[0] instanceof Number) {
0416: n = new Number[1];
0417:
0418: if (name.startsWith("INT")) {
0419: n[0] = new Integer(((Number) res[0]).intValue());
0420: } else if (name.startsWith("LONG")) {
0421: n[0] = new Long(((Number) res[0]).longValue());
0422: } else if (name.startsWith("FLOAT")) {
0423: n[0] = new Float(((Number) res[0]).floatValue());
0424: } else if (name.startsWith("DOUBLE")) {
0425: n[0] = new Double(((Number) res[0])
0426: .doubleValue());
0427: } else if (name.startsWith("BYTE")) {
0428: n[0] = new Byte(((Number) res[0]).byteValue());
0429: } else if (name.startsWith("SHORT")) {
0430: n[0] = new Short(((Number) res[0]).shortValue());
0431: } else {
0432: return;
0433: }
0434:
0435: meth.invoke(comp, n);
0436: }
0437: } else {
0438: if (name.startsWith("BOOLEAN")) {
0439: Boolean b = new Boolean(false);
0440: res[0] = b;
0441: meth.invoke(comp, res);
0442: } else if (name.endsWith("STRING")) {
0443: String s = null;
0444: res[0] = s;
0445: meth.invoke(comp, res);
0446: } else {
0447: n = new Number[1];
0448:
0449: if (name.startsWith("INT")) {
0450: n[0] = new Integer((int) 0);
0451: } else if (name.startsWith("LONG")) {
0452: n[0] = new Long((long) 0);
0453: } else if (name.startsWith("FLOAT")) {
0454: n[0] = new Float((float) 0);
0455: } else if (name.startsWith("DOUBLE")) {
0456: n[0] = new Double((double) 0);
0457: } else if (name.startsWith("BYTE")) {
0458: n[0] = new Byte((byte) 0);
0459: } else if (name.startsWith("SHORT")) {
0460: n[0] = new Short((short) 0);
0461: } else {
0462: return;
0463: }
0464:
0465: meth.invoke(comp, n);
0466: }
0467: }
0468: } catch (Exception e) {
0469: MessageLog.writeErrorMessage("Execute Property Method", e,
0470: null);
0471: }
0472: }
0473:
0474: /**
0475: * This method returns a HTML script that opens the print dialog box of the browser.
0476: *
0477: * @param submitBtn - Button that will get the script added to it
0478: * @param p - Page
0479: *
0480: * @return HtmlScript
0481: */
0482: public HtmlScript getPrintScript(HtmlSubmitImage submitBtn,
0483: HtmlPage p) {
0484: HtmlScript script = new HtmlScript("", "JavaScript1.1", p);
0485:
0486: String sScript = " function PrintScript() { \n";
0487: sScript += " if (!(window.print)) { \n";
0488: sScript += " alert( \"Please select the Print option from File Menu\"); \n";
0489: sScript += " } \n";
0490: sScript += " else{ \n";
0491: sScript += " window.print(); \n";
0492: sScript += " } \n";
0493: sScript += "} \n";
0494:
0495: script.setScript(sScript);
0496:
0497: if (submitBtn != null) {
0498: submitBtn.setOnClick("PrintScript()");
0499: }
0500:
0501: return script;
0502: }
0503:
0504: /**
0505: * Check an int and returns if it resolves to true boolean value. numbers greater then 0 are treated as true
0506: *
0507: * @param intToCheck - Int to check
0508: *
0509: * @return boolean
0510: */
0511: public static boolean isTrue(int intToCheck) {
0512: boolean ret = false;
0513:
0514: if (intToCheck <= 0) {
0515: ret = false;
0516: } else {
0517: ret = true;
0518: }
0519:
0520: return ret;
0521:
0522: }
0523:
0524: /**
0525: * Check a string and returns if it resolves to true boolean value. numbers greater then 0 are treated as true
0526: *
0527: * @param strToCheck - String to check
0528: *
0529: * @return boolean
0530: */
0531: public static boolean isTrue(String strToCheck) {
0532: if (strToCheck == null) {
0533: return false;
0534: }
0535:
0536: strToCheck = strToCheck.toLowerCase();
0537:
0538: if (Util.isNumeric(strToCheck)) {
0539: /**
0540: * numbers greater then 0 are treated as true
0541: */
0542: if (Integer.parseInt(strToCheck) > 0) {
0543: return true;
0544: }
0545: } else if (strToCheck.equals("t") || strToCheck.equals("true")
0546: || strToCheck.equals("y") || strToCheck.equals("yes")) {
0547: return true;
0548: }
0549:
0550: return false;
0551: }
0552:
0553: /**
0554: * This method finds the nth occurrence of a string within another string and return the location within the source string
0555: *
0556: * @param searchStr is the string to search for.
0557: * @param source is the string to be searched.
0558: * @param numOfOcurrence is the number of occurrence we are looking for.
0559: *
0560: * @return int index of occurence
0561: */
0562: public static int indexOfOccurence(String searchStr, String source,
0563: int numOfOcurrence) {
0564: int index = -1;
0565:
0566: // Find the nth occurrence of a string within another string
0567: // and return the location within the source string
0568: // The current position within the soruce string
0569: int currPos = 0;
0570:
0571: // The current number of matches found
0572: int mathesFound = 0;
0573:
0574: if (numOfOcurrence == 0) {
0575: return index; // Return -1 if the number of occurrences is 0
0576: }
0577:
0578: if (source.indexOf(searchStr) == -1) {
0579: return index; // Return -1 if either string is Null
0580: }
0581:
0582: if (stringCount(source, searchStr) < numOfOcurrence) {
0583: return index; // Return -1 if there is not the specified number of occurences of the search string in the source string
0584: }
0585:
0586: while (mathesFound < numOfOcurrence) {
0587: mathesFound = mathesFound + 1;
0588: currPos = source.indexOf(searchStr, currPos)
0589: + searchStr.length();
0590: }
0591:
0592: index = currPos - searchStr.length();
0593:
0594: return index;
0595: }
0596:
0597: /**
0598: * Returns true if class2 is a subclass of class1
0599: *
0600: * @param class1
0601: * @param class2
0602: *
0603: * @return
0604: */
0605: public static boolean instanceOf(Class class1, Class class2) {
0606: if (class1.isPrimitive() || class2.isPrimitive()) {
0607: return (class1 == class2);
0608: }
0609:
0610: while (class1 != Object.class) {
0611: if (class1 == class2) {
0612: return true;
0613: }
0614:
0615: class1 = class1.getSuperclass();
0616:
0617: if (class1 == null) {
0618: return false;
0619: }
0620: }
0621:
0622: return false;
0623: }
0624:
0625: /**
0626: * Maps a string to a datastore datatype constant
0627: *
0628: * @param val
0629: *
0630: * @return int value that is DataStore.DATATYPE_
0631: */
0632: public static int javaClassToDataStoreType(String val) {
0633: // String
0634: if (val.indexOf("String") > -1) {
0635: return DataStore.DATATYPE_STRING;
0636: }
0637:
0638: // Integer
0639: if (val.indexOf("Integer") > -1) {
0640: return DataStore.DATATYPE_INT;
0641: }
0642:
0643: // Date
0644: if (val.indexOf("Date") > -1) {
0645: return DataStore.DATATYPE_DATE;
0646: }
0647:
0648: // DateTime
0649: if (val.indexOf("DateTime") > -1) {
0650: return DataStore.DATATYPE_DATETIME;
0651: }
0652:
0653: // Double
0654: if (val.indexOf("Double") > -1) {
0655: return DataStore.DATATYPE_DOUBLE;
0656: }
0657:
0658: // Time
0659: if (val.indexOf("Time") > -1) {
0660: return DataStore.DATATYPE_TIME;
0661: }
0662:
0663: // Short
0664: if (val.indexOf("Short") > -1) {
0665: return DataStore.DATATYPE_SHORT;
0666: }
0667:
0668: // Long
0669: if (val.indexOf("Long") > -1) {
0670: return DataStore.DATATYPE_LONG;
0671: }
0672:
0673: // Float
0674: if (val.indexOf("Float") > -1) {
0675: return DataStore.DATATYPE_FLOAT;
0676: }
0677:
0678: // ByteArray
0679: if (val.indexOf("ByteArray") > -1) {
0680: return DataStore.DATATYPE_BYTEARRAY;
0681: }
0682:
0683: return -1;
0684: }
0685:
0686: /**
0687: * This method checks a column to see if it has been filled. If it has not been filled it with a safe value.
0688: *
0689: * @param ds DataStore the datastore to use during checking
0690: * @param row int
0691: * @param colName String
0692: *
0693: * @throws Exception - if column is not found
0694: */
0695: public static void makeSureNotNull(DataStore ds, int row,
0696: String colName) throws Exception {
0697: makeSureNotNull(ds, row, colName, null);
0698: }
0699:
0700: /**
0701: * This method checks a column to see if it has been filled. If it has not been filled it with a safe value.
0702: *
0703: * @param ds DataStore the datastore to use during checking
0704: * @param row - row to check
0705: * @param colName - column to check
0706: * @param defaultVal - Object You can specify what your defaultvalue should be.
0707: *
0708: * @throws Exception - if column is not found
0709: */
0710: public static void makeSureNotNull(DataStore ds, int row,
0711: String colName, Object defaultVal) throws Exception {
0712: try {
0713: Object oTest = ds.getAny(row, colName);
0714: int colType = ds.getColumnDataType(colName);
0715:
0716: if (oTest == null) {
0717: switch (colType) {
0718: case DataStore.DATATYPE_BYTEARRAY:
0719:
0720: if (defaultVal == null) {
0721: ds.setByteArray(row, colName, new byte[1]);
0722: } else {
0723: if (defaultVal instanceof byte[]) {
0724: ds.setByteArray(row, colName,
0725: (byte[]) defaultVal);
0726: } else {
0727: throw new Exception(
0728: "Expecting Byte array,You passed the wrong type aurgument for this coulmn type.");
0729: }
0730: }
0731:
0732: break;
0733:
0734: case DataStore.DATATYPE_SHORT:
0735:
0736: if (defaultVal == null) {
0737: ds.setShort(row, colName, (short) 0);
0738: } else {
0739: if (defaultVal instanceof Short) {
0740: ds.setShort(row, colName,
0741: ((Short) defaultVal).shortValue());
0742: } else {
0743: throw new Exception(
0744: "Expecting short value,You passed the wrong type aurgument for this coulmn type.");
0745: }
0746: }
0747:
0748: break;
0749:
0750: case DataStore.DATATYPE_INT:
0751:
0752: if (defaultVal == null) {
0753: ds.setInt(row, colName, 0);
0754: } else {
0755: if (defaultVal instanceof Integer) {
0756: ds.setInt(row, colName,
0757: ((Integer) defaultVal).intValue());
0758: } else {
0759: throw new Exception(
0760: "Expecting int value,You passed the wrong type aurgument for this coulmn type.");
0761: }
0762: }
0763:
0764: break;
0765:
0766: case DataStore.DATATYPE_LONG:
0767:
0768: if (defaultVal == null) {
0769: ds.setLong(row, colName, 0);
0770: } else {
0771: if (defaultVal instanceof Long) {
0772: ds.setLong(row, colName,
0773: ((Long) defaultVal).longValue());
0774: } else {
0775: throw new Exception(
0776: "Expecting long value,You passed the wrong type aurgument for this coulmn type.");
0777: }
0778: }
0779:
0780: break;
0781:
0782: case DataStore.DATATYPE_FLOAT:
0783:
0784: if (defaultVal == null) {
0785: ds.setFloat(row, colName, 0.0f);
0786: } else {
0787: if (defaultVal instanceof Float) {
0788: ds.setFloat(row, colName,
0789: ((Float) defaultVal).floatValue());
0790: } else {
0791: throw new Exception(
0792: "Expecting float value,You passed the wrong type aurgument for this coulmn type.");
0793: }
0794: }
0795:
0796: break;
0797:
0798: case DataStore.DATATYPE_DOUBLE:
0799:
0800: if (defaultVal == null) {
0801: ds.setDouble(row, colName, 0.0);
0802: } else {
0803: if (defaultVal instanceof Double) {
0804: ds
0805: .setDouble(row, colName,
0806: ((Double) defaultVal)
0807: .doubleValue());
0808: } else {
0809: throw new Exception(
0810: "Expecting double value,You passed the wrong type aurgument for this coulmn type.");
0811: }
0812: }
0813:
0814: break;
0815:
0816: case DataStore.DATATYPE_STRING:
0817:
0818: if (defaultVal == null) {
0819: ds.setString(row, colName, " ");
0820: } else {
0821: if (defaultVal instanceof String) {
0822: ds.setString(row, colName,
0823: ((String) defaultVal).toString());
0824: } else {
0825: throw new Exception(
0826: "Expecting String value,You passed the wrong type aurgument for this coulmn type.");
0827: }
0828: }
0829:
0830: break;
0831:
0832: case DataStore.DATATYPE_DATE:
0833:
0834: if (defaultVal == null) {
0835: ds.setDate(row, colName, Util.getDateObject(0,
0836: 0, 0, 0, 0));
0837: } else {
0838: if (defaultVal instanceof java.sql.Date) {
0839: ds.setDate(row, colName,
0840: (java.sql.Date) defaultVal);
0841: } else {
0842: throw new Exception(
0843: "Expecting java.sql.Date value,You passed the wrong type aurgument for this coulmn type.");
0844: }
0845: }
0846:
0847: break;
0848:
0849: case DataStore.DATATYPE_DATETIME:
0850:
0851: if (defaultVal == null) {
0852: ds.setDateTime(row, colName, new Timestamp(0));
0853: } else {
0854: if (defaultVal instanceof java.sql.Timestamp) {
0855: ds.setDateTime(row, colName,
0856: (java.sql.Timestamp) defaultVal);
0857: } else {
0858: throw new Exception(
0859: "Expecting java.sql.Timestamp value,You passed the wrong type aurgument for this coulmn type.");
0860: }
0861: }
0862:
0863: break;
0864:
0865: case DataStore.DATATYPE_TIME:
0866:
0867: if (defaultVal == null) {
0868: ds.setTime(row, colName, new Time(0));
0869: } else {
0870: if (defaultVal instanceof java.sql.Time) {
0871: ds.setTime(row, colName,
0872: (java.sql.Time) defaultVal);
0873: } else {
0874: throw new Exception(
0875: "Expecting ava.sql.Time value,You passed the wrong type aurgument for this coulmn type.");
0876: }
0877: }
0878:
0879: break;
0880: }
0881: }
0882: } catch (Exception e) {
0883: MessageLog.writeErrorMessage("makeSureNotNull", e, null);
0884: throw e;
0885: }
0886: }
0887:
0888: /**
0889: * This method checks a column to see if it has been filled. If it has not been filled it with a safe value.
0890: *
0891: * @param ds DataStore the datastore to use during checking
0892: * @param colName - column to check
0893: *
0894: * @throws Exception - if column is not found
0895: */
0896: public static void makeSureNotNull(DataStore ds, String colName)
0897: throws Exception {
0898: makeSureNotNull(ds, 0, colName);
0899: }
0900:
0901: /**
0902: * This function is used to pad a string to the specified length with a specific character and return this created string.
0903: * If passed String is greater than iPadLength than the string is chopped to that length.
0904: * @param sPassed String - the string to be padded.
0905: * @param iPadLength int - the length of the resulting string.
0906: * @param cPadChar char - the character to pad the string with.
0907: * @return String - the padded string of the operation.
0908: */
0909: public final static String padString(String sPassed,
0910: int iPadLength, char cPadChar) {
0911: StringBuffer sbReturn = new StringBuffer(sPassed);
0912: if (sbReturn.length() < iPadLength) {
0913: int iPadding = iPadLength - sbReturn.length();
0914: for (int i = 0; i < iPadding; i++)
0915: sbReturn.append(cPadChar);
0916: }
0917: if (sbReturn.length() > iPadLength)
0918: sbReturn.setLength(iPadLength);
0919: return sbReturn.toString();
0920: }
0921:
0922: /**
0923: * This function is used to pad a string in the front to the specified length with a specific character and return this created string.
0924: * If passed String is greater than iPadLength than the string is chopped to that length.
0925: * @param sPassed String - the string to be padded.
0926: * @param iPadLength int - the length of the resulting string.
0927: * @param cPadChar char - the character to pad the string with.
0928: * @return String - the padded string of the operation.
0929: */
0930: public final static String padStringInFront(String sPassed,
0931: int iPadLength, char cPadChar) {
0932: StringBuffer sbReturn = new StringBuffer(sPassed);
0933: if (sbReturn.length() < iPadLength) {
0934: int iPadding = iPadLength - sbReturn.length();
0935: for (int i = 0; i < iPadding; i++)
0936: sbReturn.insert(0, cPadChar);
0937: }
0938: if (sbReturn.length() > iPadLength)
0939: sbReturn.setLength(iPadLength);
0940: return sbReturn.toString();
0941: }
0942:
0943: /**
0944: * This method replaces strings within another string with a third specified string Usage: replaceString(StringBuffer soucre, String searchStr, String replaceStr)
0945: * replaces all occurences
0946: * @param source is the string to be searched.
0947: * @param searchStr is the string to search for.
0948: * @param replaceStr is the string that replaces searchStr in soucre. If omitted, replacement is the empty string.
0949: *
0950: * @return DOCUMENT ME!
0951: */
0952: public static String replaceString(String source, String searchStr,
0953: String replaceStr) {
0954: return replaceString(source, searchStr, replaceStr, -1, -1);
0955: }
0956:
0957: /**
0958: * This method replaces strings within another string with a third specified string Usage: replaceString(StringBuffer soucre, String searchStr, String replaceStr, int startOcurrence, int numOfOccurences)
0959: *
0960: * @param source is the string to be searched.
0961: * @param searchStr is the string to search for.
0962: * @param replaceStr is the string that replaces searchStr in soucre. If omitted, replacement is the empty string.
0963: * @param startOcurrence is the first occurrence of searchStr that is replaced. If omitted, the first occurrence is used.
0964: * @param numOfOccurences is the number of occurrences of searchStr that are replaced. If omitted, all occurrences are replaced.
0965: *
0966: * @return DOCUMENT ME!
0967: */
0968: public static String replaceString(String source, String searchStr,
0969: String replaceStr, int startOcurrence, int numOfOccurences) {
0970: if ((source == null) || (searchStr == null)
0971: || (replaceStr == null)) {
0972: return null;
0973: }
0974:
0975: // If the search string does not appear in the source string then return the original source string
0976: int totalOccurences = Util.stringCount(source.toString(),
0977: searchStr);
0978:
0979: if (totalOccurences == 0) {
0980: return source;
0981: }
0982:
0983: if (startOcurrence < 1) {
0984: startOcurrence = 1;
0985: }
0986:
0987: // If lngStartOccurrence is greater than the total number of occurrences then
0988: // start with the last occurrence by default
0989: if (startOcurrence > totalOccurences) {
0990: startOcurrence = totalOccurences;
0991: }
0992:
0993: // If numOfOccurences is either omitted, less than one, or greater than
0994: // the total number of occurrences then replace all remaining occurrences by default
0995: if ((numOfOccurences < 1)
0996: || (totalOccurences < numOfOccurences)
0997: || ((numOfOccurences + startOcurrence) > totalOccurences)) {
0998: numOfOccurences = totalOccurences - startOcurrence + 1;
0999: }
1000:
1001: // Step through all specified occurrences of the search string within the soruce
1002: // string, replacing the search string with the replacement string for each
1003: // required occurrence
1004: int currPos = indexOfOccurence(searchStr, source.toString(),
1005: startOcurrence);
1006: StringBuffer work = new StringBuffer(source.substring(0,
1007: currPos));
1008: int currOcurrence = 0;
1009: int nextPos = 0;
1010:
1011: for (currOcurrence = startOcurrence; currOcurrence < ((startOcurrence + numOfOccurences) - 1); currOcurrence++) {
1012: nextPos = source.indexOf(searchStr, currPos + 1);
1013: work.append(replaceStr);
1014:
1015: String temp = source.substring(
1016: currPos + searchStr.length(), nextPos);
1017: work.append(temp);
1018:
1019: // old currPos = nextPos + searchStr.length();
1020: currPos = nextPos;
1021: }
1022:
1023: work.append(replaceStr);
1024: work.append(source.substring(currPos + searchStr.length()));
1025:
1026: return work.toString();
1027:
1028: //// Finally, append the remainder of the source string to the result
1029: //StrTran = StrTran & Mid(strSourceString, lngCurrentPosition, Len(strSourceString) - lngCurrentPosition + 1) java.util.Vector indexVec = new java.util.Vector();
1030: //int searchStrLen = searchStr.length();
1031: //int searchStrPos = -1;
1032: //String work = sb.toString();
1033: //for (int i = 0; i < source.length(); i++)
1034: //{
1035: //searchStrPos = work.indexOf(searchStr, i);
1036: //if (searchStrPos > -1)
1037: //{
1038: //i = searchStrPos;
1039: //indexVec.add(new Integer(searchStrPos));
1040: //} else
1041: //{
1042: //break;
1043: //}
1044: //}
1045: //for (int i = indexVec.size() - 1; i >= 0; i--)
1046: //{
1047: //int startPos = ((Integer) indexVec.get(i)).intValue();
1048: //sb.replace(startPos, startPos + searchStrLen, serverUrl);
1049: //}
1050: }
1051:
1052: /**
1053: * This method Counts the number of occurences of one string within another
1054: *
1055: * @param source - String to be searched in
1056: * @param searchStr - String that is tring to be found
1057: *
1058: * @return number of occurences
1059: */
1060: public static int stringCount(String source, String searchStr) {
1061: int count = 0;
1062: int searchStrPos = -1;
1063:
1064: // check to make sure all strings involved are not null.
1065: if ((source == null) || (searchStr == null)) {
1066: return count;
1067: }
1068:
1069: for (int i = 0; i < source.length(); i++) {
1070: searchStrPos = source.indexOf(searchStr, i);
1071:
1072: if (searchStrPos > -1) {
1073: count++;
1074: i = searchStrPos;
1075: } else {
1076: break;
1077: }
1078: }
1079:
1080: return count;
1081: }
1082:
1083: /**
1084: * Attempts to convert a string into its boolean equivalent; otherwise returns the true
1085: *
1086: * @param val - String to be converted
1087: *
1088: * @return boolean
1089: */
1090: public static boolean stringToBoolean(String val) {
1091: return stringToBoolean(val, true);
1092: }
1093:
1094: /**
1095: * Attempts to convert a string into its boolean equivalent; otherwise returns the default
1096: *
1097: * @param val java.lang.String
1098: * @param def boolean
1099: *
1100: * @return boolean
1101: */
1102: public static boolean stringToBoolean(String val, boolean def) {
1103: if (val == null) {
1104: return def;
1105: }
1106:
1107: String test = val.toUpperCase();
1108:
1109: if (test.equals("1") || test.equals("T") || test.equals("Y")
1110: || test.equals("TRUE") || test.equals("YES")) {
1111: return true;
1112: } else if (test.equals("0") || test.equals("F")
1113: || test.equals("N") || test.equals("FALSE")
1114: || test.equals("NO")) {
1115: return false;
1116: } else {
1117: return def;
1118: }
1119: }
1120:
1121: /**
1122: * This method will return the Color-object equivalent of a string
1123: *
1124: * @param s - colr passed as a string.
1125: *
1126: * @return Color
1127: */
1128: public static Color stringToColor(String s) {
1129: if (s == null) {
1130: return null;
1131: }
1132:
1133: if (s.startsWith("#")) {
1134: return Color.decode(s);
1135: } else {
1136: s = s.toUpperCase();
1137:
1138: if (s.equals("WHITE")) {
1139: return Color.white;
1140: } else if (s.equals("LIGHTGRAY")) {
1141: return Color.lightGray;
1142: } else if (s.equals("GRAY")) {
1143: return Color.gray;
1144: } else if (s.equals("DARKGRAY")) {
1145: return Color.darkGray;
1146: } else if (s.equals("BLACK")) {
1147: return Color.black;
1148: } else if (s.equals("RED")) {
1149: return Color.red;
1150: } else if (s.equals("PINK")) {
1151: return Color.pink;
1152: } else if (s.equals("ORANGE")) {
1153: return Color.orange;
1154: } else if (s.equals("YELLOW")) {
1155: return Color.yellow;
1156: } else if (s.equals("YELLOW")) {
1157: return Color.yellow;
1158: } else if (s.equals("MAGENTA")) {
1159: return Color.magenta;
1160: } else if (s.equals("CYAN")) {
1161: return Color.cyan;
1162: } else if (s.equals("BLUE")) {
1163: return Color.blue;
1164: } else {
1165: return null;
1166: }
1167: }
1168: }
1169:
1170: /**
1171: * Converts a string to an int or returns -1 if it can't
1172: *
1173: * @param val - value to convert
1174: *
1175: * @return int
1176: */
1177: public static int stringToInt(String val) {
1178: if (val == null) {
1179: return -1;
1180: }
1181:
1182: try {
1183: return Integer.parseInt(val.trim());
1184: } catch (Exception e) {
1185: return -1;
1186: }
1187: }
1188:
1189: /**
1190: * This method returns a new string containing only letters and numeric digits in the original string.
1191: *
1192: * @param s java.lang.String string to be stripped of all characters other than letters or digits
1193: *
1194: * @return java.lang.String the new string containing only letters or digits
1195: */
1196: public static String stripChars(String s) {
1197: char sourceArray[] = s.toCharArray();
1198: int length = sourceArray.length;
1199: char destArray[] = new char[length];
1200:
1201: int j = 0;
1202:
1203: for (int i = 0; i < length; i++) {
1204: if (Character.isLetterOrDigit(sourceArray[i])) {
1205: destArray[j++] = sourceArray[i];
1206: }
1207: }
1208:
1209: return (j <= 0) ? null : (new String(destArray)).trim();
1210: }
1211:
1212: /**
1213: * This method returns a new string with only the allowed characters and no disallowed characters.
1214: *
1215: * @param source java.lang.String source string
1216: * @param allowedChars a String containing the characters allowed to be in the resulting string.
1217: * @param disallowedChars a String containing the characters disallowed to be in the resulting string
1218: *
1219: * @return the new formatted string containing the allowed characters and not containing the disallowed characters.
1220: */
1221: public static String stripChars(String source, String allowedChars,
1222: String disallowedChars) {
1223: if (source == null) {
1224: return null;
1225: }
1226:
1227: char sourceArray[] = source.toCharArray();
1228: int length = sourceArray.length;
1229: char destArray[] = new char[length];
1230:
1231: int j = 0;
1232:
1233: for (int i = 0; i < length; i++) {
1234: if (((allowedChars != null) && (allowedChars
1235: .indexOf(sourceArray[i]) >= 0))
1236: || ((disallowedChars != null) && (disallowedChars
1237: .indexOf(sourceArray[i]) < 0))) {
1238: destArray[j++] = sourceArray[i];
1239: }
1240: }
1241:
1242: return (j <= 0) ? null : (new String(destArray)).trim();
1243: }
1244:
1245: /**
1246: * This method returns a new string containing only the root string with no .jsp.
1247: *
1248: * @param s java.lang.String string to be stripped
1249: *
1250: * @return java.lang.String the new string containing only root string.
1251: */
1252: public static String stripDotJsp(String s) {
1253: if (s == null) {
1254: return null;
1255: }
1256:
1257: String work = s;
1258:
1259: int dotJspPos = work.indexOf(".jsp");
1260:
1261: if (dotJspPos > -1) {
1262: s = work.substring(0, dotJspPos);
1263: }
1264:
1265: return s;
1266: }
1267:
1268: /**
1269: * Removes the html from an html string and leaves only the text
1270: *
1271: * @param stripString - String to strip html from
1272: *
1273: * @return - stripped String
1274: */
1275: public static String stripHtmlFromText(String stripString) {
1276: String temp = "";
1277: if (Util.isFilled(stripString)) {
1278:
1279: boolean whileLoop = true;
1280:
1281: for (int i = 0; i < stripString.length(); i++) {
1282: if (stripString.charAt(i) != '<') {
1283: temp = temp + stripString.charAt(i);
1284: } else {
1285: whileLoop = true;
1286:
1287: while (whileLoop) {
1288: if ((i < stripString.length())
1289: && (stripString.charAt(i) != '>')) {
1290: i++;
1291: } else {
1292: whileLoop = false;
1293: }
1294: }
1295: }
1296: }
1297:
1298: }
1299:
1300: return temp;
1301: }
1302:
1303: /**
1304: * This method returns a string containing only digits and the decimal point.
1305: *
1306: * @param sField java.lang.String
1307: *
1308: * @return java.lang.String a string containing only digits and the decimal point
1309: */
1310: public static String stripSpecialChars(String sField) {
1311: char acOrigField[] = sField.toCharArray();
1312: int length = acOrigField.length;
1313: char acDestField[] = new char[length];
1314: int j = 0;
1315:
1316: for (int i = 0; i < length; i++) {
1317: if (Character.isLetterOrDigit(acOrigField[i])) {
1318: acDestField[j++] = acOrigField[i];
1319: } else {
1320: if ((acOrigField[i] == ' ') || (acOrigField[i] == '@')
1321: || (acOrigField[i] == '#')
1322: || (acOrigField[i] == '$')
1323: || (acOrigField[i] == '%')
1324: || (acOrigField[i] == '&')
1325: || (acOrigField[i] == '*')
1326: || (acOrigField[i] == '(')
1327: || (acOrigField[i] == ')')
1328: || (acOrigField[i] == '[')
1329: || (acOrigField[i] == ']')
1330: || (acOrigField[i] == '.')
1331: || (acOrigField[i] == ',')
1332: || (acOrigField[i] == ';')
1333: || (acOrigField[i] == ':')
1334: || (acOrigField[i] == '~')
1335: || (acOrigField[i] == '`')
1336: || (acOrigField[i] == '!')
1337: || (acOrigField[i] == '"')) {
1338: acDestField[j++] = acOrigField[i];
1339: }
1340: }
1341: }
1342:
1343: return (j <= 0) ? null : (new String(acDestField)).trim();
1344: }
1345:
1346: /**
1347: * Convert a java.sql.Timestamp to a valid java.sql.Date
1348: *
1349: * @param timeStampToConvert - Timestamp to convert
1350: *
1351: * @return valid java.sql.Date if a null is passed in a null is back out
1352: */
1353: public static java.sql.Date timeToDate(
1354: java.sql.Timestamp timeStampToConvert) {
1355: java.sql.Date sqlDate = null;
1356: if (!Util.isNull(timeStampToConvert)) {
1357: sqlDate = new java.sql.Date(timeStampToConvert.getTime());
1358: }
1359:
1360: return sqlDate;
1361: }
1362:
1363: /**
1364: * This method will remove illegal characters for strings so they can be placed in a url link.
1365: *
1366: * @param s - string to work on
1367: *
1368: * @return - encoded String
1369: */
1370: public static String urlEncode(String s) {
1371: return urlEncode(s, false);
1372: }
1373:
1374: /**
1375: * This method will remove illegal characters for strings so they can be placed in a url link.
1376: *
1377: * @param s - string to work on
1378: * @param encodeFull - whether to encode all characters
1379: *
1380: * @return - encoded String
1381: */
1382: public static String urlEncode(String s, boolean encodeFull) {
1383: if (s == null) {
1384: return null;
1385: }
1386:
1387: StringBuffer b = new StringBuffer();
1388:
1389: for (int i = 0; i < s.length(); i++) {
1390: char c = s.charAt(i);
1391: int ci = (int) c;
1392:
1393: if (c == ' ') {
1394: b.append("%20");
1395: } else if (c == '&') {
1396: b.append("%26");
1397: } else if (c == '?') {
1398: b.append("%3F");
1399: } else if (c == '#') {
1400: b.append("%35");
1401: } else if (c == '/') {
1402: if (encodeFull) {
1403: b.append("%2F");
1404: } else {
1405: b.append('/');
1406: }
1407: } else if (c == '.') {
1408: if (encodeFull) {
1409: b.append("%2E");
1410: } else {
1411: b.append('.');
1412: }
1413: } else if (c == '-') {
1414: if (encodeFull) {
1415: b.append("%2D");
1416: } else {
1417: b.append('-');
1418: }
1419: } else if (c == '_') {
1420: if (encodeFull) {
1421: b.append("%5F");
1422: } else {
1423: b.append('_');
1424: }
1425: } else if (c == '+') {
1426: b.append("%2B");
1427: } else if (c == '"') {
1428: b.append("%22");
1429: } else if (((ci >= 48) && (ci <= 57))
1430: || ((ci >= 65) && (ci <= 90))
1431: || ((ci >= 97) && (ci <= 122))) {
1432: b.append(c);
1433: } else {
1434: b.append("%");
1435: if (ci <= 15)
1436: b.append("0");
1437: b.append(Integer.toHexString(ci).toUpperCase());
1438: }
1439: }
1440:
1441: return b.toString();
1442: }
1443:
1444: /**
1445: * Returns the number of whole days that have elapsed from a given day to
1446: * today. If the given day is today, it will return zero. If the day
1447: * is yesterday, it will return 1, etc. If the given day is in the future,
1448: * the reult will be a negative number.
1449: *
1450: * @param comDate - the date to compare to
1451: *
1452: * @return int
1453: */
1454: public static int getDaysElapsed(java.sql.Timestamp compDate) {
1455: long currentMillis;
1456: long compareMillis;
1457:
1458: // Always compare to the last millsecond of today. This guarantees
1459: // that the result will be a whole day.
1460: GregorianCalendar current = new GregorianCalendar();
1461: current.setTime(new Date(System.currentTimeMillis()));
1462: current.set(GregorianCalendar.HOUR_OF_DAY, 23);
1463: current.set(GregorianCalendar.MINUTE, 59);
1464: current.set(GregorianCalendar.SECOND, 59);
1465: current.set(GregorianCalendar.MILLISECOND, 999);
1466: currentMillis = current.getTime().getTime();
1467:
1468: GregorianCalendar compareDate = new GregorianCalendar();
1469: compareDate.setTime(new Date(compDate.getTime()));
1470: compareMillis = compareDate.getTime().getTime();
1471:
1472: return (int) ((currentMillis - compareMillis) / NUM_MILLIS_IN_DAY);
1473:
1474: }
1475:
1476: /**
1477: * Splits a String into an array of Strings based on a delimiter
1478: * @param st
1479: * @return
1480: */
1481: public static String[] split(String st, String delimiter) {
1482: if (st == null)
1483: return new String[0];
1484: ArrayList l = new ArrayList();
1485: StringTokenizer tok = new StringTokenizer(st, delimiter);
1486: while (tok.hasMoreTokens())
1487: l.add(tok.nextToken());
1488: String ret[] = new String[l.size()];
1489: l.toArray(ret);
1490: return ret;
1491: }
1492:
1493: /**
1494: * Returns the cause for the exception, JDK 1.4 and above only
1495: * @param e
1496: * @return
1497: */
1498: public static Throwable getCause(Exception e) {
1499: Class c = e.getClass();
1500: Class parms[] = {};
1501: Object pass[] = {};
1502: try {
1503: Method m = c.getMethod("getCause", parms);
1504: Throwable t = (Throwable) m.invoke(e, pass);
1505: return t;
1506: } catch (SecurityException e1) {
1507: return null;
1508: } catch (NoSuchMethodException e1) {
1509: return null;
1510: } catch (IllegalArgumentException e1) {
1511: return null;
1512: } catch (IllegalAccessException e1) {
1513: return null;
1514: } catch (InvocationTargetException e1) {
1515: return null;
1516: }
1517:
1518: }
1519:
1520: }
|