KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > de > gulden > util > Toolbox


1 /*
2  * Project: Gulden Utilies
3  * Class: de.gulden.util.Toolbox
4  * Version: snapshot-beautyj-1.1
5  *
6  * Date: 2004-09-29
7  *
8  * This is a snapshot version of the Gulden Utilities,
9  * it is not released as a seperate version.
10  *
11  * Note: Contains auto-generated Javadoc comments created by BeautyJ.
12  *
13  * This is licensed under the GNU Lesser General Public License (LGPL)
14  * and comes with NO WARRANTY.
15  *
16  * Author: Jens Gulden
17  * Email: amoda@jensgulden.de
18  */

19
20 package de.gulden.util;
21
22 import java.awt.*;
23 import java.net.MalformedURLException JavaDoc;
24 import java.net.URL JavaDoc;
25 import java.util.*;
26 import java.util.Collection JavaDoc;
27 import java.util.List JavaDoc;
28 import java.util.Map JavaDoc;
29 import javax.swing.text.Document JavaDoc;
30
31 /**
32  * Class Toolbox.
33  *
34  * @author Jens Gulden
35  * @version snapshot-beautyj-1.1
36  */

37 public class Toolbox {
38
39     // ------------------------------------------------------------------------
40
// --- final static fields ---
41
// ------------------------------------------------------------------------
42

43     /**
44      * Constant NORTH.
45      */

46     public static final int NORTH = 1;
47
48     /**
49      * Constant EAST.
50      */

51     public static final int EAST = 2;
52
53     /**
54      * Constant SOUTH.
55      */

56     public static final int SOUTH = 4;
57
58     /**
59      * Constant WEST.
60      */

61     public static final int WEST = 8;
62
63     /**
64      * Constant NORTH_EAST.
65      */

66     public static final int NORTH_EAST = 3;
67
68     /**
69      * Constant SOUTH_EAST.
70      */

71     public static final int SOUTH_EAST = 6;
72
73     /**
74      * Constant SOUTH_WEST.
75      */

76     public static final int SOUTH_WEST = 12;
77
78     /**
79      * Constant NORTH_WEST.
80      */

81     public static final int NORTH_WEST = 9;
82
83     /**
84      * Constant CENTER.
85      */

86     public static final int CENTER = 0;
87
88     /**
89      * Constant NL.
90      */

91     public static final String JavaDoc NL = System.getProperty("line.separator");
92
93     /**
94      * Constant primitiveTypeWrappers[][].
95      */

96     private static final Object JavaDoc[][] primitiveTypeWrappers = {{"boolean","byte","short","int","long","float","double","char"},{java.lang.Boolean JavaDoc.class,java.lang.Byte JavaDoc.class,java.lang.Short JavaDoc.class,java.lang.Integer JavaDoc.class,java.lang.Long JavaDoc.class,java.lang.Float JavaDoc.class,java.lang.Double JavaDoc.class,java.lang.Character JavaDoc.class}};
97
98
99     // ------------------------------------------------------------------------
100
// --- static methods ---
101
// ------------------------------------------------------------------------
102

103     /**
104      * Returns the primitive type wrapper class.
105      */

106     public static Class JavaDoc getPrimitiveTypeWrapperClass(String JavaDoc typename) throws ClassNotFoundException JavaDoc {
107         int i=getPrimitiveTypeIndex(typename);
108         if (i!=-1) {
109             return (Class JavaDoc)primitiveTypeWrappers[1][i];
110         } else {
111             throw new ClassNotFoundException JavaDoc("'"+typename+"' is not a primitive type");
112         }
113     }
114
115     /**
116      * Returns the primitive type class.
117      */

118     public static Class JavaDoc getPrimitiveTypeClass(String JavaDoc typename) throws ClassNotFoundException JavaDoc {
119         Class JavaDoc wrapper=getPrimitiveTypeWrapperClass(typename);
120         try {
121             java.lang.reflect.Field JavaDoc field=wrapper.getField("TYPE"); // all wrapper classes have public static field TYPE to represent the primitive Class
122
Class JavaDoc primitiveClass=(Class JavaDoc)field.get(null);
123             return primitiveClass;
124         } catch (Exception JavaDoc e) {
125             throw new ClassNotFoundException JavaDoc("wrapper for '"+typename+"' has no TYPE field");
126         }
127     }
128
129     public static boolean isPrimitiveType(String JavaDoc typename) {
130         return (getPrimitiveTypeIndex(typename)!=-1);
131     }
132
133     /**
134      * Parses the color.
135      */

136     public static Color parseColor(String JavaDoc s) {
137         if ((s.length()==7)&&(s.startsWith("#"))) {
138             String JavaDoc rStr=s.substring(1,3);
139             String JavaDoc gStr=s.substring(3,5);
140             String JavaDoc bStr=s.substring(5,7);
141             int r=decimal(rStr);
142             int g=decimal(gStr);
143             int b=decimal(bStr);
144             return new Color(r,g,b);
145         } else {
146             // try to get from AWT-color-constants
147
try {
148                 java.lang.reflect.Field JavaDoc field=Color.class.getField(s);
149                 return (Color)field.get(null);
150             } catch (Exception JavaDoc e) {
151                 return null; // not found
152
}
153         }
154     }
155
156     public static String JavaDoc toString(Color color) {
157         return "#"+hex(color.getRed(),2)+hex(color.getGreen(),2)+hex(color.getBlue(),2);
158     }
159
160     public static String JavaDoc hex(int i) {
161         return Integer.toHexString(i);
162     }
163
164     public static String JavaDoc hex(int i, int minLength) {
165         String JavaDoc s=hex(i);
166         int lendiff=minLength-s.length();
167         return s+repeat('0',lendiff); // negative values are ok for repeat
168
}
169
170     public static int decimal(String JavaDoc hex) {
171         return Integer.valueOf(hex,16).intValue();
172     }
173
174     public static String JavaDoc repeat(String JavaDoc s, int count) {
175         StringBuffer JavaDoc sb=new StringBuffer JavaDoc();
176         for (int i=0;i<count;i++) {
177             sb.append(s);
178         }
179         return sb.toString();
180     }
181
182     public static String JavaDoc repeat(char c, int count) {
183         StringBuffer JavaDoc sb=new StringBuffer JavaDoc();
184         for (int i=0;i<count;i++) {
185             sb.append(c);
186         }
187         return sb.toString();
188     }
189
190     public static String JavaDoc noNull(String JavaDoc s) {
191         if (s!=null) {
192             return s;
193         } else {
194             return "";
195         }
196     }
197
198     public static String JavaDoc unqualify(String JavaDoc s) {
199         int pos=s.lastIndexOf('.');
200         if (pos!=-1) {
201             return s.substring(pos+1);
202         } else {
203             return s;
204         }
205     }
206
207     public static String JavaDoc padRight(String JavaDoc s, String JavaDoc fill, int len) {
208         return s+repeat(fill,len-s.length());
209     }
210
211     public static String JavaDoc padLeft(String JavaDoc s, String JavaDoc fill, int len) {
212         return repeat(fill,len-s.length())+s;
213     }
214
215     /**
216      * Parses the boolean.
217      */

218     public static boolean parseBoolean(String JavaDoc s) {
219         return s.equalsIgnoreCase("yes")||s.equalsIgnoreCase("y")||s.equalsIgnoreCase("on")||s.equalsIgnoreCase("true");
220     }
221
222     public static String JavaDoc capitalize(String JavaDoc s) {
223         if (s.length()>0) {
224             return s.substring(0,1).toUpperCase()+s.substring(1);
225         } else {
226             return "";
227         }
228     }
229
230     public static String JavaDoc unqualifyJavaName(String JavaDoc name) {
231         int lastDotPos=name.lastIndexOf('.');
232         if (lastDotPos!=-1) {
233             return name.substring(lastDotPos+1);
234         } else {
235             return name;
236         }
237     }
238
239     /**
240      * Tests if an element is contained in an array, based on a test using equals(...).
241      */

242     public static boolean arrayContains(Object JavaDoc[] array, Object JavaDoc object) {
243         for (int i=0;i<array.length;i++) {
244             if (object.equals(array[i])) {
245                 return true;
246             }
247         }
248         return false;
249     }
250
251     /**
252      *
253      * @deprecated use isEmpty(String) instead
254      */

255     public static boolean empty(String JavaDoc s) {
256         return isEmpty(s);
257     }
258
259     public static boolean isEmpty(String JavaDoc s) {
260         return (s==null)||(s.trim().length()==0);
261     }
262
263     /**
264      * Returns null if the String has zero size, or is already null itself.
265      * Otherwise returns the string.
266      *
267      * @param s the String to test
268      */

269     public static String JavaDoc emptyNull(String JavaDoc s) {
270         if (s==null||s.length()==0) {
271             return null;
272         } else {
273             return s;
274         }
275     }
276
277     public static void centerOnScreen(Component component) {
278         Dimension screen=component.getToolkit().getScreenSize();
279         Dimension comp=component.getSize();
280         Point newLocation=new Point((screen.width-comp.width)/2,(screen.height-comp.height)/2);
281         component.setLocation(newLocation);
282     }
283
284     public static void centerComponent(Component component, Component parent) {
285         Dimension p=parent.getSize();
286         Dimension comp=component.getSize();
287         Point oldPos=parent.getLocation();
288         Point newPos=new Point();
289         newPos.x=oldPos.x+(p.width-comp.width)/2;
290         newPos.y=oldPos.y+(p.height-comp.height)/2;
291         component.setLocation(newPos);
292     }
293
294     public static Object JavaDoc invokeValueOf(Class JavaDoc clazz, String JavaDoc s) {
295         try {
296             Class JavaDoc[] signature={String JavaDoc.class};
297             java.lang.reflect.Method JavaDoc m=clazz.getMethod("valueOf",signature);
298             Object JavaDoc[] params={s};
299             Object JavaDoc result=m.invoke(null,params);
300             return result;
301         } catch (Exception JavaDoc e) {
302             return null;
303         }
304     }
305
306     public static Object JavaDoc invokeMethod(Object JavaDoc o, String JavaDoc methodName, Class JavaDoc[] signature, Object JavaDoc[] parameters) {
307         try {
308             java.lang.reflect.Method JavaDoc m=o.getClass().getMethod(methodName,signature);
309             Object JavaDoc result=m.invoke(o,parameters);
310             return result;
311         } catch (Exception JavaDoc e) {
312             return null;
313         }
314     }
315
316     public static Object JavaDoc invokeMethod(Object JavaDoc o, String JavaDoc methodName, Class JavaDoc signatureSingle, Object JavaDoc parameterSingle) {
317         return invokeMethod(o, methodName, new Class JavaDoc[] {signatureSingle}, new Object JavaDoc[] {parameterSingle});
318     }
319
320     public static List JavaDoc invokeOnAll(Collection JavaDoc c, String JavaDoc methodName, Class JavaDoc[] signature, Object JavaDoc[] parameter) {
321         List JavaDoc l = new ArrayList();
322         for (Iterator it = c.iterator(); it.hasNext(); ) {
323             Object JavaDoc o = it.next();
324             Object JavaDoc result = invokeMethod(o, methodName, signature, parameter);
325             l.add(result);
326         }
327         return l;
328     }
329
330     public static void fireEvent(Collection JavaDoc listeners, String JavaDoc methodName, EventObject event) {
331         invokeOnAll(listeners, methodName, new Class JavaDoc[] {event.getClass()}, new Object JavaDoc[] {event});
332     }
333
334     /**
335      * Returns the document text.
336      */

337     public static String JavaDoc getDocumentText(Document JavaDoc d) {
338         try {
339             return d.getText(d.getStartPosition().getOffset(),d.getLength());
340         } catch (javax.swing.text.BadLocationException JavaDoc ble) {
341             return null;
342         }
343     }
344
345     /**
346      * Sets the document text.
347      */

348     public static void setDocumentText(Document JavaDoc d, String JavaDoc s) {
349         try {
350             d.remove(d.getStartPosition().getOffset(),d.getLength());
351             d.insertString(d.getStartPosition().getOffset(),s,null);
352         } catch (javax.swing.text.BadLocationException JavaDoc ble) {
353             throw new Error JavaDoc("INTERNAL ERROR: Toolbox.setDocumentText");
354         }
355     }
356
357     public static Collection JavaDoc filterCollectionOnType(Collection JavaDoc c, Class JavaDoc type) {
358         Collection JavaDoc result=new ArrayList();
359         for (Iterator it=c.iterator();it.hasNext();) {
360             Object JavaDoc o=it.next();
361             if (type.isAssignableFrom(o.getClass())) {
362                 result.add(o);
363             }
364         }
365         return result;
366     }
367
368     public static Map JavaDoc filterMapOnType(Map JavaDoc m, Class JavaDoc type) {
369         OrderedHashMap result=new OrderedHashMap();
370         for (Iterator it=m.entrySet().iterator();it.hasNext();) {
371             Map.Entry JavaDoc entry=(Map.Entry JavaDoc)it.next();
372             if (type.isAssignableFrom(entry.getValue().getClass())) {
373                 result.put(entry.getKey(),entry.getValue());
374             }
375         }
376         return result;
377     }
378
379     public static Component findChildComponent(Container c, Class JavaDoc childType) {
380         Component[] children=c.getComponents();
381         for (int i=0;i<children.length;i++) {
382             if (childType==children[i].getClass()) {
383                 return children[i];
384             }
385         }
386         // if not yet found flatly, recurse search on containers
387
for (int i=0;i<children.length;i++) {
388             if (children[i] instanceof Container) {
389                 Component found=findChildComponent((Container)children[i],childType);
390                 if (found!=null) {
391                     return found;
392                 }
393             }
394         }
395         return null;
396     }
397
398     public static Component findChildComponentCloseTo(Container c, Class JavaDoc childType, Component anker) {
399         Component[] children=c.getComponents();
400         // find anker index
401
int index = -1;
402         for (int i=0; (index == -1) && (i<children.length); i++) {
403             if (children[i]==anker) {
404                 index = i;
405             }
406         }
407         if (index != -1) {
408             int closest = -1;
409             // find closest instance of requested type
410
for (int i=0; i<children.length; i++) {
411                 if (childType==children[i].getClass()) {
412                     if ( (closest == -1) || (abs(index-i)<abs(index-closest)) ) {
413                         closest = i;
414                     }
415                 }
416             }
417             if (closest != -1) {
418                 return children[closest];
419             } else {
420                 return null;
421             }
422         } else {
423             // if not yet found flatly, recurse search on containers
424
for (int i=0;i<children.length;i++) {
425                 if (children[i] instanceof Container) {
426                     Component found=findChildComponentCloseTo((Container)children[i],childType, anker);
427                     if (found!=null) {
428                         return found;
429                     }
430                 }
431             }
432         }
433         return null;
434     }
435
436     public static void drawString(Graphics g, String JavaDoc s, Point p, int anchor, Insets shift, Color backgroundColor, Insets backgroundBorder) {
437         java.awt.FontMetrics JavaDoc fm=g.getFontMetrics();
438         int w=fm.stringWidth(s);
439         int h=fm.getHeight();
440         // AWT draws string anchored at SOUTH_WEST
441
if ((anchor&NORTH)!=0) { // north
442
p.y+=(h+shift.top);
443         } else if ((anchor&SOUTH)==0) { // middle
444
p.y+=(h/2);
445         } else { // south
446
p.y-=shift.bottom;
447         }
448         if ((anchor&EAST)!=0) { // east
449
p.x-=(w+shift.right);
450         } else if ((anchor&WEST)==0) { // center
451
p.x-=(w/2);
452         } else { // west
453
p.x+=shift.left;
454         }
455         if (backgroundColor!=null) {
456             if (backgroundBorder==null) {
457                 backgroundBorder=new Insets(0,0,0,0);
458             }
459             Color foregroundColor=g.getColor();
460             g.setColor(backgroundColor);
461             java.awt.Rectangle JavaDoc r=new java.awt.Rectangle JavaDoc();
462             r.x=p.x-backgroundBorder.left;
463             r.y=p.y-fm.getAscent()-backgroundBorder.top;
464             r.width=w+backgroundBorder.left+backgroundBorder.right;
465             r.height=h+backgroundBorder.top+backgroundBorder.bottom;
466             g.fillRect(r.x,r.y,r.width,r.height);
467             g.setColor(foregroundColor);
468         }
469         g.drawString(s,p.x,p.y);
470     }
471
472     public static void drawString(Graphics g, String JavaDoc s, Point p, int anchor, Insets shift) {
473         drawString(g,s,p,anchor,shift,null,null);
474     }
475
476     public static void drawString(Graphics g, String JavaDoc s, Point p, int anchor) {
477         drawString(g,s,p,anchor,new Insets(0,0,0,0));
478     }
479
480     /**
481      * Sets the location centered.
482      */

483     public static void setLocationCentered(Component c, Point p) {
484         Dimension size=c.getSize();
485         c.setLocation(p.x-size.width/2,p.y-size.height/2);
486     }
487
488     public static String JavaDoc replace(String JavaDoc s, String JavaDoc search, String JavaDoc repl) {
489         int pos=s.indexOf(search);
490         if (pos>=0) {
491             return s.substring(0,pos)+repl+replace(s.substring(pos+search.length()),search,repl);
492         } else {
493             return s;
494         }
495     }
496
497     public static List JavaDoc explode(String JavaDoc s, char seperator) {
498         StringTokenizer st=new StringTokenizer(s,String.valueOf(seperator),false);
499         List JavaDoc l=new ArrayList();
500         while (st.hasMoreTokens()) {
501             l.add(st.nextToken());
502         }
503         return l;
504     }
505
506     public static List JavaDoc explode(String JavaDoc s) {
507         return explode(s,',');
508     }
509
510     public static String JavaDoc implode(Collection JavaDoc c, char separator) {
511         StringBuffer JavaDoc sb=new StringBuffer JavaDoc();
512         for (Iterator it=c.iterator();it.hasNext();) {
513             String JavaDoc s=(String JavaDoc)it.next();
514             sb.append(s);
515             if (it.hasNext()) {
516                 sb.append(separator);
517             }
518         }
519         return sb.toString();
520     }
521
522     public static String JavaDoc implode(Collection JavaDoc c) {
523         return implode(c,',');
524     }
525
526     /**
527      * Returns the lines.
528      */

529     public static List JavaDoc getLines(String JavaDoc s) {
530         List JavaDoc l = new ArrayList();
531         if ((s!=null) && (s.length()>0)) {
532             int start = 0;
533             int pos = s.indexOf('\n');
534             String JavaDoc line;
535             while (pos != -1) {
536                 line = s.substring(start, pos);
537                 l.add(line);
538                 if (pos < s.length()) {
539                     start = pos + 1;
540                     pos = s.indexOf('\n', start);
541                 } else {
542                     pos = -1;
543                 }
544             }
545             line = s.substring(start);
546             l.add(line);
547         }
548         return l;
549     }
550
551     public static boolean isYes(String JavaDoc s) {
552         if (s!=null) {
553             s=s.trim().toLowerCase();
554             return (s.equals("yes")||s.equals("true")||s.equals("on"));
555         } else {
556             return false;
557         }
558     }
559
560     public static boolean isNo(String JavaDoc s) {
561         if (s!=null) {
562             s=s.trim().toLowerCase();
563             return (s.equals("no")||s.equals("false")||s.equals("off"));
564         } else {
565             return false;
566         }
567     }
568
569     public static String JavaDoc replaceCharsWithStrings(String JavaDoc s, char[] c, String JavaDoc[] r) {
570         int len=s.length();
571         StringBuffer JavaDoc sb=new StringBuffer JavaDoc();
572         int[] pos=new int[c.length];
573         int firstIndex=-1;
574         int first=len;
575         int lastPos=0;
576         // init first positions of each char
577
for (int i=0;i<c.length;i++) {
578             int p=s.indexOf(c[i]);
579             pos[i]=p;
580             if ((p!=-1)&&(p<first)) {
581                 first=p;
582                 firstIndex=i;
583             }
584         }
585         do {
586             String JavaDoc part=s.substring(lastPos,first);
587             sb.append(part);
588             if (first<len) { // firstIndex had been found
589
sb.append(r[firstIndex]);
590                 lastPos=first+1;
591                 if (lastPos<len) { // update next pos of this char
592
pos[firstIndex]=s.indexOf(c[firstIndex],lastPos);
593                 } else {
594                     pos[firstIndex]=-1;
595                 }
596                 // find new first
597
first=len;
598                 for (int i=0;i<c.length;i++) {
599                     int p=pos[i];
600                     if ((p!=-1)&&(p<first)) {
601                         first=p;
602                         firstIndex=i;
603                     }
604                 }
605             } else {
606                 lastPos=len;
607             }
608         } while (lastPos<len);
609         return sb.toString();
610     }
611
612     /**
613      * Converts a String to a URL. If the string starts with "res:/",
614      * this leading part is cut off and the URL is created via ClassLoader.getResource().
615      * Otherwise, the URL is created sirectly from the String.
616      */

617     public static URL JavaDoc getResourceURL(String JavaDoc resString) throws MalformedURLException JavaDoc {
618         if (resString.startsWith("res:")) {
619             resString = resString.substring(4);
620             java.net.URL JavaDoc url = ClassLoader.getSystemClassLoader().getResource(resString);
621             return url;
622         } else {
623             return new java.net.URL JavaDoc(resString);
624         }
625     }
626
627     public static URL JavaDoc findResource(String JavaDoc resString, Object JavaDoc ref) {
628         return findResource(resString, ref.getClass().getClassLoader());
629     }
630
631     public static URL JavaDoc findResource(String JavaDoc resString, ClassLoader JavaDoc cl) {
632             // first try to get from current ClassLoader
633
java.net.URL JavaDoc url = (cl != null) ? cl.getResource(resString) : null;
634             // if not found, try to get from system-ClassLoader
635
if (url == null) {
636                 url = ClassLoader.getSystemClassLoader().getResource(resString);
637             }
638             return url;
639
640     }
641
642     /**
643      * Loads a class and instantiates it.
644      */

645     public static Object JavaDoc instantiateClass(String JavaDoc classname, Class JavaDoc ensureType) throws ClassNotFoundException JavaDoc, IllegalAccessException JavaDoc, InstantiationException JavaDoc {
646         Class JavaDoc cl = Class.forName(classname);
647         if (!ensureType.isAssignableFrom(cl)) {
648             throw new IllegalAccessException JavaDoc("cannot instantiate class '"+classname+"' - not a subclass/implementation of '"+ensureType.getName()+"'");
649         }
650         return cl.newInstance();
651     }
652
653     /**
654      * Parse key/value pairs in a string. Key and value are sperated by '='.
655      * the pairs are seperated by whitespace or ';'.
656      * Multiple occurrences of the same key will result in a String[]-array
657      * parse result for that key.
658      *
659      * @param s The string to parse.
660      * @return Properties, with value entries either of type String or String[]
661      */

662     public static Properties parseKeyValuePairs(String JavaDoc s) {
663         // parses strings like: a="val"; b="val"; c="val"...
664
StringTokenizer st = new StringTokenizer(s, " \t\n=\";", false);
665         Properties p = new Properties();
666         while (st.hasMoreTokens()) {
667             String JavaDoc key = st.nextToken();
668             if (st.hasMoreTokens()) {
669                 String JavaDoc val = st.nextToken();
670                 p.put(key, val);
671             }
672         }
673         return p;
674     }
675
676     /**
677      * Removes all whitespace at the start of the string.
678      */

679     public static String JavaDoc trimLeft(String JavaDoc s) {
680         int pos=0;
681         while ((pos<s.length())&&(Character.isWhitespace(s.charAt(pos)))) {
682             pos++;
683         }
684         return s.substring(pos);
685     }
686
687     /**
688      * Removes all whitespace at the end of the string.
689      */

690     public static String JavaDoc trimRight(String JavaDoc s) {
691         int pos=s.length();
692         while ((pos>=1)&&(Character.isWhitespace(s.charAt(pos-1)))) {
693             pos--;
694         }
695         return s.substring(0,pos);
696     }
697
698     public static int abs(int i) {
699         if (i>=0) {
700             return i;
701         } else {
702             return -i;
703         }
704     }
705
706     /**
707      * Returns the primitive type index.
708      */

709     private static int getPrimitiveTypeIndex(String JavaDoc typename) {
710         for (int i=0;i<primitiveTypeWrappers[0].length;i++) {
711             if (primitiveTypeWrappers[0][i].equals(typename)) {
712                 return i;
713             }
714         }
715         return -1;
716     }
717
718 } // end Toolbox
719
Popular Tags