KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > shark > utilities > MiscUtilities


1 package org.enhydra.shark.utilities;
2
3 import java.io.*;
4 import java.lang.reflect.Method JavaDoc;
5 import java.security.MessageDigest JavaDoc;
6 import java.util.*;
7
8 import org.enhydra.shark.api.RootException;
9
10 /**
11  * The various utilities needed for shark.
12  * @author Sasa Bojanic
13  * @author Vladimir Puskas
14  * @author Zoran Milakovic
15  */

16 public class MiscUtilities {
17
18    // recursive implementation
19
public static void traverse(File f,Collection c,FileFilter filter) {
20       if (!f.exists()) {
21          return;
22       }
23       if (f.isDirectory()) {
24          File[] children = f.listFiles(filter);
25          for (int i=0; i<children.length; i++) {
26             traverse(children[i],c,filter);
27          }
28       } else {
29          c.add(f);
30       }
31    }
32
33
34    public static byte[] serialize(Object JavaDoc obj) throws IOException {
35       //System.err.println(" ser ##"+obj);
36
ByteArrayOutputStream bout = new ByteArrayOutputStream();
37       ObjectOutputStream oout = new ObjectOutputStream(bout);
38       oout.writeObject(obj);
39       oout.flush();
40       byte array[] = bout.toByteArray();
41       oout.close();
42       bout.close();
43       //System.err.println(" ser #"+new String(array));
44
return array;
45    }
46
47    public static Object JavaDoc deserialize(byte[]array) throws Throwable JavaDoc {
48       //System.err.println("neser#"+new String(array));
49
ObjectInputStream rin = new ObjectInputStream
50          (new ByteArrayInputStream(array));
51       Object JavaDoc obj = rin.readObject();
52       rin.close();
53       //System.err.println("neser##"+obj);
54
return obj;
55    }
56
57    // Temporary realized to get the time passed from .. 1970 in millis
58
public static long getAbsoluteTimeInUTCFormat () {
59       return System.currentTimeMillis();
60    }
61
62    /**
63     * Take the given string and chop it up into a series
64     * of strings on given boundries. This is useful
65     * for trying to get an array of strings out of the
66     * resource file.
67     */

68    public static String JavaDoc[] tokenize(String JavaDoc input,String JavaDoc boundary) {
69       if (input==null) input="";
70       Vector v = new Vector();
71       StringTokenizer t = new StringTokenizer(input,boundary);
72       String JavaDoc cmd[];
73
74       while (t.hasMoreTokens())
75          v.addElement(t.nextToken());
76       cmd = new String JavaDoc[v.size()];
77       for (int i = 0; i < cmd.length; i++)
78          cmd[i] = (String JavaDoc)v.elementAt(i);
79
80       return cmd;
81    }
82
83    public static String JavaDoc getTimeDiff (long tStart,long tEnd) {
84       long sec=1000;
85       long min=sec*60;
86       long hour=min*60;
87       long day=hour*24;
88       long month=day*30;
89       long year=365*day;
90
91       // UTC is temporary realized to hold the time in miliss passed from .. 1970
92
long diffInMills=tEnd-tStart;
93       if (diffInMills<min) {
94          return String.valueOf(diffInMills/sec)+" [s]";
95       } else if (diffInMills<hour) {
96          long m=diffInMills/min;
97          long s=(diffInMills-m*min)/sec;
98          return String.valueOf(m)+" [min] "+String.valueOf(s)+" [s]";
99       } else if (diffInMills<day) {
100          long h=diffInMills/hour;
101          long m=(diffInMills-h*hour)/min;
102          long s=(diffInMills-h*hour-m*min)/sec;
103          return String.valueOf(h)+" [h] "+String.valueOf(m)+" [min] "+
104             String.valueOf(s)+" [s]";
105       } else if (diffInMills<month) {
106          long d=diffInMills/day;
107          long h=(diffInMills-d*day)/hour;
108          long m=(diffInMills-d*day-h*hour)/min;
109          long s=(diffInMills-d*day-h*hour-m*min)/sec;
110          return String.valueOf(d)+" [d] "+String.valueOf(h)+" [h] "+
111             String.valueOf(m)+" [min] "+String.valueOf(s)+" [s]";
112       } else if (diffInMills<year) {
113          long mn=diffInMills/month;
114          long d=(diffInMills-mn*month)/day;
115          long h=(diffInMills-mn*month-d*day)/hour;
116          long m=(diffInMills-mn*month-d*day-h*hour)/min;
117          long s=(diffInMills-mn*month-d*day-h*hour-m*min)/sec;
118          return String.valueOf(mn)+" [m] "+String.valueOf(d)+" [d] "+
119             String.valueOf(h)+" [h] "+String.valueOf(m)+
120             " [min] "+String.valueOf(s)+" [s]";
121       } else { //if (diffInMills>=year)
122
long y=diffInMills/year;
123          long mn=(diffInMills-y*year)/month;
124          long d=(diffInMills-y*year-mn*month)/day;
125          long h=(diffInMills-y*year-mn*month-d*day)/hour;
126          long m=(diffInMills-y*year-mn*month-d*day-h*hour)/min;
127          long s=(diffInMills-y*year-mn*month-d*day-h*hour-m*min)/sec;
128          return String.valueOf(y)+" [y] "+String.valueOf(mn)+" [m] "+
129             String.valueOf(d)+" [d] "+String.valueOf(h)+" [h] "+
130             String.valueOf(m)+" [min] "+String.valueOf(s)+" [s]";
131       }
132    }
133
134
135    public static void copyFile(String JavaDoc src,String JavaDoc dest) throws IOException {
136       FileInputStream in=new FileInputStream(src);
137       FileOutputStream out=new FileOutputStream(dest);
138       byte buffer[] = new byte[1024];
139       int read = -1;
140       while ((read = in.read(buffer, 0, 1024)) != -1) {
141          out.write(buffer, 0, read);
142       }
143       out.flush();
144       out.close();
145       in.close();
146    }
147
148
149    /**
150     * Converts the given time in milliseconds into the time
151     * string in format YYYY-MM-DD-HH-mm-SS-mmmm
152     */

153    public static String JavaDoc convertMillisecondsToDateAndTimeString (long cdt) {
154       String JavaDoc dateSeparator="-";
155       Calendar cal=new GregorianCalendar();
156       cal.setTime(new Date(cdt));
157       //cal.setTimeInMillis(cdt);
158

159       int YYYY=cal.get(Calendar.YEAR);
160       int MM=cal.get(Calendar.MONTH)+1;
161       int DD=cal.get(Calendar.DAY_OF_MONTH);
162       int HH=cal.get(Calendar.HOUR_OF_DAY);
163       int mm=cal.get(Calendar.MINUTE);
164       int ss=cal.get(Calendar.SECOND);
165       int mmmm=cal.get(Calendar.MILLISECOND);
166
167       String JavaDoc dateTime="";
168
169       dateTime=dateTime+String.valueOf(YYYY)+dateSeparator;
170       if (MM<10) {
171          dateTime=dateTime+"0";
172       }
173       dateTime=dateTime+String.valueOf(MM)+dateSeparator;
174       if (DD<10) {
175          dateTime=dateTime+"0";
176       }
177       dateTime=dateTime+String.valueOf(DD)+dateSeparator;
178
179       if (cal.get(Calendar.AM_PM)==Calendar.PM && HH<12) {
180          HH+=12;
181       }
182       if (HH<10) {
183          dateTime=dateTime+"0";
184       }
185       dateTime=dateTime+String.valueOf(HH)+dateSeparator;
186
187       if (mm<10) {
188          dateTime=dateTime+"0";
189       }
190       dateTime=dateTime+String.valueOf(mm)+dateSeparator;
191
192       if (ss<10) {
193          dateTime=dateTime+"0";
194       }
195       dateTime=dateTime+String.valueOf(ss)+dateSeparator;
196
197       if (mmmm<10) {
198          dateTime=dateTime+"000";
199       } else if (mmmm<100) {
200          dateTime=dateTime+"00";
201       } else {
202          dateTime=dateTime+"0";
203       }
204       dateTime=dateTime+String.valueOf(mmmm);
205
206       return dateTime;
207    }
208
209    /**
210     * Converts the given time string into milliseconds.
211     */

212    public static long convertDateAndTimeStringToMilliseconds (String JavaDoc dateTime) {
213       String JavaDoc dateSeparator="-";
214       String JavaDoc[] dts=tokenize(dateTime,dateSeparator);
215       if (dts==null || dts.length!=7) return -1;
216
217       int YYYY=Integer.parseInt(dts[0]);
218       int MM=Integer.parseInt(dts[1]);
219       int DD=Integer.parseInt(dts[2]);
220       int HH=Integer.parseInt(dts[3]);
221       int mm=Integer.parseInt(dts[4]);
222       int ss=Integer.parseInt(dts[5]);
223       int mmmm=Integer.parseInt(dts[6]);
224
225       Calendar cal=new GregorianCalendar(YYYY,MM,DD,HH,mm,ss);
226       //long time=cal.getTimeInMillis()+mmmm;
227
long time=cal.getTime().getTime()+mmmm;
228
229       return time;
230    }
231
232    public static boolean isEmptyString (String JavaDoc str) {
233       return (str==null || str.trim().length()==0);
234    }
235
236    /**
237     * The variable is complex if its type is not BasicType in the XPDL sense.
238     */

239    public static final boolean isComplexWRD (Object JavaDoc wrd) {
240       return !((wrd instanceof Long JavaDoc) || (wrd instanceof Double JavaDoc) || (wrd instanceof Boolean JavaDoc) || (wrd instanceof Date)
241                   || (wrd instanceof String JavaDoc));
242    }
243
244    /**
245     * Tries to clone Workflow relevant data. It this is a simple WRD (String,
246     * Long, Boolean, ...) then it just returns the same object. If it is a
247     * complex WRD (some specific Java class), it first check if it implements
248     * interface Cloneable, and tries to execute public method clone() if it
249     * finds it, by using reflection, and if this doesn't succeed, it tries to
250     * serialize object, and then deserialize it. If everything fails, the
251     * original object is returned.
252     */

253    public static Object JavaDoc cloneWRD (Object JavaDoc wrd) throws Throwable JavaDoc {
254       if (!isComplexWRD(wrd)) {
255          return wrd;
256       }
257       if (wrd==null) {
258          return null;
259       }
260
261       Object JavaDoc ret=null;
262
263       if (wrd instanceof Cloneable JavaDoc) {
264          //System.err.println("Cloning WRD for class: hc="+wrd.hashCode()+", nm="+wrd.getClass().getName()+" using clone() method");
265
Class JavaDoc cls=wrd.getClass();
266          try {
267             Method JavaDoc mth=cls.getMethod("clone",null);
268             ret=mth.invoke(wrd,null);
269             //System.err.println("WRD class cloned: hc="+ret.hashCode());
270
} catch (Throwable JavaDoc ex) {
271             ex.printStackTrace();
272          }
273       }
274
275       if (ret==null) {
276          // serialize object
277
byte[] serVal=serialize(wrd);
278          ret=deserialize(serVal);
279       }
280
281       return ret;
282    }
283
284    public static String JavaDoc passwordDigest(String JavaDoc password) throws RootException {
285       try {
286          MessageDigest JavaDoc md = MessageDigest.getInstance("SHA-1");
287          byte[] passwd = md.digest(password.getBytes());
288          StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
289          for (int i =0; i < passwd.length; ++i) {
290             byte current = passwd[i];
291             for (int j = 0; j < 2; ++j) {
292                int nibble = 0xF &((1 == j)? current: current >> 4);
293                buffer.append(Character.forDigit(nibble, 16));
294             }
295          }
296          return buffer.toString();
297       } catch (Exception JavaDoc e) {
298          throw new RootException(e);
299       }
300    }
301
302    /**
303     * Replace all occurence of forReplace with replaceWith in input string.
304     * @param input represents input string
305     * @param forReplace represents substring for replace
306     * @param replaceWith represents replaced string value
307     * @return new string with replaced values
308     */

309    public static String JavaDoc replaceAll(String JavaDoc input,
310                                    String JavaDoc forReplace,
311                                    String JavaDoc replaceWith) {
312       if( input == null )
313          return null;
314       StringBuffer JavaDoc result = new StringBuffer JavaDoc();
315       boolean hasMore = true;
316       while (hasMore) {
317          int start = input.indexOf(forReplace);
318          int end = start + forReplace.length();
319          if (start != -1) {
320             result.append(input.substring(0, start) + replaceWith);
321             input = input.substring(end);
322          } else {
323             hasMore = false;
324             result.append(input);
325          }
326       }
327       if (result.toString().equals(""))
328          return input; //nothing is changed
329
else
330          return result.toString();
331    }
332 }
333
Popular Tags