SharkUtilities.java :  » Workflow-Engines » shark » org » enhydra » shark » Java Open Source

Java Open Source » Workflow Engines » shark 
shark » org » enhydra » shark » SharkUtilities.java
package org.enhydra.shark;

import java.io.StringReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.enhydra.shark.api.RootError;
import org.enhydra.shark.api.client.wfmc.wapi.WMActivityInstance;
import org.enhydra.shark.api.client.wfmc.wapi.WMActivityInstanceState;
import org.enhydra.shark.api.client.wfmc.wapi.WMParticipant;
import org.enhydra.shark.api.client.wfmc.wapi.WMProcessDefinition;
import org.enhydra.shark.api.client.wfmc.wapi.WMProcessDefinitionState;
import org.enhydra.shark.api.client.wfmc.wapi.WMProcessInstance;
import org.enhydra.shark.api.client.wfmc.wapi.WMProcessInstanceState;
import org.enhydra.shark.api.client.wfmc.wapi.WMSessionHandle;
import org.enhydra.shark.api.client.wfmc.wapi.WMWorkItem;
import org.enhydra.shark.api.client.wfmc.wapi.WMWorkItemState;
import org.enhydra.shark.api.client.wfmodel.AlreadyRunning;
import org.enhydra.shark.api.client.wfmodel.AlreadySuspended;
import org.enhydra.shark.api.client.wfmodel.CannotComplete;
import org.enhydra.shark.api.client.wfmodel.CannotResume;
import org.enhydra.shark.api.client.wfmodel.CannotStart;
import org.enhydra.shark.api.client.wfmodel.CannotStop;
import org.enhydra.shark.api.client.wfmodel.CannotSuspend;
import org.enhydra.shark.api.client.wfmodel.InvalidState;
import org.enhydra.shark.api.client.wfmodel.NotRunning;
import org.enhydra.shark.api.client.wfmodel.NotSuspended;
import org.enhydra.shark.api.client.wfmodel.TransitionNotAllowed;
import org.enhydra.shark.api.client.wfmodel.WfAssignment;
import org.enhydra.shark.api.client.wfservice.WMEntity;
import org.enhydra.shark.api.common.SharkConstants;
import org.enhydra.shark.api.internal.caching.CacheMgr;
import org.enhydra.shark.api.internal.caching.ProcessCache;
import org.enhydra.shark.api.internal.eventaudit.AssignmentEventAuditPersistenceObject;
import org.enhydra.shark.api.internal.eventaudit.CreateProcessEventAuditPersistenceObject;
import org.enhydra.shark.api.internal.eventaudit.DataEventAuditPersistenceObject;
import org.enhydra.shark.api.internal.eventaudit.EventAuditManagerInterface;
import org.enhydra.shark.api.internal.eventaudit.EventAuditPersistenceInterface;
import org.enhydra.shark.api.internal.eventaudit.StateEventAuditPersistenceObject;
import org.enhydra.shark.api.internal.instancepersistence.ActivityPersistenceObject;
import org.enhydra.shark.api.internal.instancepersistence.AssignmentPersistenceObject;
import org.enhydra.shark.api.internal.instancepersistence.PersistenceException;
import org.enhydra.shark.api.internal.instancepersistence.PersistentManagerInterface;
import org.enhydra.shark.api.internal.instancepersistence.ProcessMgrPersistenceObject;
import org.enhydra.shark.api.internal.instancepersistence.ProcessPersistenceObject;
import org.enhydra.shark.api.internal.instancepersistence.ResourcePersistenceObject;
import org.enhydra.shark.api.internal.repositorypersistence.RepositoryPersistenceManager;
import org.enhydra.shark.api.internal.scripting.Evaluator;
import org.enhydra.shark.api.internal.working.CallbackUtilities;
import org.enhydra.shark.api.internal.working.ObjectFactory;
import org.enhydra.shark.api.internal.working.TxSynchronization;
import org.enhydra.shark.api.internal.working.TxSynchronizationFactory;
import org.enhydra.shark.api.internal.working.WfActivityInternal;
import org.enhydra.shark.api.internal.working.WfAssignmentInternal;
import org.enhydra.shark.api.internal.working.WfProcessInternal;
import org.enhydra.shark.api.internal.working.WfProcessMgrInternal;
import org.enhydra.shark.api.internal.working.WfResourceInternal;
import org.enhydra.shark.utilities.MiscUtilities;
import org.enhydra.shark.xpdl.Version;
import org.enhydra.shark.xpdl.XMLCollection;
import org.enhydra.shark.xpdl.XMLCollectionElement;
import org.enhydra.shark.xpdl.XMLComplexElement;
import org.enhydra.shark.xpdl.XMLElement;
import org.enhydra.shark.xpdl.XMLInterface;
import org.enhydra.shark.xpdl.XMLInterfaceForJDK13;
import org.enhydra.shark.xpdl.XMLUtil;
import org.enhydra.shark.xpdl.XPDLConstants;
import org.enhydra.shark.xpdl.elements.Activity;
import org.enhydra.shark.xpdl.elements.ActualParameter;
import org.enhydra.shark.xpdl.elements.ActualParameters;
import org.enhydra.shark.xpdl.elements.Application;
import org.enhydra.shark.xpdl.elements.BasicType;
import org.enhydra.shark.xpdl.elements.DataField;
import org.enhydra.shark.xpdl.elements.DataType;
import org.enhydra.shark.xpdl.elements.ExternalPackage;
import org.enhydra.shark.xpdl.elements.FormalParameter;
import org.enhydra.shark.xpdl.elements.FormalParameters;
import org.enhydra.shark.xpdl.elements.Package;
import org.enhydra.shark.xpdl.elements.Participant;
import org.enhydra.shark.xpdl.elements.SchemaType;
import org.enhydra.shark.xpdl.elements.WorkflowProcess;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

/**
 * The various utilities needed for shark.
 * 
 * @author Sasa Bojanic
 * @author Vladimir Puskas
 * @author Zoran Milakovic
 */
public class SharkUtilities {
   // TODO: implement Enumeration type handling
   // TODO: if some data from XPDL Package are wanted, sometimes
   // they are not retrieved (i.e. if one asks for variable name, and
   // the variable's XPDL is not cached -> exception happens)

   public static final int READ_ONLY_MODE = 0;

   public static final int WRITE_MODE = 1;

   private static Map validActivityStates = new HashMap();
   static {
      List vsList = new ArrayList();
      validActivityStates.put(SharkConstants.STATE_CLOSED_ABORTED, vsList);
      validActivityStates.put(SharkConstants.STATE_CLOSED_COMPLETED, vsList);
      validActivityStates.put(SharkConstants.STATE_CLOSED_TERMINATED, vsList);

      vsList = new ArrayList(SharkConstants.possibleActivityStates);
      vsList.remove(SharkConstants.STATE_OPEN_RUNNING);
      validActivityStates.put(SharkConstants.STATE_OPEN_RUNNING, vsList);

      vsList = new ArrayList(SharkConstants.possibleActivityStates);
      vsList.remove(SharkConstants.STATE_OPEN_NOT_RUNNING_NOT_STARTED);
      vsList.remove(SharkConstants.STATE_CLOSED_COMPLETED);
      validActivityStates.put(SharkConstants.STATE_OPEN_NOT_RUNNING_NOT_STARTED, vsList);

      vsList = new ArrayList(SharkConstants.possibleActivityStates);
      vsList.remove(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED);
      vsList.remove(SharkConstants.STATE_CLOSED_COMPLETED);
      validActivityStates.put(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED, vsList);
   }

   static final List valid_activity_states(String currentState) {
      return (List) validActivityStates.get(currentState);
   }

   static List valid_activity_states_to_get_in(String state) {
      List valid_states = new ArrayList();

      for (int i = 0; i < SharkConstants.possibleActivityStates.size(); i++) {
         List temp = valid_activity_states((String) SharkConstants.possibleActivityStates.get(i));
         if (temp.contains(state))
            valid_states.add(SharkConstants.possibleActivityStates.get(i));
      }

      return valid_states;
   }

   private static Map validProcessStates = new HashMap();
   static {
      List vsList = new ArrayList();
      validProcessStates.put(SharkConstants.STATE_CLOSED_ABORTED, vsList);
      validProcessStates.put(SharkConstants.STATE_CLOSED_COMPLETED, vsList);
      validProcessStates.put(SharkConstants.STATE_CLOSED_TERMINATED, vsList);

      vsList = new ArrayList(SharkConstants.possibleProcessStates);
      vsList.remove(SharkConstants.STATE_OPEN_RUNNING);
      vsList.remove(SharkConstants.STATE_OPEN_NOT_RUNNING_NOT_STARTED);
      validProcessStates.put(SharkConstants.STATE_OPEN_RUNNING, vsList);

      vsList = new ArrayList(SharkConstants.possibleProcessStates);
      vsList.remove(SharkConstants.STATE_OPEN_NOT_RUNNING_NOT_STARTED);
      vsList.remove(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED);
      vsList.remove(SharkConstants.STATE_CLOSED_COMPLETED);
      validProcessStates.put(SharkConstants.STATE_OPEN_NOT_RUNNING_NOT_STARTED, vsList);

      vsList = new ArrayList(SharkConstants.possibleProcessStates);
      vsList.remove(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED);
      vsList.remove(SharkConstants.STATE_OPEN_NOT_RUNNING_NOT_STARTED);
      vsList.remove(SharkConstants.STATE_CLOSED_COMPLETED);
      validProcessStates.put(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED, vsList);
   }

   static final List valid_process_states(String currentState) {
      return (List) validProcessStates.get(currentState);
   }

   static List valid_process_states_to_get_in(String state) {
      List valid_states = new ArrayList();

      for (int i = 0; i < SharkConstants.possibleProcessStates.size(); i++) {
         List temp = valid_process_states((String) SharkConstants.possibleProcessStates.get(i));
         if (temp.contains(state))
            valid_states.add(SharkConstants.possibleProcessStates.get(i));
      }

      return valid_states;
   }

   // counts connections to engine
   private static int nextConnectionKey = 1;

   static synchronized String getNextConnectionKey() {
      String ck = Integer.toString(nextConnectionKey);
      nextConnectionKey++;
      return ck;
   }

   // a cache of loaded objects
   private static Map loggedUsers = new TreeMap();

   private static int currentUsrId = 0;

   private static Map currentPkgVersions = new HashMap();

   static String connect(String userId, boolean storingConnectionInfo) {
      if (storingConnectionInfo) {
         String connectionKey = null;
         synchronized (loggedUsers) {
            while (true) {
               connectionKey = Integer.toHexString(new Random().nextInt(Integer.MAX_VALUE));
               if (!loggedUsers.containsKey(connectionKey)) {
                  loggedUsers.put(connectionKey, userId);
                  return connectionKey;
               }
            }
         }
      }
      return Integer.toHexString(++currentUsrId);
   }

   static boolean checkSession(WMSessionHandle shandle) {
      return true;
   }

   static boolean disconnect(String connectionKey, boolean storingConnectionInfo) {
      if (storingConnectionInfo) {
         synchronized (loggedUsers) {
            return null != loggedUsers.remove(connectionKey);
         }
      }
      return true;
   }

   static Map getLoggedUsers() throws Exception {
      return Collections.unmodifiableMap(loggedUsers);
   }

   static List createProcessMgrsProcessWrappers(WMSessionHandle shandle, String mgrName)
      throws Exception {

      List l = SharkEngineManager.getInstance()
         .getInstancePersistenceManager()
         .getAllProcessesForMgr(shandle, mgrName);
      List ret = new ArrayList();
      for (int i = 0; i < l.size(); i++) {
         ProcessPersistenceObject po = (ProcessPersistenceObject) l.get(i);
         ret.add(SharkEngineManager.getInstance()
            .getObjectFactory()
            .createProcessWrapper(shandle, mgrName, po.getId()));
      }

      return ret;
   }

   static List createActivityPerformerWrapper(WMSessionHandle shandle,
                                              String procId,
                                              String actId) throws Exception {
      WfActivityInternal act = SharkUtilities.getActivity(shandle,
                                                          procId,
                                                          actId,
                                                          SharkUtilities.READ_ONLY_MODE);
      String performerId = act.getPerformerId(shandle);
      List ret = new ArrayList();
      if (performerId != null) {
         // TODO: process manager information is not valid
         ret.add(SharkEngineManager.getInstance()
            .getObjectFactory()
            .createProcessWrapper(shandle, null, performerId));
      }

      return ret;
   }

   static List createResourceRequesterPerformersWrapper(WMSessionHandle shandle,
                                                        String username) throws Exception {

      PersistentManagerInterface ipi = SharkEngineManager.getInstance()
         .getInstancePersistenceManager();
      List l = ipi.getResourceRequestersProcessIds(shandle, username);
      List ret = new ArrayList();
      for (int i = 0; i < l.size(); i++) {
         String pId = (String) l.get(i);
         ProcessPersistenceObject po = ipi.restoreProcess(shandle, pId);
         // TODO: decide if we have to check here about external
         // requesters
         // (or maybe already in instance persistence layer). This is
         // all due
         // to a change of persisting external requesters
         ret.add(SharkEngineManager.getInstance()
            .getObjectFactory()
            .createProcessWrapper(shandle, po.getProcessMgrName(), po.getId()));
      }
      return ret;
   }

   static List createProcessActivityWrappers(WMSessionHandle shandle, String procId)
      throws Exception {

      WfProcessInternal proc = SharkUtilities.getProcess(shandle,
                                                         procId,
                                                         SharkUtilities.READ_ONLY_MODE);
      List l = proc.getAllActivities(shandle);
      List ret = new ArrayList();
      for (int i = 0; i < l.size(); i++) {
         WfActivityInternal act = (WfActivityInternal) l.get(i);
         ret.add(SharkEngineManager.getInstance()
            .getObjectFactory()
            .createActivityWrapper(shandle,
                                   proc.manager_name(shandle),
                                   procId,
                                   act.key(shandle)));
      }
      // System.err.println("AllProcesses for mgr
      // "+mgr.getProcessDefinitionId()+" are "+ret);
      return ret;
   }

   static List createAssignmentWrappers(WMSessionHandle shandle,
                                        String procId,
                                        String actId) throws Exception {

      List objs = SharkEngineManager.getInstance()
         .getInstancePersistenceManager()
         .getAllValidAssignmentsForActivity(shandle, procId, actId);

      List pobjs = new ArrayList();
      for (Iterator i = objs.iterator(); i.hasNext();) {
         AssignmentPersistenceObject po = (AssignmentPersistenceObject) i.next();
         pobjs.add(SharkEngineManager.getInstance()
            .getObjectFactory()
            .createAssignmentWrapper(shandle,
                                     po.getProcessMgrName(),
                                     procId,
                                     actId,
                                     po.getResourceUsername()));
      }
      return pobjs;
   }

   static List createAssignmentWrappers(WMSessionHandle shandle, String username)
      throws Exception {

      List objs = SharkUtilities.getResource(shandle, username).getAssignments(shandle);
      List pobjs = new ArrayList();
      for (Iterator i = objs.iterator(); i.hasNext();) {
         WfAssignmentInternal ass = (WfAssignmentInternal) i.next();
         pobjs.add(SharkEngineManager.getInstance()
            .getObjectFactory()
            .createAssignmentWrapper(shandle,
                                     ass.managerName(shandle),
                                     ass.processId(shandle),
                                     ass.activityId(shandle),
                                     username));
      }
      return pobjs;
   }

   static List createAllResourceWrappers(WMSessionHandle shandle) throws Exception {
      List resources = new ArrayList();
      List l = SharkEngineManager.getInstance()
         .getInstancePersistenceManager()
         .getAllResources(shandle);
      for (int i = 0; i < l.size(); i++) {
         ResourcePersistenceObject po = (ResourcePersistenceObject) l.get(i);
         resources.add(SharkEngineManager.getInstance()
            .getObjectFactory()
            .createResourceWrapper(shandle, po.getUsername()));
      }
      return resources;
   }

   static List createProcessHistoryEvents(WMSessionHandle shandle, String procId)
      throws Exception {
      List history = new ArrayList();

      EventAuditManagerInterface eam = SharkEngineManager.getInstance()
         .getDefaultEventAuditManager();

      if (null == eam)
         return history;

      List l = eam.restoreProcessHistory(shandle, procId);
      for (int i = 0; i < l.size(); i++) {
         EventAuditPersistenceInterface audit = (EventAuditPersistenceInterface) l.get(i);
         if (audit instanceof CreateProcessEventAuditPersistenceObject) {
            history.add(SharkEngineManager.getInstance()
               .getObjectFactory()
               .createCreateProcessEventAuditWrapper(shandle,
                                                     (CreateProcessEventAuditPersistenceObject) audit));
         } else if (audit instanceof DataEventAuditPersistenceObject) {
            history.add(SharkEngineManager.getInstance()
               .getObjectFactory()
               .createDataEventAuditWrapper(shandle,
                                            (DataEventAuditPersistenceObject) audit));
         } else if (audit instanceof StateEventAuditPersistenceObject) {
            history.add(SharkEngineManager.getInstance()
               .getObjectFactory()
               .createStateEventAuditWrapper(shandle,
                                             (StateEventAuditPersistenceObject) audit));
         }
      }
      return history;
   }

   static List createActivityHistoryEvents(WMSessionHandle shandle,
                                           String procId,
                                           String actId) throws Exception {
      List history = new ArrayList();

      EventAuditManagerInterface eam = SharkEngineManager.getInstance()
         .getDefaultEventAuditManager();
      if (null == eam)
         return history;
      List l = eam.restoreActivityHistory(shandle, procId, actId);
      for (int i = 0; i < l.size(); i++) {
         EventAuditPersistenceInterface audit = (EventAuditPersistenceInterface) l.get(i);
         if (audit instanceof AssignmentEventAuditPersistenceObject) {
            history.add(SharkEngineManager.getInstance()
               .getObjectFactory()
               .createAssignmentEventAuditWrapper(shandle,
                                                  (AssignmentEventAuditPersistenceObject) audit));
         } else if (audit instanceof DataEventAuditPersistenceObject) {
            history.add(SharkEngineManager.getInstance()
               .getObjectFactory()
               .createDataEventAuditWrapper(shandle,
                                            (DataEventAuditPersistenceObject) audit));
         } else if (audit instanceof StateEventAuditPersistenceObject) {
            history.add(SharkEngineManager.getInstance()
               .getObjectFactory()
               .createStateEventAuditWrapper(shandle,
                                             (StateEventAuditPersistenceObject) audit));
         }
      }

      return history;
   }

   static void reevaluateAssignments(WMSessionHandle shandle) throws Exception {
      List l = SharkEngineManager.getInstance()
         .getInstancePersistenceManager()
         .getAllRunningProcesses(shandle);
      for (int i = 0; i < l.size(); i++) {
         ProcessPersistenceObject po = (ProcessPersistenceObject) l.get(i);
         if (po.getState().startsWith(SharkConstants.STATEPREFIX_OPEN)) {
            WfProcessInternal proc = SharkUtilities.getProcess(shandle,
                                                               po.getId(),
                                                               SharkUtilities.WRITE_MODE);
            List acts = proc.getActiveActivities(shandle);
            Iterator itActs = acts.iterator();
            while (itActs.hasNext()) {
               WfActivityInternal aint = (WfActivityInternal) itActs.next();
               aint.reevaluateAssignments(shandle);
            }
         }
      }
   }

   static TxSynchronization getTxSynchronization() throws Exception {
      TxSynchronizationFactory xasf = SharkEngineManager.getInstance()
         .getTxSynchronizationFactory();
      return (null != xasf) ? xasf.createTxSynchronization() : null;
   }

   static void addResourceToCache(WMSessionHandle shandle, WfResourceInternal r)
      throws Exception {
      SharkUtilities.getTxSynchronization().addToTransaction(r.resource_key(shandle), r);
      CacheMgr cm = SharkEngineManager.getInstance().getCacheManager();
      if (null != cm)
         try {
            cm.getResourceCache().add(r.resource_key(shandle), r);
         } catch (Exception e) {
         }
   }

   static void removeResourceFromCache(WMSessionHandle shandle, WfResourceInternal r)
      throws Exception {
      // ((SharkInternalTransaction)t).removeResource(r.resource_key(t));
      CacheMgr cm = SharkEngineManager.getInstance().getCacheManager();
      if (null != cm)
         cm.getResourceCache().remove(r.resource_key(shandle));
   }

   static WfResourceInternal getResourceFromCache(String username) throws Exception {
      TxSynchronization sr = SharkUtilities.getTxSynchronization();
      WfResourceInternal res = sr.getResource(username);
      if (res == null) {
         CacheMgr cm = SharkEngineManager.getInstance().getCacheManager();
         if (null != cm) {
            try {
               res = cm.getResourceCache().get(username);
               if (res != null) {
                  sr.addToTransaction(username, res);
               }
            } catch (Exception ex) {
            }
         }
      }

      return res;
   }

   static WfResourceInternal getResource(WMSessionHandle shandle, String username)
      throws Exception {
      SharkEngineManager em = SharkEngineManager.getInstance();
      ObjectFactory objectFactory = em.getObjectFactory();

      WfResourceInternal res = SharkUtilities.getResourceFromCache(username);
      if (res == null) {
         PersistentManagerInterface pmi = em.getInstancePersistenceManager();
         ResourcePersistenceObject po = pmi.restoreResource(shandle, username);
         if (po != null) {
            res = objectFactory.createResource(po);
            SharkUtilities.addResourceToCache(shandle, res);
         }
      }

      return res;
   }

   static void addProcessToCache(WMSessionHandle shandle, WfProcessInternal p, int mode)
      throws Exception {
      TxSynchronization sr = SharkUtilities.getTxSynchronization();
      sr.addToTransaction(p.key(shandle), p);
      if (mode == SharkUtilities.WRITE_MODE) {
         sr.markNotReadOnly(p.key(shandle));
      } else {
         CacheMgr cm = SharkEngineManager.getInstance().getCacheManager();
         if (null != cm) {
            try {
               cm.getProcessCache().add(p.key(shandle), p);
            } catch (Exception e) {
            }
         }
      }
   }

   static void removeProcessFromCache(WMSessionHandle shandle, WfProcessInternal p)
      throws Exception {
      CacheMgr cm = SharkEngineManager.getInstance().getCacheManager();

      if (null != cm)
         cm.getProcessCache().remove(p.key(shandle));
   }

   private static WfProcessInternal getProcessFromCache(WMSessionHandle shandle,
                                                        String procId,
                                                        int mode) throws Exception {
      TxSynchronization sr = SharkUtilities.getTxSynchronization();
      WfProcessInternal proc = sr.getProcess(procId);

      if (proc == null) {
         CacheMgr cm = SharkEngineManager.getInstance().getCacheManager();
         if (null != cm) {
            try {
               proc = cm.getProcessCache().get(procId);
               if (proc != null) {
                  sr.addToTransaction(proc.key(shandle), proc);
               }
            } catch (Exception ex) {
            }
         }
      }

      if (proc != null && mode == SharkUtilities.WRITE_MODE && proc.isReadOnly()) {
         sr.markNotReadOnly(procId);
         proc = sr.getProcess(procId);
      }

      return proc;
   }

   static WfProcessInternal getProcess(WMSessionHandle shandle, String procId, int mode)
      throws Exception {
      ObjectFactory objectFactory = SharkEngineManager.getInstance().getObjectFactory();

      WfProcessInternal proc = SharkUtilities.getProcessFromCache(shandle, procId, mode);

      if (proc == null) {
         PersistentManagerInterface pmi = SharkEngineManager.getInstance()
            .getInstancePersistenceManager();
         ProcessPersistenceObject po = pmi.restoreProcess(shandle, procId);
         if (po != null) {
            proc = objectFactory.createProcess(po);
            if (mode == SharkUtilities.WRITE_MODE) {
               proc.setReadOnly(false);
            }
            SharkUtilities.addProcessToCache(shandle, proc, mode);
         }
      }

      return proc;
   }

   static WfProcessInternal getProcess(WMSessionHandle shandle,
                                       ProcessPersistenceObject po,
                                       int mode) throws Exception {
      ObjectFactory objectFactory = SharkEngineManager.getInstance().getObjectFactory();

      WfProcessInternal proc = SharkUtilities.getProcessFromCache(shandle,
                                                                  po.getId(),
                                                                  mode);
      if (proc == null) {
         proc = objectFactory.createProcess(po);
         if (mode == SharkUtilities.WRITE_MODE) {
            proc.setReadOnly(false);
         }
         SharkUtilities.addProcessToCache(shandle, proc, mode);
      }

      return proc;
   }

   static WfProcessMgrInternal getProcessMgr(WMSessionHandle shandle, String name)
      throws Exception {

      WfProcessMgrInternal mgr = null;

      PersistentManagerInterface pmi = SharkEngineManager.getInstance()
         .getInstancePersistenceManager();

      ProcessMgrPersistenceObject po = pmi.restoreProcessMgr(shandle, name);
      if (po != null) {
         mgr = SharkEngineManager.getInstance().getObjectFactory().createProcessMgr(po);
      }
      return mgr;
   }

   static WfActivityInternal getActivity(WMSessionHandle shandle,
                                         String procId,
                                         String actId,
                                         int mode) throws Exception {

      // System.out.println("PID="+procId+",aid="+actId);
      WfProcessInternal proc = getProcess(shandle, procId, mode);
      WfActivityInternal act = proc.getActivity(shandle, actId);

      return act;
   }

   static WfAssignmentInternal getAssignment(WMSessionHandle shandle,
                                             String procId,
                                             String actId,
                                             String username) throws Exception {

      WfResourceInternal res = getResource(shandle, username);
      WfAssignmentInternal ass = res.getAssignment(shandle, procId, actId);

      return ass;
   }

   static WfAssignment getAssignmentWrapper(WMSessionHandle shandle,
                                            String procId,
                                            String assId) throws Exception {
      String[] tokens = MiscUtilities.tokenize(assId, "#");
      String actId = tokens[0];
      String uname = tokens[1];
      WfResourceInternal res = getResource(shandle, uname);
      WfAssignmentInternal ass = null;

      if (res != null) {
         ass = res.getAssignment(shandle, procId, actId);
      }

      if (ass != null) {
         return SharkEngineManager.getInstance()
            .getObjectFactory()
            .createAssignmentWrapper(shandle,
                                     ass.managerName(shandle),
                                     procId,
                                     actId,
                                     uname);
      }

      return null;
   }

   /**
    * Throws an exception if type of the variable is not the same or can't be converted
    * into the type defined by XPDL. Otherwise, returns the converted value.
    */
   static Object checkDataType(WorkflowProcess wp, String varId, Object oldVal, Object val)
      throws Exception {

      if (val == null) {
         return val;
      }

      if (oldVal != null && oldVal.getClass().isInstance(val)) {
         return val;
      }

      XMLCollectionElement dfOrFp = (XMLCollectionElement) wp.getAllVariables()
         .get(varId);

      if (dfOrFp == null) {
         throw new Exception("Can't find variable with Id="
                             + varId + " in XPDL definition");
      }

      Class cls = SharkUtilities.getJavaClass(dfOrFp);
      if (cls.isInstance(val)) {
         return val;
      }

      boolean throwException = false;
      XMLElement choosen = ((DataType) dfOrFp.get("DataType")).getDataTypes()
         .getChoosen();

      if (choosen instanceof BasicType) {
         if (cls == Long.class) {
            if (val instanceof Integer) {
               val = new Long(((Integer) val).intValue());
            } else if (val instanceof Short) {
               val = new Long(((Short) val).shortValue());
            } else {
               throwException = true;
            }
         } else if (cls == Double.class) {
            if (val instanceof Integer) {
               val = new Double(((Integer) val).intValue());
            } else if (val instanceof Short) {
               val = new Double(((Short) val).shortValue());
            } else if (val instanceof Long) {
               val = new Double(((Long) val).longValue());
            } else if (val instanceof Float) {
               val = new Double(((Float) val).floatValue());
            } else {
               throwException = true;
            }
         } else if (cls == java.util.Date.class) {
            if (val instanceof java.sql.Date) {
               val = new java.util.Date(((java.sql.Date) val).getTime());
            } else if (val instanceof java.sql.Timestamp) {
               val = new java.util.Date(((java.sql.Timestamp) val).getTime());
            } else if (val instanceof Calendar) {
               val = new java.util.Date(((Calendar) val).getTime().getTime());
            } else {
               throwException = true;
            }
         } else if (cls == String.class) {
            if (!(val instanceof String)) {
               throwException = true;
            }
         } else if (cls == Boolean.class) {
            if (!(val instanceof Boolean)) {
               throwException = true;
            }
         }
      } else if (choosen instanceof SchemaType) {
         if (!Node.class.isAssignableFrom(val.getClass())) {
            throwException = true;
         }
      } else {
         if (oldVal != null || !cls.isInstance(val)) {
            throwException = true;
         }
      }

      if (throwException) {
         throw new Exception("Invalid data type for variable "
                             + dfOrFp.getId() + ", required type=" + cls.getName()
                             + ", provided type=" + val.getClass() + ", oldval=" + oldVal
                             + ", value=" + val);
      }

      return val;
   }

   static Object getInitialValue(WMSessionHandle shandle,
                                 XMLCollectionElement dfOrFp,
                                 boolean forceDefaultValueForType) throws Exception {
      String initialValStr = null;
      if (dfOrFp instanceof DataField) {
         initialValStr = ((DataField) dfOrFp).getInitialValue();
         if (initialValStr.equalsIgnoreCase("null")) {
            return null;
         }
         if (forceDefaultValueForType) {
            initialValStr = "";
         }
      } else {
         initialValStr = "";
      }
      // System.err.println("Creating IA for "+dfOrFp.getID()+" -
      // javaType="+javaType+", IV="+initialValStr);

      return createInitialValue(shandle, initialValStr, dfOrFp);
   }

   static Class getJavaClass(XMLCollectionElement dfOrFp) {
      String jt = ((DataType) dfOrFp.get("DataType")).getJavaType();
      if (jt.endsWith("<>")) {
         if (jt.equals("byte<>")) {
            jt = "[B";
         } else if (jt.equals("boolean<>")) {
            jt = "[Z";
         } else if (jt.equals("char<>")) {
            jt = "[C";
         } else if (jt.equals("double<>")) {
            jt = "[D";
         } else if (jt.equals("float<>")) {
            jt = "[F";
         } else if (jt.equals("int<>")) {
            jt = "[I";
         } else if (jt.equals("long<>")) {
            jt = "[J";
         } else if (jt.equals("short<>")) {
            jt = "[S";
         } else {
            jt = "[L" + jt.substring(0, jt.length() - 2) + ";";
         }
      }
      // System.out.println("GJC-jt for "+dfOrFp.getID()+" is "+jt);
      Class cls = java.lang.Object.class;
      try {
         cls = Class.forName(jt);
      } catch (Exception ex) {
      }

      return cls;
   }

   private static Object createInitialValue(WMSessionHandle shandle,
                                            String initialValStr,
                                            XMLCollectionElement dfOrFp) throws Exception {
      String javaType = ((DataType) dfOrFp.get("DataType")).getJavaType();
      // System.out.println("JT from XPDL of dforfp "+dfOrFp+" is
      // "+javaType);

      // System.err.println("Creating IA for javaType="+javaType+" for
      // ivs="+initialValStr+",for dfOrFp "+dfOrFp);
      Object any = null;
      int ivsl = initialValStr.length();
      if (javaType.equals("java.lang.Boolean")) {
         any = new Boolean(false);
         if (ivsl > 0) {
            try {
               if (initialValStr.equalsIgnoreCase("true") || initialValStr.equals("1")) {
                  any = new Boolean(true);
               } else if (initialValStr.equalsIgnoreCase("false")
                          || initialValStr.equals("0")) {
                  any = new Boolean(false);
               }
            } catch (Exception ex) {
            }
         }
      } else if (javaType.equals("java.lang.String")) {
         any = initialValStr;
      } else if (javaType.equals("java.lang.Long")) {
         any = new Long(0);
         if (ivsl > 0) {
            try {
               any = new Long(initialValStr);
            } catch (NumberFormatException nfe) {
               try {
                  Double d = new Double(initialValStr);
                  any = new Long(d.longValue());
               } catch (Exception ex) {
               }
            }
         }
      } else if (javaType.equals("java.lang.Double")) {
         any = new Double(0);
         if (ivsl > 0) {
            try {
               any = new Double(initialValStr);
            } catch (Exception nfe) {
            }
         }
      } else if (javaType.equals("java.util.Date")) {
         any = new Date();
         if (ivsl > 0) {
            try {
               any = DateFormat.getDateInstance().parse(initialValStr);
            } catch (ParseException pe) {
               try {
                  any = new Date(Long.parseLong(initialValStr));
               } catch (Exception ex) {
                  try {
                     Package pkg = XMLUtil.getPackage(dfOrFp);
                     String scriptType = pkg.getScript().getType();
                     Evaluator ev = SharkEngineManager.getInstance()
                        .getScriptingManager()
                        .getEvaluator(shandle, scriptType);
                     any = (Date) ev.evaluateExpression(shandle,
                                                        null,
                                                        null,
                                                        initialValStr,
                                                        new HashMap(),
                                                        Date.class);
                  } catch (Exception ex2) {
                  }
               }
            }
         }
      } else if (javaType.equals("org.w3c.dom.Node")) {
         if (ivsl > 0) {
            try {
               DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
               dbf.setNamespaceAware(true);
               DocumentBuilder db = dbf.newDocumentBuilder();
               any = db.parse(new InputSource(new StringReader(initialValStr)));
               // System.err.println(XMLUtil.getChildNodesContent((Document) any));
            } catch (Throwable ex) {
               SharkEngineManager.getInstance()
                  .getCallbackUtilities()
                  .warn(shandle,
                        "The instantiation of object for class "
                              + javaType + " failed - using null value");
               // ex.printStackTrace();
            }
         }
      } else {
         try {
            /*
             * if (initialValStr!=null && initialValStr.trim().equalsIgnoreCase("null")) {
             * any=null; //System.out.println("CREATED NULL OBJ FOR xpdlt "+xpdlType); }
             * else {
             */
            Class cls = Class.forName(javaType);
            if (ivsl == 0) {
               if (!cls.isInterface()) {
                  any = cls.newInstance();
               }
            } else {
               Package pkg = XMLUtil.getPackage(dfOrFp);
               String scriptType = pkg.getScript().getType();
               Evaluator ev = SharkEngineManager.getInstance()
                  .getScriptingManager()
                  .getEvaluator(shandle, scriptType);
               any = ev.evaluateExpression(shandle,
                                           null,
                                           null,
                                           initialValStr,
                                           new HashMap(),
                                           cls);
            }
            // System.out.println("CREATED OBJ FOR xpdlt "+xpdlType);
            // }
         } catch (Throwable ex) {
            SharkEngineManager.getInstance()
               .getCallbackUtilities()
               .warn(shandle,
                     "The instantiation of object for class "
                           + javaType + " failed - using null value");
            // ex.printStackTrace();
         }
      }
      // System.err.println("Created value is "+any);
      return any;
   }

   static Package getPackage(WMSessionHandle shandle, String pkgId, String pkgVer)
      throws Exception {
      XMLInterface xmlInterface = SharkEngineManager.getInstance().getXMLInterface();
      // System.out.println("Getting pkg "+pkgIdWithVersion);
      Package pkg = null;

      if (pkgVer != null) {
         pkg = xmlInterface.getPackageByIdAndVersion(pkgId, pkgVer);
      } else {
         pkg = xmlInterface.getPackageById(pkgId);
      }

      if (pkg == null) {
         SharkEngineManager.getInstance()
            .getCallbackUtilities()
            .info(shandle,
                  "Package ["
                        + pkgId + "," + pkgVer
                        + "] is not found - synchronizing XPDL caches ...");

         synchronizeXPDLCache(shandle);
         if (pkgVer != null) {
            pkg = xmlInterface.getPackageByIdAndVersion(pkgId, pkgVer);
         } else {
            pkg = xmlInterface.getPackageById(pkgId);
         }
         if (pkg == null) {
            throw new Exception("Package with Id="
                                + pkgId + " and version=" + pkgVer + " can't be found!");
         }

      }
      return pkg;
   }

   static WorkflowProcess getWorkflowProcess(WMSessionHandle shandle,
                                             String pkgId,
                                             String pkgVer,
                                             String wpId) throws Exception {
      try {
         return getPackage(shandle, pkgId, pkgVer).getWorkflowProcess(wpId);
      } catch (Exception ex) {
         return null;
      }
   }

   static Activity getActivityDefinition(WMSessionHandle shandle,
                                         String pkgId,
                                         String pkgVer,
                                         String wpId,
                                         String actDefId) throws Exception {
      WorkflowProcess wp = getWorkflowProcess(shandle, pkgId, pkgVer, wpId);
      if (wp == null) {
         throw new Exception("Can't find process definition for definition Id="
                             + wpId + " in package with Id=" + pkgId + ", and version="
                             + pkgVer);
      }

      return wp.getActivity(actDefId);
   }

   /**
    * When activity is within block, this is recursive implementation. The recursion is
    * needed because the activities block can be inside some other block.
    */
   static Activity getActivityDefinition(WMSessionHandle shandle,
                                         WfActivityInternal act,
                                         WorkflowProcess wp) throws Exception {

      return wp.getActivity(act.activity_definition_id(shandle));
   }

   static WMEntity getEntity(WMSessionHandle shandle,
                             String mgrName,
                             String procId,
                             String actId) throws Exception {
      XMLComplexElement cel = null;
      if (!MiscUtilities.isEmptyString(mgrName)) {
         WfProcessMgrInternal mgr = SharkUtilities.getProcessMgr(shandle, mgrName);
         cel = SharkUtilities.getWorkflowProcess(shandle,
                                                 mgr.package_id(shandle),
                                                 mgr.version(shandle),
                                                 mgr.process_definition_id(shandle));
      } else if (!MiscUtilities.isEmptyString(procId)) {
         WfProcessInternal proc = SharkUtilities.getProcess(shandle,
                                                            procId,
                                                            SharkUtilities.READ_ONLY_MODE);
         cel = SharkUtilities.getWorkflowProcess(shandle,
                                                 proc.package_id(shandle),
                                                 proc.manager_version(shandle),
                                                 proc.process_definition_id(shandle));
         if (cel != null && !MiscUtilities.isEmptyString(actId)) {
            WfActivityInternal act = proc.getActivity(shandle, actId);
            cel = SharkUtilities.getActivityDefinition(shandle,
                                                       act,
                                                       (WorkflowProcess) cel);
         }
      }
      if (cel == null) {
         throw new Exception("Can't find entity for parameters: mgrName="
                             + mgrName + ", procId=" + procId + ", actId=" + actId);
      }
      return SharkUtilities.createBasicEntity(cel);
   }

   // This will properly work for the most of the elements
   static WMEntity createBasicEntity(XMLComplexElement el) throws Exception {
      if (el == null)
         return null;

      WMEntity wment = new WMEntity();
      Package pkg = XMLUtil.getPackage(el);
      WorkflowProcess wp = XMLUtil.getWorkflowProcess(el);
      Activity act = XMLUtil.getActivity(el);
      wment.setPkgId(pkg.getId());
      wment.setPkgVer(pkg.getInternalVersion());
      if (wp != null) {
         wment.setWpId(wp.getId());
      }
      if (act != null) {
         wment.setActId(act.getId());
      }

      XMLComplexElement parentEl = null;
      if (!(el instanceof Package)) {
         parentEl = (XMLComplexElement) el.getParent().getParent();
         XMLElement parentId = parentEl.get("Id");
         if (parentId != null) {
            wment.setParentId(parentId.toValue());
         }
         wment.setParentType(parentEl.toName());
         if (parentEl.getParent() instanceof XMLCollection) {
            wment.setParentOrdNo(((XMLCollection) parentEl.getParent()).indexOf(parentEl));
         }
      }
      if (el.getParent() instanceof XMLCollection) {
         wment.setOrdNo(((XMLCollection) el.getParent()).indexOf(el));
      }

      XMLElement id = el.get("Id");
      if (id != null) {
         wment.setId(id.toValue());
      }
      XMLElement name = el.get("Name");
      if (name != null) {
         wment.setName(name.toValue());
      }
      wment.setType(el.toName());
      wment.setValue(el.toValue());

      return wment;
   }

   static Map createContextMap(WMSessionHandle shandle,
                               WfActivityInternal act,
                               ActualParameters actualParameters,
                               FormalParameters formalParameters) throws Exception {
      String packageId = act.container(shandle).package_id(shandle);
      String packageVer = act.container(shandle).manager_version(shandle);

      return createContextMap(shandle,
                              act.process_id(shandle),
                              act.key(shandle),
                              act.process_context(shandle),
                              actualParameters,
                              formalParameters,
                              packageId,
                              packageVer);
   }

   static Map createContextMap(WMSessionHandle shandle,
                               String procId,
                               String actId,
                               Map context,
                               ActualParameters actualParameters,
                               FormalParameters formalParameters,
                               String packageId,
                               String packageVer) throws Exception {
      Evaluator evaluator = SharkEngineManager.getInstance()
         .getScriptingManager()
         .getEvaluator(shandle,
                       SharkUtilities.getScriptType(shandle, packageId, packageVer));
      Map m = new HashMap();
      // When this is a subflow or tool activity, it's context contains
      // actual parameters to be passed to the referenced
      // process or tool in exact order. The map to be passed has to
      // have
      // the formal parameter ids of subflow process or application as
      // keys,
      // and actual parameter values of subflow or tool activity as
      // values
      // We iterate through the actual and formal parameter list
      // simultaneously and create a map.
      Iterator fps = formalParameters.toElements().iterator();
      // Get actual parameters definition of the subflow activity
      Iterator aps = actualParameters.toElements().iterator();
      while (aps.hasNext() && fps.hasNext()) {
         ActualParameter ap = (ActualParameter) aps.next();
         FormalParameter fp = (FormalParameter) fps.next();
         String fpMode = fp.getMode();
         Object val = null;
         // if the actual param is an expression, calculate it using
         // process evaluator
         String apVal = ap.toValue().trim();
         if (fpMode.equals(XPDLConstants.FORMAL_PARAMETER_MODE_IN)) {
            XMLCollectionElement dfOrFp = null;
            WorkflowProcess wp = XMLUtil.getWorkflowProcess(ap);
            dfOrFp = wp.getDataField(apVal);
            if (dfOrFp == null) {
               dfOrFp = XMLUtil.getPackage(wp).getDataField(apVal);
               if (dfOrFp == null) {
                  dfOrFp = wp.getFormalParameter(apVal);
               }
            }
            if (dfOrFp != null) {
               val = context.get(dfOrFp.getId());
            }
            if (val == null) {
               if (!(fp.getDataType().getDataTypes().getChoosen() instanceof SchemaType)) {
                  val = evaluator.evaluateExpression(shandle,
                                                     procId,
                                                     actId,
                                                     apVal,
                                                     context,
                                                     getJavaClass(fp));
               } else {
                  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                  dbf.setNamespaceAware(true);
                  DocumentBuilder db = dbf.newDocumentBuilder();
                  val = db.parse(new InputSource(new StringReader(apVal)));
               }
            }

            /*
             * if (!isComplexWRD(eval)) { val=getValue(fp,eval.toString()); } else { if
             * (!getJavaType(fp).endsWith(eval.getClass().getName())) { throw new
             * Exception ("Incorrect data type"); } else { val=eval; } }
             */
            // else, get the value of the activity context variable
         } else if (!fpMode.equals(XPDLConstants.FORMAL_PARAMETER_MODE_OUT)) {
            if (!context.containsKey(apVal)) {
               throw new Exception("There is no variable " + apVal + " in a context");
            }
            val = context.get(apVal);
         } else {
            val = getInitialValue(shandle, SharkUtilities.getVariable(actualParameters,
                                                                      apVal), true);
         }
         m.put(fp.getId(), val);
      }

      return m;
   }

   static Map createContextMap(WMSessionHandle shandle,
                               String procId,
                               String actId,
                               Map context,
                               ActualParameters actualParameters,
                               String packageId,
                               String packageVer) throws Exception {
      Evaluator evaluator = SharkEngineManager.getInstance()
         .getScriptingManager()
         .getEvaluator(shandle,
                       SharkUtilities.getScriptType(shandle, packageId, packageVer));
      Map m = new HashMap();
      // Get actual parameters definition of the subflow activity
      Iterator aps = actualParameters.toElements().iterator();
      int i = 0;
      while (aps.hasNext()) {
         ActualParameter ap = (ActualParameter) aps.next();
         Object val = null;
         // if the actual param is an expression, calculate it using
         // process evaluator
         String apVal = ap.toValue().trim();
         XMLCollectionElement dfOrFp = null;
         WorkflowProcess wp = XMLUtil.getWorkflowProcess(ap);
         dfOrFp = wp.getDataField(apVal);
         if (dfOrFp == null) {
            dfOrFp = XMLUtil.getPackage(wp).getDataField(apVal);
            if (dfOrFp == null) {
               dfOrFp = wp.getFormalParameter(apVal);
            }
         }

         if (dfOrFp != null) {
            val = context.get(apVal);
         }
         if (val == null) {
            apVal = SharkConstants.REMOTE_SUBPROCESS_EVAL_PARAM + String.valueOf(i++);
            val = evaluator.evaluateExpression(shandle,
                                               procId,
                                               actId,
                                               apVal,
                                               context,
                                               null);
         }

         m.put(apVal, val);
      }

      return m;
   }

   static XMLCollectionElement getXPDLVariable(WMSessionHandle shandle,
                                               String procIdOrMgrName,
                                               String variableId,
                                               boolean isManager) throws Exception {
      WorkflowProcess wp = null;
      if (isManager) {
         WfProcessMgrInternal mgr = SharkUtilities.getProcessMgr(shandle, procIdOrMgrName);
         wp = SharkUtilities.getWorkflowProcess(shandle,
                                                mgr.package_id(shandle),
                                                mgr.version(shandle),
                                                mgr.process_definition_id(shandle));
      } else {
         WfProcessInternal proc = SharkUtilities.getProcess(shandle,
                                                            procIdOrMgrName,
                                                            SharkUtilities.READ_ONLY_MODE);
         wp = SharkUtilities.getWorkflowProcess(shandle,
                                                proc.package_id(shandle),
                                                proc.manager_version(shandle),
                                                proc.process_definition_id(shandle));
      }

      DataField df = wp.getDataField(variableId);

      if (df == null) {
         df = XMLUtil.getPackage(wp).getDataField(variableId);
      }

      if (df == null) {
         // maybe this is a formal parameter of the process
         FormalParameter fp = wp.getFormalParameter(variableId);
         // if (fp == null) {
         // String msg = "process ";
         // if (isManager)
         // msg = "process manager ";
         // throw new Exception("There is no variable "
         // + variableId + " for the " + msg + procIdOrMgrName);
         // }
         return fp;
      }
      return df;
   }

   static synchronized boolean synchronizeXPDLCache(WMSessionHandle shandle)
      throws Exception {
      boolean hasChanges = false;
      SharkEngineManager.getInstance()
         .getCallbackUtilities()
         .info(shandle, "SharkUtilities -> synchronizing XPDL cache");
      // long st=System.currentTimeMillis();
      Map newCurrentVersions = new HashMap();

      XMLInterface xmlInterface = SharkEngineManager.getInstance().getXMLInterface();
      XMLInterface xpdlHandler = new XMLInterfaceForJDK13();
      xpdlHandler.setValidation(false);
      // synchronizing XPDL handler, so all operations will be performed
      // on the copy of XPDL cache, and after synchronizing is finished,
      // the changes are
      // applied to original.
      xpdlHandler.synchronizePackages(xmlInterface);
      RepositoryPersistenceManager repMgr = SharkEngineManager.getInstance()
         .getRepositoryPersistenceManager();

      // get info about engine XPDL caches
      long version = Version.getVersion();
      Set enginePkgIds = new HashSet(xpdlHandler.getAllPackageIds());
      Set enginePkgIdsWithVersionAndClassVersion = new HashSet();
      Iterator prep = enginePkgIds.iterator();
      while (prep.hasNext()) {
         String epid = (String) prep.next();
         Collection c = xpdlHandler.getAllPackageVersions(epid);
         Iterator prepc = c.iterator();
         while (prepc.hasNext()) {
            String epidWithVersion = SharkUtilities.createPkgIdWithVersionAndClassVersion(epid,
                                                                                          (String) prepc.next(),
                                                                                          version);
            enginePkgIdsWithVersionAndClassVersion.add(epidWithVersion);
         }
      }
      // get current state from repository
      // Map reposPkgIdsToVersionsAndClassVersions=new HashMap();
      Set reposPkgIdsWithVersionAndClassVersion = new HashSet();
      Set allPkgIds = new HashSet(repMgr.getExistingXPDLIds(shandle));
      Iterator it = allPkgIds.iterator();
      while (it.hasNext()) {
         String pkgId = (String) it.next();
         Set pkgVers = new HashSet(repMgr.getXPDLVersions(shandle, pkgId));
         Set pkgVersAndClassVers = new HashSet();
         Iterator pv = pkgVers.iterator();
         while (pv.hasNext()) {
            String pkgVer = (String) pv.next();
            pkgVersAndClassVers.add(createPkgVersionAndClassVersion(pkgVer,
                                                                    repMgr.getSerializedXPDLObjectVersion(shandle,
                                                                                                          pkgId,
                                                                                                          pkgVer)));
         }
         newCurrentVersions.put(pkgId, repMgr.getCurrentVersion(shandle, pkgId));
         // reposPkgIdsToVersionsAndClassVersions.put(pkgId,pkgVersAndClassVers);
         Iterator it2 = pkgVersAndClassVers.iterator();
         while (it2.hasNext()) {
            String pkgVerAndClassVer = (String) it2.next();
            String pkgIdWithVersionAndClassVersion = SharkUtilities.createPkgIdWithVersionAndClassVersion(pkgId,
                                                                                                          pkgVerAndClassVer);
            reposPkgIdsWithVersionAndClassVersion.add(pkgIdWithVersionAndClassVersion);
         }
      }

      // System.out.println("E="+enginePkgIdsWithVersionAndClassVersion);
      // System.out.println("R="+reposPkgIdsWithVersionAndClassVersion);
      // find packages that need to be loaded/reloaded/unloaded

      Set pkgsToLoad = new HashSet(reposPkgIdsWithVersionAndClassVersion);
      pkgsToLoad.removeAll(enginePkgIdsWithVersionAndClassVersion);

      Set pkgsToUnload = new HashSet(enginePkgIdsWithVersionAndClassVersion);
      pkgsToUnload.removeAll(reposPkgIdsWithVersionAndClassVersion);

      /*
       * Set pkgsToReload=new HashSet(); it=pkgsToLoad.iterator(); while (it.hasNext()) {
       * String pkgToLoad=SharkUtilities.getPkgId((String)it.next()); //Set refIds=new
       * HashSet(repMgr.getReferringXPDLIds(t,pkgToLoad)); Set
       * refIds=SharkUtilities.getAllReferences(t,repMgr,pkgToLoad); //new
       * HashSet(repMgr.getReferringXPDLIds(t,pkgToLoad)); //System.out.println("RefIds
       * for "+pkgToLoad+"="+refIds); Iterator it2=refIds.iterator(); while
       * (it2.hasNext()) { String refId=(String)it2.next(); Set
       * vers=(Set)reposPkgIdsToVersionsAndClassVersions.get(refId); Iterator
       * itv=vers.iterator(); while (itv.hasNext()) { String refVer=(String)itv.next();
       * String
       * pkgIdWithVer=SharkUtilities.createPkgIdWithVersionAndClassVersion(refId,refVer,repMgr.getSerializedXPDLObjectVersion(t,
       * refId, refVer)); if (!pkgsToLoad.contains(pkgIdWithVer)) {
       * pkgsToReload.add(pkgIdWithVer); } } } }
       */

      /*
       * System.out.println("EPIDWW="+enginePkgIdsWithVersion);
       * System.out.println("PTU="+pkgsToUnload); System.out.println("PTL="+pkgsToLoad);
       * System.out.println("PTRL="+pkgsToReload);
       */

      // pkgsToUnload.addAll(pkgsToReload);
      // pkgsToLoad.addAll(pkgsToReload);
      it = pkgsToUnload.iterator();
      while (it.hasNext()) {
         String pkgIdWithVersionAndClassVersion = (String) it.next();
         xpdlHandler.closePackageVersion(SharkUtilities.getPkgId(pkgIdWithVersionAndClassVersion),
                                         SharkUtilities.getPkgVersion(pkgIdWithVersionAndClassVersion));
      }
      it = pkgsToLoad.iterator();
      while (it.hasNext()) {
         String pkgIdWithVersionAndClassVersion = (String) it.next();
         String pkgId = SharkUtilities.getPkgId(pkgIdWithVersionAndClassVersion);
         String pkgVer = SharkUtilities.getPkgVersion(pkgIdWithVersionAndClassVersion);
         // SharkEngineManager.getInstance().getCallbackUtilities().info("Restoring
         // pkg "+pkgIdWithVersion);
         if (SharkUtilities.restorePackage(shandle, xpdlHandler, pkgId, pkgVer) == null) {
            throw new Exception("Problems while restoring packages!");
         }
      }

      if (pkgsToLoad.size() > 0 || pkgsToUnload.size() > 0) {
         hasChanges = true;
      }
      /*
       * if (pkgsToReload.size()>0) { SharkUtilities.clearProcessCache(); }
       */
      xmlInterface.synchronizePackages(xpdlHandler);
      currentPkgVersions = newCurrentVersions;
      xpdlHandler.closeAllPackages();
      xpdlHandler = null;
      /*
       * System.gc(); ((XMLInterfaceForJDK13)xmlInterface).printDebug();
       */
      return hasChanges;
   }

   /*
    * private static Set getAllReferences (RepositoryTransaction t,
    * RepositoryPersistenceManager repMgr, String pkgId) throws Exception { Set refs=new
    * HashSet(); Set refIds=new HashSet(repMgr.getReferringXPDLIds(t,pkgId));
    * refs.addAll(refIds); Iterator it=refIds.iterator(); while (it.hasNext()) { String
    * refId=(String)it.next();
    * refs.addAll(SharkUtilities.getAllReferences(t,repMgr,refId)); }
    * //System.out.println("pkgid="+pkgId+", refs="+refs); return refs; }
    */

   static void restorePackages(WMSessionHandle shandle) throws Exception {
      SharkUtilities.synchronizeXPDLCache(shandle);
   }

   static Package restorePackage(WMSessionHandle shandle,
                                 XMLInterface xmlInterface,
                                 String pkgId,
                                 String pkgVersion) throws Exception {
      RepositoryPersistenceManager repM = SharkEngineManager.getInstance()
         .getRepositoryPersistenceManager();
      long version = Version.getVersion();
      long repVersion = repM.getSerializedXPDLObjectVersion(shandle, pkgId, pkgVersion);
      Package pkg = null;
      if (version == repVersion) {
         pkg = xmlInterface.openPackageFromStream(repM.getSerializedXPDLObject(shandle,
                                                                               pkgId,
                                                                               pkgVersion),
                                                  false);
      } else {
         byte[] contXPDL = repM.getXPDL(shandle, pkgId, pkgVersion);
         pkg = xmlInterface.openPackageFromStream(contXPDL, true);
         List epIds = repM.getReferredXPDLIds(shandle, pkgId, pkgVersion);
         ArrayList eps = pkg.getExternalPackages().toElements();
         for (int i = 0; i < eps.size(); i++) {
            ExternalPackage ep = (ExternalPackage) eps.get(i);
            pkg.addExternalPackageMapping(ep.getHref(), (String) epIds.get(i));
         }
         pkg.setInternalVersion(pkgVersion);
         pkg.setReadOnly(true);
         byte[] cont = XMLUtil.serialize(pkg);
         // System.out.println("UPDC for pjg "+pkgId+", "+pkgVersion+"
         // to vers "+version);
         repM.updateXPDL(shandle, pkgId, pkgVersion, contXPDL, cont, version);
      }

      pkg.initCaches();
      return pkg;
   }

   static void clearProcessCache() throws Exception {
      CacheMgr cmgr = SharkEngineManager.getInstance().getCacheManager();
      if (cmgr != null) {
         ProcessCache pc = cmgr.getProcessCache();
         int size = pc.getSize();
         pc.setSize(0);
         pc.setSize(size);
      }
   }

   private static final String createPkgIdWithVersionAndClassVersion(String pkgId,
                                                                     String pkgVersion,
                                                                     long pkgClassVersion) {
      return (pkgId + "_" + pkgVersion + "_" + pkgClassVersion);
   }

   private static final String createPkgIdWithVersionAndClassVersion(String pkgId,
                                                                     String pkgVersionAndClassVersion) {
      return (pkgId + "_" + pkgVersionAndClassVersion);
   }

   private static final String createPkgVersionAndClassVersion(String pkgVersion,
                                                               long pkgClassVersion) {
      return (pkgVersion + "_" + pkgClassVersion);
   }

   private static final String getPkgId(String pkgIdWithVersionAndClassVersion) {
      String[] tokens = MiscUtilities.tokenize(pkgIdWithVersionAndClassVersion, "_");
      return pkgIdWithVersionAndClassVersion.substring(0,
                                                       pkgIdWithVersionAndClassVersion.length()
                                                             - tokens[tokens.length - 1].length()
                                                             - tokens[tokens.length - 2].length()
                                                             - 2);
   }

   private static final String getPkgVersion(String pkgIdWithVersion) {
      String[] tokens = MiscUtilities.tokenize(pkgIdWithVersion, "_");
      return tokens[tokens.length - 2];
   }

   /*
    * private static final String getPkgVersion2(String versionAndClassVersion) { String[]
    * tokens = MiscUtilities.tokenize(versionAndClassVersion, "_"); return tokens[0]; }
    */
   static String getCurrentPkgVersion(WMSessionHandle shandle,
                                      String pkgId,
                                      boolean fromCache) throws Exception {
      String curVer = null;
      if (fromCache) {
         curVer = (String) currentPkgVersions.get(pkgId);
      }
      if (curVer != null) {
         return curVer;
      }

      curVer = SharkEngineManager.getInstance()
         .getRepositoryPersistenceManager()
         .getCurrentVersion(shandle, pkgId);

      return curVer;
   }

   static String getScriptType(WMSessionHandle shandle, String pkgId, String pkgVer)
      throws Exception {
      Package pkg = getPackage(shandle, pkgId, pkgVer);
      String scriptType = pkg.getScript().getType();
      return scriptType;
   }

   static String getNextId(String idName) {
      try {
         return SharkEngineManager.getInstance()
            .getInstancePersistenceManager()
            .getNextId(idName);
      } catch (PersistenceException pe) {
         throw new RootError("Fatal error: couldn't allocate an Id!", pe);
      }
   }

   static String extractExceptionName(Exception tage) {
      String causeClassName = "";
      if (tage != null) {
         Throwable cause = tage.getCause();
         if (cause != null) {
            causeClassName = cause.getClass().getName();
         }
      }
      return causeClassName;
   }

   static WorkflowProcess getWorkflowProcess(WMSessionHandle shandle,
                                             XMLElement el,
                                             String procDefId) throws Exception {
      Package pkg = XMLUtil.getPackage(el);
      WorkflowProcess wp = pkg.getWorkflowProcess(procDefId);
      if (wp == null) {
         List possPkgs = SharkUtilities.getPossibleExternalPackages(shandle, pkg);
         while (possPkgs.size() > 0) {
            for (int i = 0; i < possPkgs.size(); i++) {
               Package ePkg = (Package) possPkgs.get(i);
               wp = ePkg.getWorkflowProcess(procDefId);
               if (wp != null) {
                  break;
               }
            }
            if (wp == null) {
               List ps = new ArrayList(possPkgs);
               possPkgs.clear();
               for (int i = 0; i < ps.size(); i++) {
                  Package ePkg = (Package) ps.get(i);
                  possPkgs.addAll(SharkUtilities.getPossibleExternalPackages(shandle,
                                                                             ePkg));
               }
            } else {
               break;
            }
         }
      }
      // System.err.println("Search for procDefId "+procDefId+" finished by finding wp
      // from pkg
      // [xpdlV="+XMLUtil.getPackage(wp).getRedefinableHeader().getVersion()+",intVer="+XMLUtil.getPackage(wp).getInternalVersion()+"]");
      // if (wp==null) {
      // throw new Exception("SharkUtilities->getWorkflowProcess() -> can't find workflow
      // process definition for Id="+procDefId);
      // }
      return wp;
   }

   static Application getApplication(WMSessionHandle shandle, XMLElement el, String appId)
      throws Exception {
      Application app = null;
      WorkflowProcess wp = XMLUtil.getWorkflowProcess(el);
      app = wp.getApplication(appId);
      if (app == null) {
         Package pkg = XMLUtil.getPackage(wp);
         app = pkg.getApplication(appId);
         if (app == null) {
            List possPkgs = SharkUtilities.getPossibleExternalPackages(shandle, pkg);
            while (possPkgs.size() > 0) {
               for (int i = 0; i < possPkgs.size(); i++) {
                  Package ePkg = (Package) possPkgs.get(i);
                  app = ePkg.getApplication(appId);
                  if (app != null) {
                     break;
                  }
               }
               if (app == null) {
                  List ps = new ArrayList(possPkgs);
                  possPkgs.clear();
                  for (int i = 0; i < ps.size(); i++) {
                     Package ePkg = (Package) ps.get(i);
                     possPkgs.addAll(SharkUtilities.getPossibleExternalPackages(shandle,
                                                                                ePkg));
                  }
               } else {
                  break;
               }
            }
         }
      }

      // System.err.println("Search for appId "+appId+" finished by finding app from pkg
      // [xpdlV="+XMLUtil.getPackage(app).getRedefinableHeader().getVersion()+",intVer="+XMLUtil.getPackage(app).getInternalVersion()+"]");
      if (app == null) {
         throw new Exception("SharkUtilities->getApplication() -> can't find application definition for Id="
                             + appId);
      }
      return app;
   }

   static Participant getParticipant(WMSessionHandle shandle, XMLElement el, String partId)
      throws Exception {
      Participant p = null;
      WorkflowProcess wp = XMLUtil.getWorkflowProcess(el);
      p = wp.getParticipant(partId);
      if (p == null) {
         Package pkg = XMLUtil.getPackage(el);
         p = pkg.getParticipant(partId);
         if (p == null) {
            List possPkgs = SharkUtilities.getPossibleExternalPackages(shandle, pkg);
            while (possPkgs.size() > 0) {
               for (int i = 0; i < possPkgs.size(); i++) {
                  Package ePkg = (Package) possPkgs.get(i);
                  p = ePkg.getParticipant(partId);
                  if (p != null) {
                     break;
                  }
               }
               if (p == null) {
                  List ps = new ArrayList(possPkgs);
                  possPkgs.clear();
                  for (int i = 0; i < ps.size(); i++) {
                     Package ePkg = (Package) ps.get(i);
                     possPkgs.addAll(SharkUtilities.getPossibleExternalPackages(shandle,
                                                                                ePkg));
                  }
               } else {
                  break;
               }
            }
         }
      }
      // System.err.println("Search for partId "+partId+" finished by finding p from pkg
      // [xpdlV="+XMLUtil.getPackage(p).getRedefinableHeader().getVersion()+",intVer="+XMLUtil.getPackage(p).getInternalVersion()+"]");

      // if (p==null) {
      // throw new Exception("SharkUtilities->getParticipant() -> can't find participant
      // definition for Id="+partId);
      // }
      return p;
   }

   static List getPossibleExternalPackages(WMSessionHandle shandle, Package pkg)
      throws Exception {
      List ret = new ArrayList();
      String xpdlPkgVer = pkg.getRedefinableHeader().getVersion();
      boolean isPDblV = false;
      try {
         Double.parseDouble(xpdlPkgVer);
         isPDblV = true;
      } catch (Exception ex) {
      }
      List epIds = new ArrayList(pkg.getExternalPackageIds());
      if (!isPDblV) {
         for (int j = 0; j < epIds.size(); j++) {
            String epId = (String) epIds.get(j);
            Package p = SharkUtilities.getPackage(shandle, epId, null);
            ret.add(p);
         }
      } else {
         // System.err.println("Searching for eps for pkg
         // [xpdlV="+xpdlPkgVer+",intV="+pkg.getInternalVersion()+"]");
         double dblV = Double.parseDouble(xpdlPkgVer);
         for (int j = 0; j < epIds.size(); j++) {
            String epId = (String) epIds.get(j);
            RepositoryPersistenceManager repM = SharkEngineManager.getInstance()
               .getRepositoryPersistenceManager();
            List epVers = repM.getXPDLVersions(shandle, epId);
            long maxUplTime = -1;
            double minDiff = Double.MAX_VALUE;
            Package extPkg = null;
            for (int i = 0; i < epVers.size(); i++) {
               String epVer = (String) epVers.get(i);
               Package ePkg = SharkUtilities.getPackage(shandle, epId, epVer);
               String extPkgXPDLVer = ePkg.getRedefinableHeader().getVersion();
               boolean isDblV = false;
               try {
                  Double.parseDouble(extPkgXPDLVer);
                  isDblV = true;
               } catch (Exception ex) {
               }
               long uplT = repM.getXPDLUploadTime(shandle, epId, epVer);
               if (!isDblV) {
                  if (minDiff == Double.MAX_VALUE) {
                     if (uplT > maxUplTime) {
                        extPkg = ePkg;
                        maxUplTime = uplT;
                     }
                  }
               } else {
                  double diff = dblV - Double.parseDouble(extPkgXPDLVer);
                  if (diff >= 0) {
                     if (diff <= minDiff) {
                        if (minDiff == Double.MAX_VALUE) {
                           extPkg = ePkg;
                           maxUplTime = uplT;
                        } else if (diff < minDiff) {
                           extPkg = ePkg;
                           maxUplTime = uplT;
                        } else { // diff==minDiff
                           if (uplT > maxUplTime) {
                              extPkg = ePkg;
                              maxUplTime = uplT;
                           }
                        }
                        minDiff = diff;
                     }
                  }
               }
            }
            if (extPkg != null) {
               ret.add(extPkg);
            }
         }
      }
      return ret;
   }

   static XMLCollectionElement getVariable(XMLElement el, String varId) throws Exception {
      WorkflowProcess wp = XMLUtil.getWorkflowProcess(el);
      Map m = wp.getAllVariables();
      return (XMLCollectionElement) m.get(varId);
   }

   static void changeProcessState(WMSessionHandle shandle,
                                  String processId,
                                  String new_state)
      throws Exception,
         InvalidState,
         TransitionNotAllowed {

      WfProcessInternal procInternal = SharkUtilities.getProcess(shandle,
                                                                 processId,
                                                                 SharkUtilities.WRITE_MODE);
      if (procInternal == null) {
         throw new Exception("Process " + processId + " does not exist!");
      }

      String curState = procInternal.state(shandle);
      if (!SharkConstants.possibleProcessStates.contains(new_state)) {
         throw new InvalidState("Can't change process state to "
                                + new_state + " - no such state!");
      }
      if (!SharkUtilities.valid_process_states(procInternal.state(shandle))
         .contains(new_state)) {
         throw new TransitionNotAllowed("Current process state is "
                                        + curState + " - can't change to state "
                                        + new_state + "!");
      }
      if (new_state.equals(SharkConstants.STATE_CLOSED_ABORTED)) {
         try {
            procInternal.abort(shandle);
         } catch (CannotStop cns) {
            throw new TransitionNotAllowed(cns);
         } catch (NotRunning nr) {
            throw new TransitionNotAllowed(nr);
         }
      } else if (new_state.equals(SharkConstants.STATE_CLOSED_COMPLETED)) {
         throw new TransitionNotAllowed("Current process state is "
                                        + curState + " - can't change to state "
                                        + new_state + "!");
      } else if (new_state.equals(SharkConstants.STATE_CLOSED_TERMINATED)) {
         try {
            procInternal.terminate(shandle);
         } catch (CannotStop cns) {
            throw new TransitionNotAllowed(cns);
         } catch (NotRunning nr) {
            throw new TransitionNotAllowed(nr);
         }
      } else if (new_state.equals(SharkConstants.STATE_OPEN_NOT_RUNNING_NOT_STARTED)) {
         throw new TransitionNotAllowed("Current process state is "
                                        + curState + " - can't change to state "
                                        + new_state + "!");
      } else if (new_state.equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
         try {
            procInternal.suspend(shandle);
         } catch (AlreadySuspended as) {
            throw new TransitionNotAllowed(as);
         } catch (CannotSuspend cns) {
            throw new TransitionNotAllowed(cns);
         } catch (NotRunning nr) {
            throw new TransitionNotAllowed(nr);
         }
      } else { // new state is open.running
         if (curState.equals(SharkConstants.STATE_OPEN_NOT_RUNNING_NOT_STARTED)) {
            try {
               procInternal.start(shandle);
            } catch (CannotStart cns) {
               throw new TransitionNotAllowed(cns);
            } catch (AlreadyRunning ar) {
               throw new TransitionNotAllowed(ar);
            }
         } else {
            try {
               procInternal.resume(shandle);
            } catch (Exception exc) {
               throw new TransitionNotAllowed(exc);
            }
         }
      }
   }

   static void changeActivityState(WMSessionHandle shandle,
                                   String procId,
                                   String actId,
                                   String new_state)
      throws Exception,
         InvalidState,
         TransitionNotAllowed {
      WfActivityInternal actInternal = getActivity(shandle,
                                                   procId,
                                                   actId,
                                                   SharkUtilities.WRITE_MODE);
      if (actInternal == null) {
         throw new Exception("Activity " + actId + " does not exist");
      }
      String curState = actInternal.state(shandle);
      if (!SharkConstants.possibleActivityStates.contains(new_state)) {
         throw new InvalidState("Can't change activity state to "
                                + new_state + " - no such state!");
      }

      if (!SharkUtilities.valid_activity_states(curState).contains(new_state)) {
         throw new TransitionNotAllowed("Current activity state is "
                                        + curState + " - can't change to state "
                                        + new_state + "!");
      }
      if (new_state.equals(SharkConstants.STATE_CLOSED_ABORTED)) {
         try {
            actInternal.abort(shandle);
         } catch (CannotStop cns) {
            throw new TransitionNotAllowed(cns);
         } catch (NotRunning nr) {
            throw new TransitionNotAllowed(nr);
         }
      } else if (new_state.equals(SharkConstants.STATE_CLOSED_COMPLETED)) {
         try {
            actInternal.complete(shandle);
         } catch (CannotComplete cnc) {
            throw new TransitionNotAllowed(cnc);
         }
      } else if (new_state.equals(SharkConstants.STATE_CLOSED_TERMINATED)) {
         try {
            actInternal.terminate(shandle);
         } catch (CannotStop cns) {
            throw new TransitionNotAllowed(cns);
         } catch (NotRunning nr) {
            throw new TransitionNotAllowed(nr);
         }
      } else if (new_state.equals(SharkConstants.STATE_OPEN_NOT_RUNNING_NOT_STARTED)) {
         if (curState.equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
            try {
               actInternal.resume(shandle);
            } catch (CannotResume cnr) {
               throw new TransitionNotAllowed(cnr);
            } catch (NotSuspended ns) {
               throw new TransitionNotAllowed(ns);
            }
         } else {
            String executor = SharkEngineManager.getInstance()
               .getCallbackUtilities()
               .getUserId(shandle);
            String curUser = actInternal.getResourceUsername(shandle);

            String usrToUse = curUser;
            if (usrToUse == null) {
               usrToUse = executor;
            }
            actInternal.set_accepted_status(shandle, false, usrToUse);
         }
      } else if (new_state.equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
         try {
            actInternal.suspend(shandle);
         } catch (AlreadySuspended as) {
            throw new TransitionNotAllowed(as);
         } catch (CannotSuspend cns) {
            throw new TransitionNotAllowed(cns);
         } catch (NotRunning nr) {
            throw new TransitionNotAllowed(nr);
         }
      } else { // new state is open.running
         if (curState.equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
            try {
               actInternal.resume(shandle);
            } catch (CannotResume cnr) {
               throw new TransitionNotAllowed(cnr);
            } catch (NotSuspended ns) {
               throw new TransitionNotAllowed(ns);
            }
         } else { // curState is NOT_RUNNING_NOT_STARTED
            actInternal.set_accepted_status(shandle,
                                            true,
                                            SharkEngineManager.getInstance()
                                               .getCallbackUtilities()
                                               .getUserId(shandle));
         }
      }
   }

   static void methodEnd(WMSessionHandle shandle, long stamp, String location, Object o) {
      CallbackUtilities cus = SharkEngineManager.getInstance().getCallbackUtilities();
      if (cus != null) {
         cus.methodEnd(shandle, stamp, location, o);
      } else {
         long diff = System.currentTimeMillis() - stamp;
         String logEntry = location + " took " + diff + " millis";
         logEntry += " for "
                     + ((o != null) ? o.toString() : "null") + ","
                     + ((shandle != null) ? shandle.toString() : "");
         System.err.println(logEntry);
      }
   }

   static long methodStart(WMSessionHandle shandle, String location) {
      CallbackUtilities cus = SharkEngineManager.getInstance().getCallbackUtilities();
      if (cus != null) {
         return cus.methodStart(shandle, location);
      }
      return System.currentTimeMillis();
   }

   static WMActivityInstance getInstance(WMSessionHandle shandle, WfActivityInternal aInt)
      throws Exception {
      WMActivityInstance ai = new WMActivityInstance();
      ai.setActivityDefinitionId(aInt.activity_definition_id(shandle));
      ai.setId(aInt.key(shandle));
      ai.setName(aInt.name(shandle));
      ai.setPriority(aInt.priority(shandle));
      ai.setProcessInstanceId(aInt.process_id(shandle));
      ai.setState(WMActivityInstanceState.valueOf(aInt.state(shandle)));
      ai.setDescription(aInt.description(shandle));
      return ai;
   }

   static WMActivityInstance getInstance(ActivityPersistenceObject apo) throws Exception {
      WMActivityInstance ai = new WMActivityInstance();
      ai.setActivityDefinitionId(apo.getActivityDefinitionId());
      ai.setId(apo.getId());
      ai.setName(apo.getName());
      ai.setPriority(apo.getPriority());
      ai.setProcessInstanceId(apo.getProcessId());
      ai.setState(WMActivityInstanceState.valueOf(apo.getState()));
      ai.setDescription(apo.getDescription());
      return ai;
   }

   static WMProcessInstance getInstance(WMSessionHandle shandle, WfProcessInternal pInt)
      throws Exception {
      WMProcessInstance pi = new WMProcessInstance();
      pi.setId(pInt.key(shandle));
      pi.setName(pInt.name(shandle));
      pi.setPriority(pInt.priority(shandle));
      pi.setProcessDefinitionId(pInt.process_definition_id(shandle));
      pi.setState(WMProcessInstanceState.valueOf(pInt.state(shandle)));
      pi.setDescription(pInt.description(shandle));
      pi.setProcessFactoryName(pInt.manager_name(shandle));
      return pi;
   }

   static WMProcessInstance getInstance(ProcessPersistenceObject ppo) {
      WMProcessInstance pi = new WMProcessInstance();
      pi.setId(ppo.getId());
      pi.setName(ppo.getName());
      pi.setPriority(ppo.getPriority());
      pi.setProcessDefinitionId(MiscUtilities.getProcessMgrProcDefId(ppo.getProcessMgrName()));
      pi.setState(WMProcessInstanceState.valueOf(ppo.getState()));
      pi.setDescription(ppo.getDescription());
      pi.setProcessFactoryName(ppo.getProcessMgrName());
      return pi;
   }

   static WMWorkItem getInstance(WMSessionHandle shandle, WfAssignmentInternal aint)
      throws Exception {
      WMWorkItem wi = new WMWorkItem();
      wi.setId(MiscUtilities.createAssignmentKey(aint.activityId(shandle),
                                                 aint.resourceUsername(shandle)));
      WMParticipant p = new WMParticipant();
      p.setName(aint.resourceUsername(shandle));
      wi.setParticipant(p);

      wi.setActivityInstanceId(aint.activityId(shandle));

      wi.setName(aint.activity(shandle).name(shandle));
      wi.setPriority(aint.activity(shandle).priority(shandle));

      wi.setActivityDefinitionId(aint.activity(shandle).activity_definition_id(shandle));
      wi.setProcessInstanceId(aint.processId(shandle));

      if (aint.get_accepted_status(shandle)) {
         wi.setState(WMWorkItemState.OPEN_RUNNING);
      } else {
         wi.setState(WMWorkItemState.OPEN_NOTRUNNING);
      }

      wi.setDescription(aint.activity(shandle).description(shandle));

      return wi;
   }

   static WMWorkItem getInstance(AssignmentPersistenceObject api,
                                 ActivityPersistenceObject acpi) {
      WMWorkItem wi = new WMWorkItem();
      wi.setId(MiscUtilities.createAssignmentKey(api.getActivityId(),
                                                 api.getResourceUsername()));
      WMParticipant p = new WMParticipant();
      p.setName(api.getResourceUsername());
      wi.setParticipant(p);

      wi.setActivityInstanceId(api.getActivityId());

      wi.setName(acpi.getName());
      wi.setPriority(acpi.getPriority());

      wi.setActivityDefinitionId(acpi.getActivityDefinitionId());
      wi.setProcessInstanceId(acpi.getProcessId());

      if (api.isAccepted()) {
         wi.setState(WMWorkItemState.OPEN_RUNNING);
      } else {
         wi.setState(WMWorkItemState.OPEN_NOTRUNNING);
      }

      wi.setDescription(acpi.getDescription());

      return wi;
   }

   static WMProcessDefinition getInstance(WMSessionHandle shandle,
                                          ProcessMgrPersistenceObject po)
      throws Exception {
      WMProcessDefinition pd = new WMProcessDefinition();
      pd.setId(po.getProcessDefinitionId());
      pd.setName(po.getName());
      pd.setPackageId(po.getPackageId());
      pd.setState(WMProcessDefinitionState.valueOf(1 - po.getState()));
      WorkflowProcess wp = SharkUtilities.getWorkflowProcess(shandle,
                                                             po.getPackageId(),
                                                             po.getVersion(),
                                                             po.getProcessDefinitionId());
      pd.setDescription(wp.getProcessHeader().getDescription());
      return pd;
   }

   static WMProcessDefinition getInstance(WMSessionHandle shandle,
                                          WfProcessMgrInternal pmgrInt) throws Exception {
      WMProcessDefinition pd = new WMProcessDefinition();
      pd.setId(pmgrInt.process_definition_id(shandle));
      pd.setName(pmgrInt.name(shandle));
      pd.setPackageId(pmgrInt.package_id(shandle));
      pd.setState(WMProcessDefinitionState.valueOf(1 - pmgrInt.process_mgr_state(shandle)
         .value()));
      pd.setDescription(pmgrInt.description(shandle));
      return pd;
   }

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.