KickJava   Java API By Example, From Geeks To Geeks.

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


1 package org.enhydra.shark;
2
3 import java.io.ByteArrayOutputStream JavaDoc;
4 import java.util.ArrayList JavaDoc;
5 import java.util.Collection JavaDoc;
6 import java.util.Collections JavaDoc;
7 import java.util.HashMap JavaDoc;
8 import java.util.HashSet JavaDoc;
9 import java.util.Iterator JavaDoc;
10 import java.util.List JavaDoc;
11 import java.util.Map JavaDoc;
12 import java.util.Set JavaDoc;
13
14 import org.enhydra.shark.api.ApplicationMappingTransaction;
15 import org.enhydra.shark.api.ParticipantMappingTransaction;
16 import org.enhydra.shark.api.RepositoryTransaction;
17 import org.enhydra.shark.api.RootException;
18 import org.enhydra.shark.api.SharkTransaction;
19 import org.enhydra.shark.api.client.wfbase.BaseException;
20 import org.enhydra.shark.api.client.wfservice.ExternalPackageInvalid;
21 import org.enhydra.shark.api.client.wfservice.PackageAdministration;
22 import org.enhydra.shark.api.client.wfservice.PackageHasActiveProcesses;
23 import org.enhydra.shark.api.client.wfservice.PackageInUse;
24 import org.enhydra.shark.api.client.wfservice.PackageInvalid;
25 import org.enhydra.shark.api.client.wfservice.PackageUpdateNotAllowed;
26 import org.enhydra.shark.api.common.SharkConstants;
27 import org.enhydra.shark.api.internal.appmappersistence.ApplicationMappingManager;
28 import org.enhydra.shark.api.internal.partmappersistence.ParticipantMappingManager;
29 import org.enhydra.shark.api.internal.repositorypersistence.RepositoryPersistenceManager;
30 import org.enhydra.shark.api.internal.working.CallbackUtilities;
31 import org.enhydra.shark.api.internal.working.WfProcessMgrInternal;
32 import org.enhydra.shark.xpdl.Version;
33 import org.enhydra.shark.xpdl.XMLInterface;
34 import org.enhydra.shark.xpdl.XMLInterfaceForJDK13;
35 import org.enhydra.shark.xpdl.XMLUtil;
36 import org.enhydra.shark.xpdl.elements.Application;
37 import org.enhydra.shark.xpdl.elements.Applications;
38 import org.enhydra.shark.xpdl.elements.ExternalPackage;
39 import org.enhydra.shark.xpdl.elements.Package;
40 import org.enhydra.shark.xpdl.elements.Participant;
41 import org.enhydra.shark.xpdl.elements.Participants;
42 import org.enhydra.shark.xpdl.elements.WorkflowProcess;
43 import org.enhydra.shark.xpdl.elements.WorkflowProcesses;
44
45 /**
46  * @author Nenad Stefanovic, Sasa Bojanic
47  *
48  */

49 public class PackageAdmin implements PackageAdministration {
50
51    private XMLInterface xmlInterface=SharkEngineManager.getInstance().getXMLInterface();
52    private CallbackUtilities cus;
53    private RepositoryPersistenceManager repMgr;
54    private String JavaDoc userId="Unknown";
55
56    protected PackageAdmin () {
57       this.cus=SharkEngineManager.getInstance().getCallbackUtilities();
58       this.repMgr=SharkEngineManager.getInstance().getRepositoryPersistenceManager();
59    }
60
61    public void connect (String JavaDoc userId) {
62       this.userId=userId;
63    }
64
65    public String JavaDoc[] getOpenedPackageIds () throws BaseException {
66       String JavaDoc[] ret = null;
67       RepositoryTransaction t = null;
68       try {
69          t = SharkUtilities.createRepositoryTransaction();
70          ret = getOpenedPackageIds(t);
71          //SharkUtilities.commitRepositoryTransaction(t);
72
} catch (RootException e) {
73          //SharkUtilities.rollbackRepositoryTransaction(t);
74
if (e instanceof BaseException)
75             throw (BaseException)e;
76          else
77             throw new BaseException(e);
78       } finally {
79          SharkUtilities.releaseRepositoryTransaction(t);
80       }
81       return ret;
82    }
83
84    public String JavaDoc[] getOpenedPackageIds (RepositoryTransaction t) throws BaseException {
85       try {
86          List JavaDoc pkgIds=repMgr.getExistingXPDLIds(t);
87          Collections.sort(pkgIds);
88          String JavaDoc[] ret=new String JavaDoc[pkgIds.size()];
89          pkgIds.toArray(ret);
90          return ret;
91       } catch (Exception JavaDoc ex) {
92          throw new BaseException(ex);
93       }
94    }
95
96    public String JavaDoc[] getPackageVersions (String JavaDoc pkgId) throws BaseException {
97       String JavaDoc[] ret = null;
98       RepositoryTransaction t = null;
99       try {
100          t = SharkUtilities.createRepositoryTransaction();
101          ret = getPackageVersions(t,pkgId);
102          //SharkUtilities.commitRepositoryTransaction(t);
103
} catch (RootException e) {
104          //SharkUtilities.rollbackRepositoryTransaction(t);
105
if (e instanceof BaseException)
106             throw (BaseException)e;
107          else
108             throw new BaseException(e);
109       } finally {
110          SharkUtilities.releaseRepositoryTransaction(t);
111       }
112       return ret;
113    }
114
115    public String JavaDoc[] getPackageVersions (RepositoryTransaction t,String JavaDoc pkgId) throws BaseException {
116       try {
117          List JavaDoc pkgVers=repMgr.getXPDLVersions(t,pkgId);
118          Collections.sort(pkgVers);
119          String JavaDoc[] ret=new String JavaDoc[pkgVers.size()];
120          pkgVers.toArray(ret);
121          return ret;
122       } catch (Exception JavaDoc ex) {
123          throw new BaseException(ex);
124       }
125    }
126
127    public boolean isPackageOpened (String JavaDoc pkgId) throws BaseException {
128       boolean ret = false;
129       RepositoryTransaction t = null;
130       try {
131          t = SharkUtilities.createRepositoryTransaction();
132          ret = isPackageOpened(t,pkgId);
133          //SharkUtilities.commitRepositoryTransaction(t);
134
} catch (RootException e) {
135          //SharkUtilities.rollbackRepositoryTransaction(t);
136
if (e instanceof BaseException)
137             throw (BaseException)e;
138          else
139             throw new BaseException(e);
140       } finally {
141          SharkUtilities.releaseRepositoryTransaction(t);
142       }
143       return ret;
144    }
145
146    public boolean isPackageOpened (RepositoryTransaction t,String JavaDoc pkgId) throws BaseException {
147       try {
148          return repMgr.doesXPDLExist(t,pkgId);
149       } catch (Exception JavaDoc ex) {
150          throw new BaseException(ex);
151       }
152    }
153
154    public byte[] getPackageContent (String JavaDoc pkgId) throws BaseException {
155       byte[] ret = null;
156       RepositoryTransaction t = null;
157       try {
158          t = SharkUtilities.createRepositoryTransaction();
159          ret = getPackageContent(t,pkgId);
160          //SharkUtilities.commitRepositoryTransaction(t);
161
} catch (RootException e) {
162          //SharkUtilities.rollbackRepositoryTransaction(t);
163
if (e instanceof BaseException)
164             throw (BaseException)e;
165          else
166             throw new BaseException(e);
167       } finally {
168          SharkUtilities.releaseRepositoryTransaction(t);
169       }
170       return ret;
171    }
172
173    public byte[] getPackageContent (RepositoryTransaction t,String JavaDoc pkgId) throws BaseException {
174       try {
175          return convertSharkPackageContentXPDLByteArray(repMgr.getSerializedXPDLObject(t,pkgId));
176       } catch (Throwable JavaDoc ex) {
177          ex.printStackTrace();
178          throw new BaseException(ex);
179       }
180    }
181
182    public byte[] getPackageContent (String JavaDoc pkgId,String JavaDoc pkgVer) throws BaseException {
183       byte[] ret = null;
184       RepositoryTransaction t = null;
185       try {
186          t = SharkUtilities.createRepositoryTransaction();
187          ret = getPackageContent(t,pkgId,pkgVer);
188          //SharkUtilities.commitRepositoryTransaction(t);
189
} catch (RootException e) {
190          //SharkUtilities.rollbackRepositoryTransaction(t);
191
if (e instanceof BaseException)
192             throw (BaseException)e;
193          else
194             throw new BaseException(e);
195       } finally {
196          SharkUtilities.releaseRepositoryTransaction(t);
197       }
198       return ret;
199    }
200
201    public byte[] getPackageContent (RepositoryTransaction t,String JavaDoc pkgId,String JavaDoc pkgVer) throws BaseException {
202       try {
203          return convertSharkPackageContentXPDLByteArray(repMgr.getSerializedXPDLObject(t,pkgId,pkgVer));
204       } catch (Throwable JavaDoc ex) {
205          ex.printStackTrace();
206          throw new BaseException(ex);
207       }
208    }
209
210    public String JavaDoc getCurrentPackageVersion (String JavaDoc pkgId) throws BaseException {
211       String JavaDoc ret = null;
212       RepositoryTransaction t = null;
213       try {
214          t = SharkUtilities.createRepositoryTransaction();
215          ret = getCurrentPackageVersion(t,pkgId);
216          //SharkUtilities.commitRepositoryTransaction(t);
217
} catch (RootException e) {
218          //SharkUtilities.rollbackRepositoryTransaction(t);
219
if (e instanceof BaseException)
220             throw (BaseException)e;
221          else
222             throw new BaseException(e);
223       } finally {
224          SharkUtilities.releaseRepositoryTransaction(t);
225       }
226       return ret;
227    }
228
229    public String JavaDoc getCurrentPackageVersion (RepositoryTransaction t,String JavaDoc pkgId) throws BaseException {
230       try {
231          return repMgr.getCurrentVersion(t,pkgId);
232       } catch (Exception JavaDoc ex) {
233          throw new BaseException(ex);
234       }
235    }
236
237    public String JavaDoc openPackage (String JavaDoc relativePath) throws BaseException, PackageInvalid, ExternalPackageInvalid {
238       String JavaDoc ret=null;
239       RepositoryTransaction t = null;
240       try {
241          t = SharkUtilities.createRepositoryTransaction();
242          ret=openPackage(t,relativePath);
243          SharkUtilities.commitRepositoryTransaction(t);
244       } catch (RootException e) {
245          SharkUtilities.rollbackRepositoryTransaction(t,e);
246          if (e instanceof PackageInvalid)
247             throw (PackageInvalid)e;
248          else if (e instanceof ExternalPackageInvalid)
249             throw (ExternalPackageInvalid)e;
250          else if (e instanceof BaseException)
251             throw (BaseException)e;
252          else
253             throw new BaseException(e);
254       } finally {
255          SharkUtilities.releaseRepositoryTransaction(t);
256       }
257       return ret;
258    }
259
260    public String JavaDoc openPackage (RepositoryTransaction t,String JavaDoc relativePath) throws BaseException, PackageInvalid, ExternalPackageInvalid {
261       return openPackage(t,null,relativePath);
262    }
263
264    public void updatePackage (String JavaDoc id, String JavaDoc relativePathToNewPackage) throws BaseException, PackageUpdateNotAllowed, PackageInvalid, ExternalPackageInvalid {
265       RepositoryTransaction t = null;
266       try {
267          t = SharkUtilities.createRepositoryTransaction();
268          updatePackage(t,id,relativePathToNewPackage);
269          SharkUtilities.commitRepositoryTransaction(t);
270       } catch (RootException e) {
271          SharkUtilities.rollbackRepositoryTransaction(t,e);
272          if (e instanceof PackageUpdateNotAllowed)
273             throw (PackageUpdateNotAllowed)e;
274          else if (e instanceof PackageInvalid)
275             throw (PackageInvalid)e;
276          else if (e instanceof ExternalPackageInvalid)
277             throw (ExternalPackageInvalid)e;
278          else if (e instanceof BaseException)
279             throw (BaseException)e;
280          else
281             throw new BaseException(e);
282       } finally {
283          SharkUtilities.releaseRepositoryTransaction(t);
284       }
285    }
286
287    public void updatePackage (RepositoryTransaction t,String JavaDoc id, String JavaDoc relativePathToNewPackage) throws BaseException, PackageUpdateNotAllowed, PackageInvalid, ExternalPackageInvalid {
288       if (id==null) throw new BaseException("Invalid package Id");
289       openPackage(t,id,relativePathToNewPackage);
290    }
291
292    public void closePackage (String JavaDoc pkgId) throws BaseException, PackageInUse, PackageHasActiveProcesses {
293       RepositoryTransaction t = null;
294       try {
295          t = SharkUtilities.createRepositoryTransaction();
296          closePackage(t,pkgId);
297          SharkUtilities.commitRepositoryTransaction(t);
298       } catch (RootException e) {
299          SharkUtilities.rollbackRepositoryTransaction(t,e);
300          if (e instanceof PackageInUse)
301             throw (PackageInUse)e;
302          else if (e instanceof PackageHasActiveProcesses)
303             throw (PackageHasActiveProcesses)e;
304          else if (e instanceof BaseException)
305             throw (BaseException)e;
306          else
307             throw new BaseException(e);
308       } finally {
309          SharkUtilities.releaseRepositoryTransaction(t);
310       }
311    }
312
313    public synchronized void closePackage (RepositoryTransaction t,String JavaDoc pkgId) throws BaseException, PackageInUse, PackageHasActiveProcesses {
314       cus.info("PackageAdmin -> User "+userId+" is trying to close all package versions of Package with id "+pkgId);
315
316       try {
317
318          SharkUtilities.synchronizeXPDLCache(t);
319
320          if (!repMgr.doesXPDLExist(t,pkgId)) {
321             throw new BaseException("Package with Id="+pkgId+" does not exist");
322          }
323          // check if there are any packages that uses this package as it's
324
// external package
325
if (repMgr.getReferringXPDLIds(t,pkgId).size()>0) {
326             throw new PackageInUse("The package can't be unloaded because it is referenced");
327          }
328
329          List JavaDoc pkgVers=repMgr.getXPDLVersions(t,pkgId);
330          String JavaDoc curVer=repMgr.getCurrentVersion(t,pkgId);
331          Package JavaDoc curPkg=null;
332          Map JavaDoc pkgs=new HashMap JavaDoc();
333          for (int i=0; i<pkgVers.size(); i++) {
334             String JavaDoc pkgVer=(String JavaDoc)pkgVers.get(i);
335             Package JavaDoc pkg=SharkUtilities.getPackage(pkgId,pkgVer);
336             if (pkg==null) {
337                throw new BaseException("Package with Id="+pkgId+" - something went wrong while getting XPDL object");
338             }
339             pkgs.put(pkgVer,pkg);
340             if (pkgVer.equals(curVer)) {
341                curPkg=pkg;
342             }
343          }
344          SharkTransaction st=null;
345          boolean dpe;
346          try {
347             st=SharkUtilities.createTransaction();
348             Iterator JavaDoc it=pkgs.entrySet().iterator();
349             while (it.hasNext()) {
350                Map.Entry JavaDoc me=(Map.Entry JavaDoc)it.next();
351                String JavaDoc pkgVer=(String JavaDoc)me.getKey();
352                Package JavaDoc pkg=(Package JavaDoc)me.getValue();
353
354                // check if there are any processes that were created from this
355
// packages process definition, and if so, throw an exception
356
if (checkDBProcesses(st,pkg,pkgId,pkgVer)) {
357                   throw new PackageHasActiveProcesses("Can't remove package for which exists process instance in DB");// can't remove package with active processes
358
}
359             }
360          } catch (Exception JavaDoc ex) {
361             SharkUtilities.emptyCaches(st);
362             throw ex;
363          } finally {
364             SharkUtilities.releaseTransaction(st);
365          }
366
367
368          Iterator JavaDoc it=pkgs.entrySet().iterator();
369          while (it.hasNext()) {
370             Map.Entry JavaDoc me=(Map.Entry JavaDoc)it.next();
371             String JavaDoc pkgVer=(String JavaDoc)me.getKey();
372             Package JavaDoc pkg=(Package JavaDoc)me.getValue();
373             repMgr.moveToHistory(t,pkgId,pkgVer);
374
375             WfPackageEventAuditImpl pea=new WfPackageEventAuditImpl(pkg,SharkConstants.EVENT_PACKAGE_UNLOADED,userId);
376             // remove all engine objects
377
xmlInterface.closePackageVersion(pkgId, pkgVer);
378          }
379          removeParticipantMappingsForPackage(curPkg);
380          removeApplicationMappingsForPackage(curPkg);
381
382          removeManagersForPackages(pkgs.values());
383
384          cus.info("PackageAdmin -> User "+userId+" has closed Package with id "+pkgId);
385       } catch (Exception JavaDoc ex) {
386          cus.warn("PackageAdmin -> User "+userId+" failed to close the Package with id "+pkgId+" because it is in use");
387          //ex.printStackTrace();
388
//return;
389
if (ex instanceof BaseException) {
390             throw (BaseException)ex;
391          } else if (ex instanceof PackageInUse) {
392             throw (PackageInUse)ex;
393          } else if (ex instanceof PackageHasActiveProcesses) {
394             throw (PackageHasActiveProcesses)ex;
395          } else {
396             throw new BaseException(ex);
397          }
398       }
399    }
400
401    public void closePackage (String JavaDoc pkgId,String JavaDoc pkgVer) throws BaseException, PackageInUse, PackageHasActiveProcesses {
402       RepositoryTransaction t = null;
403       try {
404          t = SharkUtilities.createRepositoryTransaction();
405          closePackage(t,pkgId,pkgVer);
406          SharkUtilities.commitRepositoryTransaction(t);
407       } catch (RootException e) {
408          SharkUtilities.rollbackRepositoryTransaction(t,e);
409          if (e instanceof PackageInUse)
410             throw (PackageInUse)e;
411          else if (e instanceof PackageHasActiveProcesses)
412             throw (PackageHasActiveProcesses)e;
413          else if (e instanceof BaseException)
414             throw (BaseException)e;
415          else
416             throw new BaseException(e);
417       } finally {
418          SharkUtilities.releaseRepositoryTransaction(t);
419       }
420    }
421
422    public synchronized void closePackage (RepositoryTransaction t,String JavaDoc pkgId,String JavaDoc pkgVer) throws BaseException, PackageInUse, PackageHasActiveProcesses {
423       cus.info("PackageAdmin -> User "+userId+" is trying to close Package with id "+pkgId+", and version "+pkgVer);
424
425       try {
426          SharkUtilities.synchronizeXPDLCache(t);
427
428          if (!repMgr.doesXPDLExist(t,pkgId,pkgVer)) {
429             throw new BaseException("Package with Id="+pkgId+" and version="+pkgVer+" does not exist");
430          }
431
432          int hm=repMgr.getXPDLVersions(t,pkgId).size();
433
434          Package JavaDoc pkg=SharkUtilities.getPackage(pkgId,pkgVer);
435          if (pkg==null) {
436             throw new BaseException("Package with Id="+pkgId+" - something went wrong while getting XPDL object");
437          }
438
439          String JavaDoc curVer=repMgr.getCurrentVersion(t,pkgId);
440          // check if there are any packages that uses this package as it's
441
// external package
442
if (repMgr.getReferringXPDLIds(t,pkgId).size()>0 && pkgVer.equals(curVer)) {
443             throw new PackageInUse("The package can't be unloaded because it is referenced");
444          }
445
446          SharkTransaction st=null;
447          boolean dpe;
448          try {
449             st=SharkUtilities.createTransaction();
450             // check if there are any processes that were created from this
451
// packages process definition, and if so, throw an exception
452
dpe=checkDBProcesses(st,pkg,pkgId,pkgVer);
453          } catch (Exception JavaDoc ex) {
454             SharkUtilities.emptyCaches(st);
455             throw ex;
456          } finally {
457             SharkUtilities.releaseTransaction(st);
458          }
459
460          if (dpe) {
461             throw new PackageHasActiveProcesses("Can't remove package with processes instances in DB");// can't remove package with active processes
462
}
463
464          repMgr.moveToHistory(t,pkgId,pkgVer);
465
466          WfPackageEventAuditImpl pea=new WfPackageEventAuditImpl(pkg,SharkConstants.EVENT_PACKAGE_UNLOADED,userId);
467          // remove all engine objects
468
xmlInterface.closePackageVersion(pkgId, pkgVer);
469
470          // remove mappings only if this was the only package version
471
if (hm==1) {
472             removeParticipantMappingsForPackage(pkg);
473             removeApplicationMappingsForPackage(pkg);
474          }
475          removeManagersForPackage(pkg);
476
477          cus.info("PackageAdmin -> User "+userId+" has closed Package with id "+pkgId+" and version "+pkgVer);
478       } catch (Exception JavaDoc ex) {
479          cus.warn("PackageAdmin -> User "+userId+" failed to close the Package with id "+pkgId+" and version "+pkgVer+" because it is in use");
480          //ex.printStackTrace();
481
//return;
482
if (ex instanceof BaseException) {
483             throw (BaseException)ex;
484          } else if (ex instanceof PackageInUse) {
485             throw (PackageInUse)ex;
486          } else if (ex instanceof PackageHasActiveProcesses) {
487             throw (PackageHasActiveProcesses)ex;
488          } else {
489             throw new BaseException(ex);
490          }
491       }
492    }
493
494    // returns true if there are processes in DB
495
private boolean checkDBProcesses (SharkTransaction st,Package JavaDoc pkg,String JavaDoc pkgId,String JavaDoc pkgVer) throws Exception JavaDoc {
496       // check if there are any processes that were created from this
497
// packages process definition, and if so, throw an exception
498
Iterator JavaDoc processes=((WorkflowProcesses)pkg.get("WorkflowProcesses")).
499          toElements().iterator();
500       while (processes.hasNext()) {
501          WorkflowProcess wp=(WorkflowProcess)processes.next();
502          String JavaDoc mgrName=SharkUtilities.createProcessMgrKey(pkgId,pkgVer,wp.getId());
503          WfProcessMgrInternal mgr =SharkUtilities.getProcessMgr(st,mgrName);
504          List JavaDoc procs=SharkEngineManager
505             .getInstance()
506             .getInstancePersistenceManager()
507             .getAllProcessesForMgr(mgrName,st);
508          if (procs!=null && procs.size()>0) {
509             return true;
510          }
511       }
512       return false;
513    }
514
515
516    public boolean isPackageReferenced(String JavaDoc pkgId) throws BaseException {
517       boolean ret=false;
518       RepositoryTransaction t = null;
519       try {
520          t = SharkUtilities.createRepositoryTransaction();
521          ret=isPackageReferenced(t,pkgId);
522          //SharkUtilities.commitRepositoryTransaction(t);
523
} catch (RootException e) {
524          //SharkUtilities.rollbackRepositoryTransaction(t);
525
if (e instanceof BaseException)
526             throw (BaseException)e;
527          else
528             throw new BaseException(e);
529       } finally {
530          SharkUtilities.releaseRepositoryTransaction(t);
531       }
532       return ret;
533    }
534
535    public boolean isPackageReferenced (RepositoryTransaction t,String JavaDoc pkgId) throws BaseException {
536       try {
537          return repMgr.getReferringXPDLIds(t,pkgId).size()>0;
538       } catch (Exception JavaDoc ex) {
539          throw new BaseException(ex);
540       }
541    }
542
543    public void synchronizeXPDLCache () throws BaseException {
544       RepositoryTransaction t = null;
545       try {
546          t = SharkUtilities.createRepositoryTransaction();
547          synchronizeXPDLCache(t);
548          //SharkUtilities.commitRepositoryTransaction(t);
549
} catch (RootException e) {
550          //SharkUtilities.rollbackRepositoryTransaction(t,e);
551
if (e instanceof BaseException)
552             throw (BaseException)e;
553          else
554             throw new BaseException(e);
555       } finally {
556          SharkUtilities.releaseRepositoryTransaction(t);
557       }
558    }
559
560    public synchronized void synchronizeXPDLCache (RepositoryTransaction t) throws BaseException {
561       SharkUtilities.synchronizeXPDLCache(t);
562    }
563
564    public void clearXPDLCache () throws BaseException {
565       try {
566          SharkUtilities.clearProcessCache();
567       } catch (Exception JavaDoc ex) {}
568       xmlInterface.closeAllPackages();
569    }
570
571    public synchronized void clearXPDLCache (RepositoryTransaction t) throws BaseException {
572       try {
573          SharkUtilities.clearProcessCache();
574       } catch (Exception JavaDoc ex) {}
575       xmlInterface.closeAllPackages();
576    }
577
578    public void refreshXPDLCache () throws BaseException {
579       RepositoryTransaction t = null;
580       try {
581          t = SharkUtilities.createRepositoryTransaction();
582          refreshXPDLCache(t);
583          //SharkUtilities.commitRepositoryTransaction(t);
584
} catch (RootException e) {
585          //SharkUtilities.rollbackRepositoryTransaction(t,e);
586
if (e instanceof BaseException)
587             throw (BaseException)e;
588          else
589             throw new BaseException(e);
590       } finally {
591          SharkUtilities.releaseRepositoryTransaction(t);
592       }
593    }
594
595    public synchronized void refreshXPDLCache (RepositoryTransaction t) throws BaseException {
596       try {
597          SharkUtilities.clearProcessCache();
598       } catch (Exception JavaDoc ex) {}
599       xmlInterface.closeAllPackages();
600       SharkUtilities.synchronizeXPDLCache(t);
601    }
602
603    private synchronized String JavaDoc openPackage (RepositoryTransaction t,String JavaDoc id,String JavaDoc relativePath) throws BaseException, PackageInvalid, ExternalPackageInvalid {
604       boolean update=(id!=null);
605       if (update) {
606          cus.info("PackageAdmin -> Trying to update Package with id="+id+" with content of file at "+relativePath);
607       } else {
608          cus.info("PackageAdmin -> Trying to open Package file "+relativePath);
609       }
610       // now really import the package(s) into engine
611
int exceptionHappened=0;
612       XMLInterface xpdlManager=new XMLInterfaceForJDK13();
613       String JavaDoc pkgId=null;
614       Map JavaDoc pkgInfo=new HashMap JavaDoc();
615
616       relativePath=XMLUtil.convertToSystemPath(relativePath);
617
618       try {
619          pkgId=Shark.getInstance().getRepositoryManager().getPackageId(relativePath);
620
621          if (id!=null && !id.equals(pkgId)) {
622             String JavaDoc msg="The package at path="+relativePath+" does not have the id="+id;
623             cus.warn("PackageAdmin -> "+msg);
624             BaseException bex=new BaseException(msg);
625             throw bex;
626
627          }
628
629          // the list of already opened package Ids
630
Set JavaDoc currentPkgIds=new HashSet JavaDoc(repMgr.getExistingXPDLIds(t));
631
632          // if package user wants to open has the same Id as the one already opened - do not proceed
633
if (id!=null && !currentPkgIds.contains(pkgId)) {
634             String JavaDoc msg="The package with id "+pkgId+" is not open";
635             cus.warn("PackageAdmin -> "+msg);
636             BaseException bex=new BaseException(msg);
637             throw bex;
638          }
639
640
641          // if package user wants to open has the same Id as the one already opened - do not proceed
642
if (id==null && currentPkgIds.contains(pkgId)) {
643             String JavaDoc msg="The package with id "+pkgId+" is already open";
644             cus.warn("PackageAdmin -> "+msg);
645             BaseException bex=new BaseException(msg);
646             throw bex;
647          }
648
649          String JavaDoc pkgVersion=repMgr.getNextVersion(t,pkgId);
650
651          relativePath=SharkUtilities.convertToAbsolutePath(relativePath);
652
653
654          Package JavaDoc pkg=xpdlManager.openPackage(relativePath,true);
655          pkg.setInternalVersion(pkgVersion);
656          // if there are any errors - do not proceed
657
SharkPackageValidator pv=new SharkPackageValidator(pkg,xpdlManager,true);
658          String JavaDoc xpdlValidationErrors="";
659          if (pkg==null || !pv.validateAll(true)) {
660             cus.info("PackageAdmin -> Package file "+relativePath+" failed to open");
661             if (pkg!=null) {
662                xpdlValidationErrors=pv.createXPDLValidationErrorsString();
663             } else {
664                xpdlValidationErrors="Fatal error while opening package from ext. rep.";
665             }
666             if (pkg==null) {
667                exceptionHappened=1;
668                throw new PackageInvalid(xpdlValidationErrors,"No package");
669             } else if (pv.isExternalPackageError()) {
670                exceptionHappened=2;
671                //pv.printDebug();
672
throw new ExternalPackageInvalid(xpdlValidationErrors,"Error in external package");
673             } else {
674                exceptionHappened=1;
675                //pv.printDebug();
676
throw new PackageInvalid(xpdlValidationErrors,"Error in package");
677             }
678          }
679
680          //System.out.println("SXPDLC1");
681
SharkUtilities.synchronizeXPDLCache(t);
682
683          // flats ext. packages paths and adjusts pkg Ids (adds a version), and fills
684
// the info for the packages that need to be uploaded to the internal repository
685
boolean chckExt=adjustPkgsForInternalRep(t,xpdlManager,pkgInfo,pkgId,update);
686
687          /*Set pkgIdsToUpload=new HashSet();
688          Iterator it=pkgInfo.values().iterator();
689          while (it.hasNext()) {
690             PkgInfo pi=(PkgInfo)it.next();
691             if (pi.isForUpload()) {
692                pkgIdsToUpload.add(pi.getId());
693             }
694          }*/

695
696          // if some of ext. pkgs are already opened - recheck
697
if (chckExt) {
698             // close all temporary packages
699
xpdlManager.closeAllPackages();
700
701             // add all packages from remembered context map
702
List JavaDoc pkgContents=new ArrayList JavaDoc();
703             Iterator JavaDoc info=pkgInfo.values().iterator();
704             while (info.hasNext()) {
705                PkgInfo pi=(PkgInfo)info.next();
706                if (pi.isForUpload()) {
707                   pkgContents.add(pi.getByteContent());
708                } else {
709                   pkgContents.add(repMgr.getSerializedXPDLObject(t,pi.getId(),pi.getVersion()));
710                }
711             }
712
713             xpdlManager.setValidation(false);
714             pkg=xpdlManager.openPackagesFromStreams(pkgContents,false);
715             xpdlManager.setValidation(true);
716             // if there are any errors - do not proceed
717
pv=new SharkPackageValidator(pkg,xpdlManager,true);
718             xpdlValidationErrors="";
719             if (pkg==null || !pv.validateAll(true)) {
720                cus.info("PackageAdmin -> Package file "+relativePath+" failed to open");
721                if (pkg!=null) {
722                   xpdlValidationErrors=pv.createXPDLValidationErrorsString();
723                } else {
724                   xpdlValidationErrors="Fatal error while opening package";
725                }
726                if (pkg==null) {
727                   exceptionHappened=1;
728                   throw new PackageInvalid(xpdlValidationErrors,"No package");
729                } else if (pv.isExternalPackageError()) {
730                   cus.warn("PackageAdmin -> there is some external package with the same Id and different content as the one of already opened packages - failed to open");
731                   exceptionHappened=2;
732                   throw new ExternalPackageInvalid("There is some external package with the same Id and different content as the one of already opened packages - failed to open","Error with ext. package");
733                } else {
734                   exceptionHappened=1;
735                   //pv.printDebug();
736
throw new PackageInvalid(xpdlValidationErrors,"Error in package");
737                }
738             }
739
740          }
741
742          xpdlManager.closeAllPackages();
743
744          exceptionHappened=3;
745
746          copyPackagesToInternalPackagesRepository(t,pkgInfo.values());
747
748          //System.out.println("SXPDLC2");
749
SharkUtilities.synchronizeXPDLCache(t);
750
751          Iterator JavaDoc it=pkgInfo.values().iterator();
752          Set JavaDoc pkgsToUpload=new HashSet JavaDoc();
753          while (it.hasNext()) {
754             PkgInfo pinf=(PkgInfo)it.next();
755             if (pinf.isForUpload()) {
756                Package JavaDoc p=xmlInterface.getPackageByIdAndVersion(pinf.getId(), pinf.getVersion());
757                String JavaDoc evType=SharkConstants.EVENT_PACKAGE_LOADED;
758                if (update && pinf.getId().equals(id)) {
759                   evType=SharkConstants.EVENT_PACKAGE_UPDATED;
760                }
761                new WfPackageEventAuditImpl(p,evType,userId);
762                pkgsToUpload.add(p);
763             }
764          }
765
766
767          // clearing process caches
768
// THIS SHOULD BE LAST METHOD TO CALL - BECAUSE OF ROLLBACK
769
addManagersForPackages(pkgsToUpload);
770
771       } catch (Exception JavaDoc ex) {
772          //System.err.println("Exc during opening of package "+urlToPackage);
773
ex.printStackTrace();
774          cus.error("PackageAdmin -> Package file "+relativePath+" failed to open");
775          if (exceptionHappened==0) {
776             if (ex instanceof BaseException) {
777                throw (BaseException)ex;
778             } else {
779                throw new BaseException(ex);
780             }
781          } else if (exceptionHappened==1) {
782             throw (PackageInvalid)ex;
783          } else if (exceptionHappened==2) {
784             throw (ExternalPackageInvalid)ex;
785          } else {
786             if (pkgInfo!=null) {
787                Iterator JavaDoc it=pkgInfo.values().iterator();
788                while (it.hasNext()) {
789                   PkgInfo pi=(PkgInfo)it.next();
790                   try {
791                      xmlInterface.closePackageVersion(pi.getId(),pi.getVersion());
792                   } catch (Exception JavaDoc exc2) {}
793                }
794             }
795             throw new BaseException(ex);
796          }
797       } finally {
798          xpdlManager.closeAllPackages();
799       }
800       if (update) {
801          cus.info("PackageAdmin -> Package with id="+pkgId+" is updated from a file "+relativePath);
802       } else {
803          cus.info("PackageAdmin -> Package with id="+pkgId+" is opened from a file "+relativePath);
804       }
805       return pkgId;
806
807    }
808    /**
809     * Add a workflow package to the engine.
810     * @param packages - collection of workflow packages
811     * @throws Exception
812     */

813    private void addManagersForPackages(Collection JavaDoc pkgInfo) throws Exception JavaDoc {
814       SharkTransaction t=null;
815       try {
816          t = SharkUtilities.createTransaction();
817
818          Iterator JavaDoc mdls=pkgInfo.iterator();
819          while (mdls.hasNext()) {
820             Package JavaDoc p=(Package JavaDoc)mdls.next();
821             String JavaDoc pkgId=p.getId();
822             String JavaDoc pkgVer=p.getInternalVersion();
823             //System.out.println("Adding mgrs for pinfo="+pi);
824
// creating process managers for all definitions within inserted package
825
WorkflowProcesses wps=p.getWorkflowProcesses();
826             Iterator JavaDoc it=wps.toElements().iterator();
827             while (it.hasNext()) {
828                WorkflowProcess wp=(WorkflowProcess)it.next();
829                WfProcessMgrInternal mgrInternal=SharkEngineManager
830                   .getInstance()
831                   .getObjectFactory()
832                   .createProcessMgr(t,pkgId,pkgVer,wp.getId());
833                cus.info("PackageAdmin -> ProcessDefinition "+wp.getId()+" for package "+p.getId()+" is added");
834             }
835
836          }
837          SharkUtilities.commitTransaction(t);
838       } catch (Exception JavaDoc e) {
839          BaseException be=null;
840          if (e instanceof BaseException)
841             be=(BaseException)e;
842          else
843             be=new BaseException(e);
844
845          SharkUtilities.rollbackTransaction(t,be);
846          throw e;
847       } finally {
848          SharkUtilities.releaseTransaction(t);
849       }
850    }
851
852    private void copyPackagesToInternalPackagesRepository (RepositoryTransaction t,
853                                                           Collection JavaDoc pkgInfo) throws Exception JavaDoc {
854       // uploading packages
855
Iterator JavaDoc ptc=pkgInfo.iterator();
856       while (ptc.hasNext()) {
857          PkgInfo pi=(PkgInfo)ptc.next();
858          if (pi.isForUpload()) {
859             //System.out.println("Uploading pkg "+pi.getId()+"V="+Version.getVersion());
860
repMgr.uploadXPDL(t,pi.getId(),pi.getXPDLContent(),pi.getByteContent(),Version.getVersion());
861          }
862       }
863
864       // adding references
865
ptc=pkgInfo.iterator();
866       while (ptc.hasNext()) {
867          PkgInfo pi=(PkgInfo)ptc.next();
868          if (pi.isForUpload()) {
869             Iterator JavaDoc it=pi.getExtRefIds().iterator();
870             int i=0;
871             while (it.hasNext()) {
872                repMgr.addXPDLReference(t,(String JavaDoc)it.next(),pi.getId(),pi.getVersion(),i++);
873             }
874          }
875       }
876    }
877
878    private void removeManagersForPackage (Package JavaDoc pkg) throws Exception JavaDoc {
879       if(pkg != null){
880          SharkTransaction t=null;
881          try {
882             t=SharkUtilities.createTransaction();
883             WorkflowProcesses wps=pkg.getWorkflowProcesses();
884             Iterator JavaDoc it=wps.toElements().iterator();
885             while (it.hasNext()) {
886                WorkflowProcess wp=(WorkflowProcess)it.next();
887                WfProcessMgrInternal toRem=SharkUtilities
888                   .getProcessMgr(t,
889                                  SharkUtilities.createProcessMgrKey(
890                                     pkg.getId(),
891                                     pkg.getInternalVersion(),
892                                     wp.getId()));
893                // deleting database entry for this process manager
894
if (toRem!=null) {
895                   toRem.delete(t);
896                   cus.info("PackageAdmin -> ProcessDefinition "+wp.getId()+" for package "+pkg.getId()+" is removed");
897                }
898             }
899             SharkUtilities.commitTransaction(t);
900          } catch (Exception JavaDoc ex) {
901             BaseException be=null;
902             if (ex instanceof BaseException)
903                be=(BaseException)ex;
904             else
905                be=new BaseException(ex);
906
907             SharkUtilities.rollbackTransaction(t,be);
908             throw ex;
909          } finally {
910             SharkUtilities.releaseTransaction(t);
911          }
912       }
913    }
914
915    private void removeManagersForPackages (Collection JavaDoc pkgs) throws Exception JavaDoc {
916       if(pkgs != null){
917          SharkTransaction t=null;
918          try {
919             t=SharkUtilities.createTransaction();
920             Iterator JavaDoc itPkgs=pkgs.iterator();
921             while (itPkgs.hasNext()) {
922                Package JavaDoc pkg=(Package JavaDoc)itPkgs.next();
923                WorkflowProcesses wps=(WorkflowProcesses)pkg.get("WorkflowProcesses");
924                Iterator JavaDoc it=wps.toElements().iterator();
925                while (it.hasNext()) {
926                   WorkflowProcess wp=(WorkflowProcess)it.next();
927                   WfProcessMgrInternal toRem=SharkUtilities
928                      .getProcessMgr(t,
929                                     SharkUtilities.createProcessMgrKey(
930                                        pkg.getId(),
931                                        pkg.getInternalVersion(),
932                                        wp.getId()));
933                   // deleting database entry for this process manager
934
if (toRem!=null) {
935                      toRem.delete(t);
936                      cus.info("PackageAdmin -> ProcessDefinition "+wp.getId()+" for package "+pkg.getId()+" is removed");
937                   }
938                }
939             }
940             SharkUtilities.commitTransaction(t);
941          } catch (Exception JavaDoc ex) {
942             BaseException be=null;
943             if (ex instanceof BaseException)
944                be=(BaseException)ex;
945             else
946                be=new BaseException(ex);
947
948             SharkUtilities.rollbackTransaction(t,be);
949             throw ex;
950          } finally {
951             SharkUtilities.releaseTransaction(t);
952          }
953       }
954    }
955
956
957    private void removeParticipantMappingsForPackage (Package JavaDoc pkg) throws Exception JavaDoc {
958       ParticipantMappingManager pms=SharkEngineManager.getInstance().getParticipantMapPersistenceManager();
959       if (pms==null) return;
960       ParticipantMappingTransaction t=null;
961       try {
962          t = SharkUtilities.createParticipantMappingTransaction();
963          // remove mappings for participants contained within the removed package
964
Participants ps=pkg.getParticipants();
965          Iterator JavaDoc participants=ps.toElements().iterator();
966          while (participants.hasNext()) {
967             Participant p=(Participant)participants.next();
968             /*
969              org.enhydra.shark.api.internal.partmappersistence.ParticipantMap pm=pms.createParticipantMap();
970              pm.setPackageId(pkgId);
971              pm.setProcessDefinitionId(null);
972              pm.setParticipantId(p.getID());
973              if (pms.doesParticipantMappingExist(t,pm)) {
974              */

975             pms.deleteParticipantMappings(
976                t,
977                pkg.getId(),
978                null,
979                p.getId());
980             // }
981
//System.out.println("Rem P["+pkgId+","+""+","+p.getID()+"]");
982
}
983          Iterator JavaDoc processes=pkg.getWorkflowProcesses().toElements().iterator();
984          while (processes.hasNext()) {
985             WorkflowProcess wp=(WorkflowProcess)processes.next();
986             String JavaDoc wpId=wp.getId();
987             ps=wp.getParticipants();
988             participants=ps.toElements().iterator();
989             while (participants.hasNext()) {
990                Participant p=(Participant)participants.next();
991                org.enhydra.shark.api.internal.partmappersistence.ParticipantMap pm=pms.createParticipantMap();
992                pm.setPackageId(pkg.getId());
993                pm.setProcessDefinitionId(wpId);
994                pm.setParticipantId(p.getId());
995                //if (pms.doesParticipantMappingExist(t,pm)) {
996
pms.deleteParticipantMappings(
997                   t,
998                   pkg.getId(),
999                   wpId,
1000                  p.getId());
1001               //}
1002
}
1003         }
1004         cus.info("PackageAdmin -> Participant mappings for package "+pkg+" are removed");
1005         SharkUtilities.commitMappingTransaction(t);
1006      } catch (RootException e) {
1007         SharkUtilities.rollbackMappingTransaction(t,e);
1008         e.printStackTrace();
1009         throw e;
1010      } finally {
1011         SharkUtilities.releaseMappingTransaction(t);
1012      }
1013   }
1014
1015   private void removeApplicationMappingsForPackage (Package JavaDoc pkg) throws Exception JavaDoc {
1016      ApplicationMappingManager ams=SharkEngineManager.getInstance().getApplicationMapPersistenceManager();
1017      if (ams==null) return;
1018      ApplicationMappingTransaction t=null;
1019      try {
1020         t = SharkUtilities.createApplicationMappingTransaction();
1021
1022         // remove mappings for participants contained within the removed package
1023
Applications apps=pkg.getApplications();
1024         Iterator JavaDoc applications=apps.toElements().iterator();
1025         while (applications.hasNext()) {
1026            Application app=(Application)applications.next();
1027            if (ams.getApplicationMap(t,pkg.getId(),"",app.getId())!=null) {
1028               ams.deleteApplicationMapping(
1029                  t,
1030                  pkg.getId(),
1031                  null,
1032                  app.getId());
1033            }
1034         }
1035         Iterator JavaDoc processes=pkg.getWorkflowProcesses().toElements().iterator();
1036         while (processes.hasNext()) {
1037            WorkflowProcess wp=(WorkflowProcess)processes.next();
1038            String JavaDoc wpId=wp.getId();
1039            apps=wp.getApplications();
1040            applications=apps.toElements().iterator();
1041            while (applications.hasNext()) {
1042               Application app=(Application)applications.next();
1043               if (ams.getApplicationMap(t,pkg.getId(),wpId,app.getId())!=null) {
1044                  ams.deleteApplicationMapping(
1045                     t,
1046                     pkg.getId(),
1047                     wpId,
1048                     app.getId());
1049               }
1050            }
1051         }
1052         cus.info("PackageAdmin -> Application mappings for package "+pkg+" are removed");
1053         SharkUtilities.commitMappingTransaction(t);
1054      } catch (RootException e) {
1055         SharkUtilities.rollbackMappingTransaction(t,e);
1056         throw e;
1057      } finally {
1058         SharkUtilities.releaseMappingTransaction(t);
1059      }
1060   }
1061
1062   private boolean adjustPkgsForInternalRep (RepositoryTransaction t,XMLInterface xpdlMgr,Map JavaDoc pkgInfo,String JavaDoc mainPkgId,boolean update) throws Exception JavaDoc {
1063      boolean chckExt=false;
1064      // flat all external packages, and use it's Ids + proper version instead of filenames
1065
Collection JavaDoc pkgsToAdjust=new HashSet JavaDoc(xpdlMgr.getAllPackages());
1066      Iterator JavaDoc packages=pkgsToAdjust.iterator();
1067      while (packages.hasNext()) {
1068         Package JavaDoc p=(Package JavaDoc)packages.next();
1069         String JavaDoc pkgId=p.getId();
1070         String JavaDoc version=null;
1071         boolean forUpl=false;
1072         if (!repMgr.doesXPDLExist(t,pkgId) || (update && pkgId.equals(mainPkgId))) {
1073            version=repMgr.getNextVersion(t,pkgId);
1074            forUpl=true;
1075         } else {
1076            version=repMgr.getCurrentVersion(t,pkgId);
1077            chckExt=true;
1078         }
1079         p.setInternalVersion(version);
1080
1081         PkgInfo pInfo=new PkgInfo(p,version,forUpl);
1082         //System.out.println("Added pkgInfo "+pInfo.toString());
1083
pkgInfo.put(pkgId,pInfo);
1084      }
1085      return chckExt;
1086   }
1087
1088   class PkgInfo {
1089      private Package JavaDoc pkg;
1090      private String JavaDoc version;
1091      private boolean isForUpload;
1092      private byte[] content;
1093      private byte[] xpdlContent;
1094
1095      public PkgInfo (Package JavaDoc pkg,String JavaDoc version,boolean isForUpload) throws Exception JavaDoc {
1096         this.pkg=pkg;
1097         this.version=version;
1098         this.isForUpload=isForUpload;
1099         if (isForUpload) {
1100            pkg.setReadOnly(true);
1101            ByteArrayOutputStream JavaDoc os=new ByteArrayOutputStream JavaDoc();
1102            XMLUtil.packageToStream(pkg,os);
1103            xpdlContent=os.toByteArray();
1104            os.close();
1105         }
1106         this.content=XMLUtil.serialize(pkg);
1107         
1108      }
1109
1110      public Package JavaDoc getPackage () {
1111         return pkg;
1112      }
1113
1114      public void setPackage (Package JavaDoc pkg) {
1115         this.pkg=pkg;
1116      }
1117
1118      public String JavaDoc getId () {
1119         return pkg.getId();
1120      }
1121
1122      public String JavaDoc getVersion () {
1123         return version;
1124      }
1125
1126      public Collection JavaDoc getExtRefIds () {
1127         return pkg.getExternalPackageIds();
1128      }
1129
1130      public byte[] getXPDLContent () {
1131         return xpdlContent;
1132      }
1133      
1134      public byte[] getByteContent () {
1135         return content;
1136      }
1137
1138      public boolean isForUpload () {
1139         return isForUpload;
1140      }
1141
1142      public String JavaDoc toString () {
1143         return "PKG="+pkg+",Id="+pkg.getId()+",isForUpl="+isForUpload+"]";
1144      }
1145   }
1146
1147   public static byte[] convertSharkPackageContentXPDLByteArray (byte[] sharkPkgBytes) throws Exception JavaDoc {
1148      Package JavaDoc shrkPkg=(Package JavaDoc)XMLUtil.deserialize(sharkPkgBytes);
1149      shrkPkg.setReadOnly(false);
1150      Iterator JavaDoc it=shrkPkg.getExternalPackages().toElements().iterator();
1151      while (it.hasNext()) {
1152         ExternalPackage ep=(ExternalPackage)it.next();
1153         String JavaDoc nhref=shrkPkg.getExternalPackageId(ep.getHref());
1154         ep.setHref(nhref);
1155      }
1156      ByteArrayOutputStream JavaDoc os=new ByteArrayOutputStream JavaDoc();
1157      XMLUtil.packageToStream(shrkPkg,os);
1158      byte[] content=os.toByteArray();
1159      os.close();
1160      return content;
1161   }
1162   
1163   
1164}
1165
1166
1167
Popular Tags