KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > jawe > Utils


1 /* Utils.java
2  *
3  * Authors:
4  * Stefanovic Nenad chupo@iis.ns.ac.yu
5  * Bojanic Sasa sasaboy@neobee.net
6  * Puskas Vladimir vpuskas@eunet.yu
7  * Pilipovic Goran zboniek@uns.ac.yu
8  *
9  */

10
11 package org.enhydra.jawe;
12
13 import java.awt.*;
14 import java.awt.image.*;
15 import java.io.*;
16 import java.lang.reflect.*;
17 import java.util.*;
18 import java.util.jar.*;
19 import java.util.zip.*;
20 import java.net.URL JavaDoc;
21
22 import org.jgraph.graph.*;
23
24 import org.enhydra.jawe.graph.*;
25 import org.enhydra.jawe.xml.*;
26
27 import org.enhydra.jawe.xml.elements.Activities;
28 import org.enhydra.jawe.xml.elements.ActivitySet;
29 import org.enhydra.jawe.xml.elements.ActivitySets;
30 import org.enhydra.jawe.xml.elements.Package;
31 import org.enhydra.jawe.xml.elements.WorkflowProcess;
32 import org.enhydra.jawe.xml.elements.WorkflowProcesses;
33
34 import org.enhydra.jawe.misc.PFLocale;
35
36 public class Utils {
37
38    /**
39     * Take the given string and chop it up into a series
40     * of strings on given boundries. This is useful
41     * for trying to get an array of strings out of the
42     * resource file.
43     */

44    public static String JavaDoc[] tokenize(String JavaDoc input,String JavaDoc boundary) {
45       if (input==null) input="";
46       Vector v = new Vector();
47       StringTokenizer t = new StringTokenizer(input,boundary);
48       String JavaDoc cmd[];
49
50       while (t.hasMoreTokens())
51          v.addElement(t.nextToken());
52       cmd = new String JavaDoc[v.size()];
53       for (int i = 0; i < cmd.length; i++)
54          cmd[i] = (String JavaDoc)v.elementAt(i);
55
56       return cmd;
57    }
58
59    /** Returns the class name without package. */
60    public static String JavaDoc getUnqualifiedClassName (Class JavaDoc cls) {
61       String JavaDoc name=cls.getName();
62       int lastDot=name.lastIndexOf(".");
63       if (lastDot>=0) {
64          name=name.substring(lastDot+1,name.length());
65       }
66       return name;
67    }
68
69    /**
70     * Returns the set of description for Start elements of given editor's graph.
71     * This description is written to the xml file.
72     * The description for a Start graph object contains of participant ID where
73     * start is placed in, the ID of activity that start points to, the relative
74     * position within participant, and indicator if transition from start
75     * object isself-routed or not.
76     *
77     * @param pe The editor.
78     * @return The set of descriptions of Start objects of given editor's graph.
79     */

80    public static Set getStartDescriptions (ProcessEditor pe) {
81       Set startDescriptions=new HashSet();
82       if (pe!=null && JaWEConfig.getInstance().getUseBubblesStatus()) {
83          WorkflowManager workflowManager=pe.getGraph().getWorkflowManager();
84          Set starts=workflowManager.getStarts();
85          // ******* start
86
if (starts.size()>0) {
87             Iterator it=starts.iterator();
88             while (it.hasNext()) {
89                Start start=(Start)it.next();
90                Set outTransitions=start.getOutgoingTransitions();
91                // ** participant ID
92
String JavaDoc startDescription=workflowManager.getParticipantID(start)+";";
93                // ** first activity ID
94
String JavaDoc ID="-1";
95                Transition t=null;
96                if (outTransitions.size()>0) {
97                   t=(Transition)outTransitions.toArray()[0];
98                   if (t!=null) {
99                      ID=t.getTargetActivity().get("Id").toString();
100                   }
101                }
102                startDescription+=(ID+";");
103                // ** position
104
Point pOffset=workflowManager.getOffset(start);
105                startDescription+=(String.valueOf(pOffset.x)+";");
106                startDescription+=(String.valueOf(pOffset.y)+";");
107                if (t!=null) {
108                   boolean isRouted=Utils.isRoutingTransition(t.getAttributes());
109                   startDescription+=(((isRouted) ?
110                                          (org.enhydra.jawe.xml.elements.Transition.SIMPLE_ROUTING) :
111                                          (org.enhydra.jawe.xml.elements.Transition.NO_ROUTING)));
112                }
113                startDescriptions.add(startDescription);
114             }
115          }
116       }
117       return startDescriptions;
118    }
119
120    /**
121     * Returns the set of descriptions for End elements of given editor's graph.
122     * This descriptions are written to the xml file.
123     * The description for an End graph object contains of participant ID where
124     * end is placed in, the ID of activity that points to end, the relative
125     * position within participant, and indicator if transition toward end is
126     * self-routed or not.
127     *
128     * @param pe The editor.
129     * @return The set of descriptions for End objects of given editor's graph.
130     */

131    public static Set getEndDescriptions (ProcessEditor pe) {
132       Set endDescriptions=new HashSet();
133
134       if (pe!=null && JaWEConfig.getInstance().getUseBubblesStatus()) {
135          WorkflowManager workflowManager=pe.getGraph().getWorkflowManager();
136          Set ends=workflowManager.getEnds();
137          if (ends.size()>0) {
138             Iterator it=ends.iterator();
139             while (it.hasNext()) {
140                End end=(End)it.next();
141                // ** participant ID
142
String JavaDoc endDescription=workflowManager.getParticipantID(end)+";";
143                // ** last activity ID
144
Set inTransitions=end.getIncomingTransitions();
145                String JavaDoc ID="-1";
146                Transition t=null;
147                if (inTransitions.size()>0) {
148                   t=(Transition)inTransitions.toArray()[0];
149                   if (t!=null) {
150                      ID=t.getSourceActivity().get("Id").toString();
151                   }
152                }
153                endDescription+=(ID+";");
154                // ** position
155
Point pOffset=workflowManager.getOffset(end);
156                endDescription+=(String.valueOf(pOffset.x)+";");
157                endDescription+=(String.valueOf(pOffset.y)+";");
158                if (t!=null) {
159                   boolean isRouted=Utils.isRoutingTransition(t.getAttributes());
160                   endDescription+=(((isRouted) ?
161                                        (org.enhydra.jawe.xml.elements.Transition.SIMPLE_ROUTING) :
162                                        (org.enhydra.jawe.xml.elements.Transition.NO_ROUTING)));
163                }
164                endDescriptions.add(endDescription);
165             }
166          }
167       }
168       return endDescriptions;
169    }
170
171    /**
172     * Returns the color parsed from the given string. The color can be given
173     * in three different string form:
174     * <ul>
175     * <li> using prefix Color, dot and wanted color, e.g. <b>Color.red</b>
176     * <li> using prefix SystemColor, dot and wanted color,
177     * e.g. <b>SystemColor.desktop</b>
178     * <li> using RGB like string, e.g. <b>R=124,G=213,B=12</b>
179     * </ul>
180     * @param col The string representation of wanted color.
181     * @return The color based on given string or null if incorrect
182     */

183    public static Color getColor (String JavaDoc col) {
184       Color c=null;
185       int dotInd=col.indexOf(".");
186       int r,g,b;
187       if (col.indexOf("Color")!=-1 && dotInd!=-1) {
188          try {
189             ClassLoader JavaDoc cl=JaWEConfig.class.getClassLoader();
190             Class JavaDoc cls=cl.loadClass("java.awt."+col.substring(0,dotInd));
191             Field f=cls.getField(col.substring(dotInd+1));
192             c=(Color)f.get(null);
193             c=new Color(c.getRed(),c.getGreen(),c.getBlue());
194          } catch (Exception JavaDoc ex) {}
195       } else {
196          try {
197             int i1=col.indexOf("R=");
198             if (i1==-1) i1=col.indexOf("r=");
199             int i1c=col.indexOf(",",i1+2);
200             int i2=col.indexOf("G=");
201             if (i2==-1) i2=col.indexOf("g=");
202             int i2c=col.indexOf(",",i2+2);
203             int i3=col.indexOf("B=");
204             if (i3==-1) i3=col.indexOf("b=");
205             if (i1!=-1 && i1c!=-1 && i2!=-1 && i2c!=-1 && i3!=-1 &&
206                    (i1c<i2) && (i2c<i3)) {
207                r=Integer.valueOf(col.substring(i1+2,i1c).trim()).intValue();
208                if (r<0) r=0;
209                if (r>255) r=255;
210                g=Integer.valueOf(col.substring(i2+2,i2c).trim()).intValue();
211                if (g<0) g=0;
212                if (g>255) g=255;
213                b=Integer.valueOf(col.substring(i3+2).trim()).intValue();
214                if (b<0) b=0;
215                if (b>255) b=255;
216                c=new Color(r,g,b);
217             }
218          } catch (Exception JavaDoc ex) {}
219       }
220       return c;
221    }
222
223    /**
224     * Returns the set of (XML) activities that have split or join.
225     * @param acts The activities graph objects that are checked if their
226     * XML object have split or join, depending on the second parameter.
227     * @param sOrJ if 0, activity is checked for split, otherwise it is
228     * checked for join
229     */

230    public static Set getSplitOrJoinActivities (Set acts,int sOrJ) {
231       Set sOrJactivities=new HashSet();
232       if (acts==null) return sOrJactivities;
233       Iterator it=acts.iterator();
234       while (it.hasNext()) {
235          Activity act=(Activity)it.next();
236          if (!(act instanceof Start) && !(act instanceof End)) {
237             Iterator iter;
238             if (sOrJ==0) {
239                iter=act.getOutgoingTransitions().iterator();
240             } else {
241                iter=act.getIncomingTransitions().iterator();
242             }
243             int noOfTrans=0;
244             while (iter.hasNext()) {
245                Transition tr = (Transition)iter.next();
246                org.enhydra.jawe.xml.elements.Transition t=
247                   (org.enhydra.jawe.xml.elements.Transition)tr.getUserObject();
248                if (t!=null && t.getFrom()!=null && t.getTo()!=null) {
249                   noOfTrans++;
250                }
251             }
252             if (noOfTrans>1) {
253                sOrJactivities.add(act);
254             }
255          }
256       }
257
258       return sOrJactivities;
259    }
260
261    //******************************** DEBUGGING STUFF ****************************
262
/** Used for debug only */
263    public static void printStrings(String JavaDoc[] s) {
264       if (s != null) {
265          for (int i=0; i<s.length; i++) {
266             System.out.println("String no "+i+" = "+s[i]);
267          }
268       }
269       else {
270          System.out.println("Passed string array is null !!!");
271       }
272    }
273    //**************************** END OF DEBUGGING STUFF *************************
274

275    public static boolean isRoutingTransition (Map attributes) {
276       Object JavaDoc routing=GraphConstants.getRouting(attributes);
277       if (routing!=null && !(routing instanceof NoRouting)) {
278          return true;
279       } else {
280          return false;
281       }
282    }
283
284    public static boolean isCircularTransition (Map attributes) {
285       int style=GraphConstants.getLineStyle(attributes);
286       if (style==GraphConstants.STYLE_BEZIER) {
287          return true;
288       } else {
289          return false;
290       }
291    }
292
293    public static void center (Window w,int minXDiffFromMax,int minYDiffFromMax) {
294       w.pack();
295
296       // make dialog smaller if needed, and center it
297
//Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
298
Dimension screenSize =
299          GraphicsEnvironment
300          .getLocalGraphicsEnvironment()
301          .getDefaultScreenDevice()
302          .getDefaultConfiguration()
303          .getBounds()
304          .getSize();
305
306
307       Dimension windowSize = w.getPreferredSize();
308       if (windowSize.width>screenSize.width-minXDiffFromMax) {
309          windowSize.width=screenSize.width-minXDiffFromMax;
310       }
311       if (windowSize.height>screenSize.height-minYDiffFromMax) {
312          windowSize.height=screenSize.height-minYDiffFromMax;
313       }
314       w.setSize(windowSize);
315       w.setLocation(screenSize.width/2 - (windowSize.width/2),
316                     screenSize.height/2 - (windowSize.height/2));
317    }
318
319    public static java.util.List JavaDoc findPropertyFiles () {
320       java.util.List JavaDoc pfs=new ArrayList();
321
322       URL JavaDoc u=Utils.class.getClassLoader().getResource("org/enhydra/jawe/resources");
323       File path=null;
324       if (u!=null) {
325          path=new File(u.getFile());
326       }
327       // if folder exists and realy is a folder but not file
328
if (path!=null && path.exists() && path.isDirectory()) {
329          // getting all .property files within folder
330
pfs.addAll(Arrays.asList(path.list(new PFFilter())));
331       } else {
332          JarFile jfile=null;
333          try {
334             String JavaDoc jp="org/enhydra/jawe/resources/JaWE.properties";
335             u=Utils.class.getClassLoader().getResource(jp);
336             String JavaDoc jarPath=u.getFile().substring(0,u.getFile().length()-jp.length()-2);
337             jarPath=jarPath.substring(5);
338             jfile=new JarFile(jarPath,false);
339             // get all entries
340
Enumeration e = jfile.entries();
341             // loop through entries and find appropriate ones
342
while (e.hasMoreElements()) {
343                try {
344                   ZipEntry entry = (ZipEntry)e.nextElement();
345                   String JavaDoc entryname = entry.getName();
346                   // entry must end with '.properties'
347
if (entryname.indexOf(JaWEConstants.APPLICATION_NAME)!=-1 && entryname.endsWith(".properties")) {
348                      pfs.add(entryname);
349                   }
350                } catch (Exception JavaDoc ex) {}
351             }
352          } catch (Exception JavaDoc ex) {}
353       }
354
355       // if there are no property files, try to find the default ones distributed
356
// with JaWE
357
if (pfs.size()==0) {
358          u=Utils.class.getClassLoader().getResource("org/enhydra/jawe/resources/JaWE.properties");
359          if (u!=null) {
360             pfs.add("JaWE.properties");
361          }
362          u=Utils.class.getClassLoader().getResource("org/enhydra/jawe/resources/JaWE_de.properties");
363          if (u!=null) {
364             pfs.add("JaWE_de.properties");
365          }
366          u=Utils.class.getClassLoader().getResource("org/enhydra/jawe/resources/JaWE_fr.properties");
367          if (u!=null) {
368             pfs.add("JaWE_fr.properties");
369          }
370          u=Utils.class.getClassLoader().getResource("org/enhydra/jawe/resources/JaWE_sh.properties");
371          if (u!=null) {
372             pfs.add("JaWE_sh.properties");
373          }
374       }
375       java.util.List JavaDoc pfLocales=new ArrayList();
376       if (pfs.size()>0) {
377          // adding default locale (for default property file)
378
pfLocales.add(new PFLocale());
379          for(int i=0; i<pfs.size(); i++) {
380             String JavaDoc propFile=(String JavaDoc)pfs.get(i);
381             int p1=propFile.indexOf(JaWEConstants.APPLICATION_NAME)+JaWEConstants.APPLICATION_NAME.length();
382             boolean isDefault=!propFile.substring(p1,p1+1).equals("_");
383             if (!isDefault) {
384                PFLocale pfl=PFLocale.createPFLocale(
385                   propFile.substring(p1+1,propFile.length()-".properties".length()));
386                if (pfl!=null) {
387                   pfLocales.add(pfl);
388                }
389             }
390          }
391       }
392       return pfLocales;
393    }
394
395    public static boolean hasCircularTransitions (Set transitions) {
396       Iterator it=transitions.iterator();
397       while (it.hasNext()) {
398          Transition t=(Transition)it.next();
399          Object JavaDoc source = ((DefaultPort)(t.getSource())).getParent();
400          Object JavaDoc target = ((DefaultPort)(t.getTarget())).getParent();
401          if (source.equals(target)) return true;
402       }
403       return false;
404    }
405
406    // Useful only if JaWE is set to work without start/end bubbles
407
public static boolean isStartingActivity (Activity act) {
408       Set trans=act.getIncomingTransitions();
409       if (trans.size()==0 || (trans.size()==1 && Utils.hasCircularTransitions(trans))) {
410          return true;
411       }
412       return false;
413    }
414
415    // Useful only if JaWE is set to work without start/end bubbles
416
public static boolean isEndingActivity (Activity act) {
417       Set trans=act.getNonExceptionalOutgoingTransitions();
418       if (trans.size()==0 || (trans.size()==1 && Utils.hasCircularTransitions(trans))) {
419          return true;
420       }
421       return false;
422    }
423
424
425    // Useful only if JaWE is set to work with start/end bubbles
426
public static boolean hasConnectedStartBubble (Activity act) {
427       Set trans=act.getIncomingTransitions();
428       if (trans.size()==1 || trans.size()==2) {
429          Object JavaDoc[] trnsArr=trans.toArray();
430          if((((Transition)trnsArr[0]).getSourceActivity() instanceof Start) ||
431                (trans.size()==2 && ((Transition)trnsArr[1]).getSourceActivity() instanceof Start)) {
432             return true;
433          }
434       }
435       return false;
436    }
437
438    // Useful only if JaWE is set to work with start/end bubbles
439
public static boolean hasConnectedEndBubble (Activity act) {
440       Set trans=act.getNonExceptionalOutgoingTransitions();
441       if (trans.size()==1 || trans.size()==2) {
442          Object JavaDoc[] trnsArr=trans.toArray();
443          if((((Transition)trnsArr[0]).getTargetActivity() instanceof End) ||
444                (trans.size()==2 && ((Transition)trnsArr[1]).getTargetActivity() instanceof End)) {
445             return true;
446          }
447       }
448       return false;
449    }
450
451    public static void removeBubblesExtAttribs (Package JavaDoc pkg) {
452       WorkflowProcesses wprocs=(WorkflowProcesses)pkg.get("WorkflowProcesses");
453       Iterator wps=wprocs.toCollection().iterator();
454       while (wps.hasNext()) {
455          WorkflowProcess wp=(WorkflowProcess)wps.next();
456          wp.getEndDescriptions().clear();
457          wp.getStartDescriptions().clear();
458          Activities activities=(Activities)wp.get("Activities");
459          Iterator acts=activities.toCollection().iterator();
460          while (acts.hasNext()) {
461             org.enhydra.jawe.xml.elements.Activity act=
462                (org.enhydra.jawe.xml.elements.Activity)acts.next();
463             act.getEndDescriptions().clear();
464             act.getStartDescriptions().clear();
465          }
466          ActivitySets asets=(ActivitySets)wp.get("ActivitySets");
467          Iterator ass=asets.toCollection().iterator();
468          while (ass.hasNext()) {
469             ActivitySet as=(ActivitySet)ass.next();
470             activities=(Activities)wp.get("Activities");
471             acts=activities.toCollection().iterator();
472             while (acts.hasNext()) {
473                org.enhydra.jawe.xml.elements.Activity act=
474                   (org.enhydra.jawe.xml.elements.Activity)acts.next();
475                act.getEndDescriptions().clear();
476                act.getStartDescriptions().clear();
477             }
478
479          }
480       }
481     }
482
483 }
484
485 class PFFilter implements FilenameFilter {
486    String JavaDoc pfStr=".properties";
487
488    public boolean accept(File dir, String JavaDoc name) {
489       String JavaDoc f = new File(name).getName();
490       int fi=f.indexOf(JaWEConstants.APPLICATION_NAME);
491       int li=f.lastIndexOf(JaWEConstants.APPLICATION_NAME);
492       return (fi!=-1 && fi==0 && fi==li && f.endsWith(pfStr));
493    }
494 }
495
Popular Tags