KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > shark > Shark


1 package org.enhydra.shark;
2
3 import org.enhydra.shark.api.*;
4
5 import java.io.File JavaDoc;
6 import java.io.FileInputStream JavaDoc;
7 import java.io.InputStream JavaDoc;
8 import java.net.URL JavaDoc;
9 import java.net.URLConnection JavaDoc;
10 import java.util.Iterator JavaDoc;
11 import java.util.List JavaDoc;
12 import java.util.Map JavaDoc;
13 import java.util.Properties JavaDoc;
14 import org.enhydra.shark.api.client.wfbase.BaseException;
15 import org.enhydra.shark.api.client.wfservice.AdminInterface;
16 import org.enhydra.shark.api.client.wfservice.ExpressionBuilderManager;
17 import org.enhydra.shark.api.client.wfservice.RepositoryMgr;
18 import org.enhydra.shark.api.client.wfservice.SharkConnection;
19 import org.enhydra.shark.api.client.wfservice.SharkInterface;
20 import org.enhydra.shark.api.common.SharkConstants;
21 import org.enhydra.shark.api.internal.instancepersistence.PersistentManagerInterface;
22 import org.enhydra.shark.api.internal.instancepersistence.ProcessPersistenceInterface;
23 import org.enhydra.shark.api.internal.instancepersistence.ResourcePersistenceInterface;
24 import org.enhydra.shark.api.internal.limitagent.LimitAgentManager;
25 import org.enhydra.shark.api.internal.working.WfActivityInternal;
26 import org.enhydra.shark.api.internal.working.WfProcessInternal;
27 import org.enhydra.shark.utilities.MiscUtilities;
28
29 /**
30  * The main engine class. The client application first has to call one of
31  * the static methods configure() (which will initialize shark), and then
32  * static getInstance() method of this class to get one and only one instance
33  * of this class. After that, clients can call other methods for getting
34  * appropriate interfaces.
35  *
36  * @author Sasa Bojanic
37  * @author Vladimir Puskas
38  */

39 public final class Shark implements SharkInterface {
40
41    private static final String JavaDoc initCachesBoundary=",";
42    private static final String JavaDoc initAllCachesString="*";
43
44    private static final String JavaDoc defaultLogChannel="Shark";
45
46    private static boolean isConfigured=false;
47    // the one and only instance of this class
48
private static Shark shark;
49
50    static {
51       shark=new Shark();
52    }
53
54    //////////////////////////////////////////////////////////////////
55
// Configuration methods
56
//////////////////////////////////////////////////////////////////
57
public static void configure (Properties JavaDoc props) {
58       if (isConfigured) {
59          SharkEngineManager.getInstance().getCallbackUtilities().info(
60             "Trying to configure shark instance that is already configured !!!");
61          return;
62       }
63       if (props==null) {
64          throw new RootError("Shark need to be configured properly - given Poperties have null value!!!");
65       }
66       configureFromJar();
67       adjustSharkProperties(props);
68       isConfigured=true;
69       shark.init();
70    }
71
72    public static void configure (String JavaDoc filePath) {
73       if (isConfigured) {
74          SharkEngineManager.getInstance().getCallbackUtilities().info(
75             "Trying to configure shark instance that is already configured !!!");
76          return;
77       }
78       if (filePath==null) {
79          throw new RootError("Shark need to be configured properly - given path to configuration file is null!!!");
80       }
81       File JavaDoc config=new File JavaDoc(filePath);
82       Shark.configure(config);
83    }
84
85    public static void configure (File JavaDoc configFile) {
86       if (isConfigured) {
87          SharkEngineManager.getInstance().getCallbackUtilities().info(
88             "Trying to configure shark instance that is already configured !!!");
89          return;
90       }
91       if (configFile==null) {
92          throw new RootError("Shark need to be configured properly - given configuration file is null!!!");
93       }
94       if (!configFile.isAbsolute()) {
95          configFile=configFile.getAbsoluteFile();
96       }
97       if (configFile.exists()) {
98          configureFromJar();
99          FileInputStream JavaDoc fis=null;
100          try {
101             fis=new FileInputStream JavaDoc(configFile);
102             Properties JavaDoc props=new Properties JavaDoc();
103             props.load(fis);
104             fis.close();
105             adjustSharkProperties(props);
106          } catch (Exception JavaDoc ex) {
107             throw new RootError ("Something went wrong while reading of configuration from the file!!!",ex);
108          }
109          try {
110             shark.properties.put(SharkConstants.ROOT_DIRECTORY_PATH_PROP,
111                                  configFile.getParentFile().getCanonicalPath());
112           } catch (Exception JavaDoc ex) {
113             shark.properties.put(SharkConstants.ROOT_DIRECTORY_PATH_PROP,
114                                  configFile.getParentFile().getAbsolutePath());
115          }
116       } else {
117          throw new RootError("Shark need to be configured properly - configuration file "+configFile+" does not exist!!!");
118       }
119       isConfigured=true;
120       shark.init();
121    }
122
123    public static void configure () {
124       if (isConfigured) {
125          SharkEngineManager.getInstance().getCallbackUtilities().info(
126             "Trying to configure shark instance that is already configured !!!");
127          return;
128       }
129       configureFromJar();
130       isConfigured=true;
131       shark.init();
132    }
133
134    public static Shark getInstance () {
135       if (!isConfigured) {
136          throw new RootError("Can't use Shark - it is not configured !!!");
137       }
138       return shark;
139    }
140
141    private Properties JavaDoc properties;
142    private ExpressionBuilderManager expressionBuilderManager;
143
144    private Shark () {
145    }
146
147    //////////////////////////////////////////////////////////////////
148
// SharkInterface API implementation
149
//////////////////////////////////////////////////////////////////
150
public AdminInterface getAdminInterface () {
151       return SharkEngineManager.getInstance().getObjectFactory().createAdminInterface();
152    }
153
154    public RepositoryMgr getRepositoryManager () {
155       return SharkEngineManager.getInstance().getObjectFactory().createRepositoryManager();
156    }
157
158    public SharkConnection getSharkConnection () {
159       return SharkEngineManager.getInstance().getObjectFactory().createSharkConnection();
160    }
161
162    public ExpressionBuilderManager getExpressionBuilderManager () {
163       if (expressionBuilderManager==null) {
164          String JavaDoc ebmClassName = properties.getProperty
165          ("ExpressionBuilderManagerClassName",
166           "org.enhydra.shark.ExpressionBuilderMgr");
167    
168          ClassLoader JavaDoc cl=getClass().getClassLoader();
169    
170          try {
171             expressionBuilderManager=(ExpressionBuilderManager)cl.loadClass(ebmClassName).newInstance();
172             SharkEngineManager.getInstance().getCallbackUtilities().info("Shark -> Working with '"+ebmClassName+"' implementation of ExpressionBuilderManager API");
173          } catch (Throwable JavaDoc ex) {
174             if (ebmClassName==null || ebmClassName.trim().equals("")) {
175                SharkEngineManager.getInstance().getCallbackUtilities().info("Shark -> Working without ExpressionBuilderManager implementation.");
176             } else if (expressionBuilderManager==null) {
177                SharkEngineManager.getInstance().getCallbackUtilities().info("Shark -> Can't find ExpressionBuilderManager class '"+ebmClassName+"' in classpath!");
178             }
179          }
180       }
181
182       return expressionBuilderManager;
183    }
184    
185    public SharkTransaction createTransaction() throws TransactionException {
186       try {
187          return SharkUtilities.createTransaction();
188       } catch (Exception JavaDoc ex) {
189          throw new TransactionException("Can't create SharkTransaction",ex);
190       }
191    }
192
193    public ParticipantMappingTransaction createParticipantMappingTransaction() throws TransactionException {
194       try {
195          return SharkEngineManager.getInstance().getParticipantMapPersistenceManager().getParticipantMappingTransaction();
196       } catch (Exception JavaDoc ex) {
197          throw new TransactionException("Can't create ParticipantMappingTransaction",ex);
198       }
199    }
200
201    public ApplicationMappingTransaction createApplicationMappingTransaction() throws TransactionException {
202       try {
203          return SharkEngineManager.getInstance().getApplicationMapPersistenceManager().getApplicationMappingTransaction();
204       } catch (Exception JavaDoc ex) {
205          throw new TransactionException("Can't create ApplicationMappingTransaction",ex);
206       }
207    }
208
209    public ScriptMappingTransaction createScriptMappingTransaction() throws TransactionException {
210       try {
211          return SharkEngineManager.getInstance().getScriptMapPersistenceManager().getScriptMappingTransaction();
212       } catch (Exception JavaDoc ex) {
213          throw new TransactionException("Can't create ScriptMappingTransaction",ex);
214       }
215    }
216
217    public UserTransaction createUserTransaction() throws TransactionException {
218       try {
219          return SharkEngineManager.getInstance().getUserTransactionFactory().createTransaction();
220       } catch (Exception JavaDoc ex) {
221          throw new TransactionException("Can't create UserTransaction",ex);
222       }
223    }
224
225    public RepositoryTransaction createRepositoryTransaction() throws TransactionException {
226       try {
227          return SharkEngineManager.getInstance().getRepositoryPersistenceManager().createTransaction();
228       } catch (Exception JavaDoc ex) {
229          throw new TransactionException("Can't create UserTransaction",ex);
230       }
231    }
232
233    public void unlockProcesses (SharkTransaction t) throws TransactionException {
234       SharkUtilities.unlock(t);
235    }
236
237    public void emptyCaches (SharkTransaction t) {
238       SharkUtilities.emptyCaches(t);
239    }
240
241    public Properties JavaDoc getProperties () {
242       Properties JavaDoc copy=new Properties JavaDoc();
243       Iterator JavaDoc it=properties.entrySet().iterator();
244       while (it.hasNext()) {
245          Map.Entry JavaDoc me=(Map.Entry JavaDoc)it.next();
246          copy.setProperty((String JavaDoc)me.getKey(),(String JavaDoc)me.getValue());
247       }
248       return copy;
249    }
250
251    //////////////////////////////////////////////////////////////////
252
// Utility methods
253
//////////////////////////////////////////////////////////////////
254
public boolean validateUser (String JavaDoc username,String JavaDoc pwd) {
255       try {
256          return SharkUtilities.validateUser(username,pwd);
257       } catch (Exception JavaDoc ex) {
258          return false;
259       }
260    }
261
262    // Initialization methods
263
//////////////////////////////////////////////////////////////////
264

265    private static void configureFromJar () {
266       String JavaDoc rootDirectoryPath=System.getProperty("user.dir");
267       try {
268          //URL u=Shark.class.getClassLoader().getResource("Shark.conf.forJar");
269
//InputStream is=(InputStream)u.getContent();
270
URL JavaDoc u=Shark.class.getClassLoader().getResource("Shark.conf.forJar");
271          URLConnection JavaDoc urlConnection = u.openConnection();
272          InputStream JavaDoc is=urlConnection.getInputStream();
273
274          shark.properties=new Properties JavaDoc();
275          shark.properties.load(is);
276          shark.properties.put(SharkConstants.ROOT_DIRECTORY_PATH_PROP,rootDirectoryPath);
277       } catch (Exception JavaDoc ex) {
278          throw new RootError("Shark need to be configured properly - Can't read Shark's default configuration from JAR!!!",ex);
279       }
280    }
281
282    private static void adjustSharkProperties (Properties JavaDoc external) {
283       Iterator JavaDoc it=external.entrySet().iterator();
284       while (it.hasNext()) {
285          Map.Entry JavaDoc me=(Map.Entry JavaDoc)it.next();
286          String JavaDoc key=(String JavaDoc)me.getKey();
287          String JavaDoc val=(String JavaDoc)me.getValue();
288          shark.properties.setProperty(key,val);
289       }
290    }
291
292    private void init () {
293       long tStart=System.currentTimeMillis();
294       System.out.println("SharkEngineManager -> Shark engine is being initialized ...");
295
296       // this is where the singlton class of SharkEngineManager is created
297
SharkEngineManager.getInstance().init(properties);
298
299       shark.initCaches();
300       shark.reevaluateAssignments();
301       shark.initLimitManager();
302
303       /*System.setProperty("user.dir",shark
304                             .getProperties()
305        .getProperty(SharkConstants.ROOT_DIRECTORY_PATH_PROP));*/

306       long tEnd=System.currentTimeMillis();
307       System.out.println("Shark -> shark engine initialization is finished, it lasted "+MiscUtilities.getTimeDiff(tStart,tEnd));
308       System.out.println("Shark -> "+properties.getProperty("enginename","Shark")+" ready and waiting ...");
309    }
310
311    // init caches
312
private void initCaches () {
313       String JavaDoc initPCS=properties.getProperty("Cache.InitProcessCacheString","");
314       String JavaDoc initRCS=properties.getProperty("Cache.InitResourceCacheString","");
315       SharkTransaction t = null;
316       try {
317          t = SharkUtilities.createTransaction();
318          if (!initPCS.trim().equals("")) {
319             SharkEngineManager.getInstance().getCallbackUtilities().info(
320                "Initializing Process cache using string "+initPCS);
321             if (initPCS.trim().equalsIgnoreCase(initAllCachesString)) {
322                List JavaDoc l=SharkEngineManager.
323                   getInstance().
324                   getInstancePersistenceManager().
325                   getAllProcesses(t);
326                Iterator JavaDoc it=l.iterator();
327                while (it.hasNext()) {
328                   ProcessPersistenceInterface po=(ProcessPersistenceInterface)it.next();
329                   // this creates and puts process into cache
330
SharkEngineManager.getInstance().getObjectFactory().createProcess(po);
331                }
332             } else {
333                String JavaDoc[] procIds=MiscUtilities.tokenize(initPCS.trim(),initCachesBoundary);
334                if (procIds!=null) {
335                   for (int i=0; i<procIds.length; i++) {
336                      // this gets process from db and puts it into cache
337
Object JavaDoc proc=SharkUtilities.getProcess(t,procIds[i]);
338                      if (proc==null) {
339                         SharkEngineManager.getInstance().getCallbackUtilities().info(
340                            "Process cache initialization - process with Id="+procIds[i]+" does not exist");
341                      }
342                   }
343                }
344             }
345          }
346
347          if (!initRCS.trim().equals("")) {
348             SharkEngineManager.getInstance().getCallbackUtilities().info(
349                "Initializing Resource cache using string "+initRCS);
350             if (initRCS.equalsIgnoreCase(initAllCachesString)) {
351                List JavaDoc l=SharkEngineManager.
352                   getInstance().
353                   getInstancePersistenceManager().
354                   getAllResources(t);
355                Iterator JavaDoc it=l.iterator();
356                while (it.hasNext()) {
357                   // this creates and puts resources into cache
358
ResourcePersistenceInterface po=(ResourcePersistenceInterface)it.next();
359                   SharkEngineManager.getInstance().getObjectFactory().createResource(po);
360                }
361             } else {
362                String JavaDoc[] resIds=MiscUtilities.tokenize(initRCS.trim(),initCachesBoundary);
363                if (resIds!=null) {
364                   for (int i=0; i<resIds.length; i++) {
365                      // this gets resource from db and puts it into cache
366
Object JavaDoc res=SharkUtilities.getResource(t,resIds[i]);
367                      if (res==null) {
368                         SharkEngineManager.getInstance().getCallbackUtilities().info(
369                            "Resource cache initialization - resource with username="+resIds[i]+" does not exist");
370                      }
371                   }
372                }
373             }
374          }
375          SharkUtilities.restorePackages();
376          //SharkUtilities.commitTransaction(t);
377
} catch (Throwable JavaDoc e) {
378          SharkEngineManager.getInstance().getCallbackUtilities().error(
379             "Problem while initializing caches !!!");
380          e.printStackTrace();
381          //try {SharkUtilities.rollbackTransaction(t);} catch (Exception ex) {}
382
} finally {
383          try {
384             SharkUtilities.releaseTransaction(t);
385          } catch (BaseException e) {}
386       }
387    }
388
389    // reevaluate assignments
390
private void reevaluateAssignments () {
391       boolean reeval=new Boolean JavaDoc(properties.getProperty("Assignments.InitialReevaluation","false")).booleanValue();
392       if (!reeval) return;
393       SharkTransaction t = null;
394       try {
395          t = SharkUtilities.createTransaction();
396          SharkUtilities.reevaluateAssignments(t);
397          SharkUtilities.commitTransaction(t);
398       } catch (Throwable JavaDoc e) {
399          SharkEngineManager
400             .getInstance()
401             .getCallbackUtilities()
402             .error("Problem while reevaluating assignments !!!");
403          try {
404             SharkUtilities.rollbackTransaction(t,new RootException(e));
405          } catch (Exception JavaDoc ex) {}
406       } finally {
407          try {
408             SharkUtilities.releaseTransaction(t);
409          } catch (BaseException e) {}
410       }
411    }
412
413    private void initLimitManager() {
414       SharkTransaction t = null;
415       LimitAgentManager lam = SharkEngineManager
416          .getInstance()
417          .getLimitAgentManager();
418       PersistentManagerInterface pmi = SharkEngineManager
419          .getInstance()
420          .getInstancePersistenceManager();
421
422       if (null != lam) {
423          try {
424             t = SharkUtilities.createTransaction();
425             for (Iterator JavaDoc processes = pmi.getAllProcesses(t).iterator();
426                  processes.hasNext();) {
427                ProcessPersistenceInterface po =
428                   ((ProcessPersistenceInterface)processes.next());
429
430                if (!po.getState().startsWith(SharkConstants.STATEPREFIX_CLOSED)) {
431                   WfProcessInternal theProcess = SharkUtilities.getProcess(t,po.getId());
432                   theProcess.activateLimitAgent(t);
433                   for (Iterator JavaDoc activeActivities = theProcess.getActiveActivities(t).iterator();
434                        activeActivities.hasNext();){
435                      ((WfActivityInternal)activeActivities.next()).activateLimitAgent(t);
436                   }
437                }
438             }
439          } catch (Throwable JavaDoc e) {
440             e.printStackTrace();
441             SharkEngineManager
442                .getInstance()
443                .getCallbackUtilities()
444                .error("Limit agent manager initialization didn't work");
445          } finally {
446             try { SharkUtilities.releaseTransaction(t);}
447             catch (BaseException e) {}
448          }
449       }
450    }
451
452 }
453
454
Popular Tags