0001: package org.enhydra.shark.xpdl;
0002:
0003: import java.io.ByteArrayInputStream;
0004: import java.io.ByteArrayOutputStream;
0005: import java.io.File;
0006: import java.io.FileInputStream;
0007: import java.io.FileOutputStream;
0008: import java.io.ObjectInputStream;
0009: import java.io.ObjectOutputStream;
0010: import java.io.OutputStream;
0011: import java.io.StringReader;
0012: import java.util.ArrayList;
0013: import java.util.Calendar;
0014: import java.util.Collection;
0015: import java.util.GregorianCalendar;
0016: import java.util.HashMap;
0017: import java.util.HashSet;
0018: import java.util.Iterator;
0019: import java.util.List;
0020: import java.util.Map;
0021: import java.util.Properties;
0022: import java.util.Set;
0023:
0024: import javax.xml.parsers.DocumentBuilder;
0025: import javax.xml.parsers.DocumentBuilderFactory;
0026: import javax.xml.transform.Transformer;
0027: import javax.xml.transform.TransformerFactory;
0028: import javax.xml.transform.dom.DOMSource;
0029: import javax.xml.transform.stream.StreamResult;
0030:
0031: import org.apache.xerces.util.XMLChar;
0032: import org.enhydra.shark.utilities.SequencedHashMap;
0033: import org.enhydra.shark.xpdl.elements.Activities;
0034: import org.enhydra.shark.xpdl.elements.Activity;
0035: import org.enhydra.shark.xpdl.elements.ActivitySet;
0036: import org.enhydra.shark.xpdl.elements.ActivitySets;
0037: import org.enhydra.shark.xpdl.elements.Application;
0038: import org.enhydra.shark.xpdl.elements.BlockActivity;
0039: import org.enhydra.shark.xpdl.elements.DataField;
0040: import org.enhydra.shark.xpdl.elements.ExtendedAttribute;
0041: import org.enhydra.shark.xpdl.elements.ExtendedAttributes;
0042: import org.enhydra.shark.xpdl.elements.FinishMode;
0043: import org.enhydra.shark.xpdl.elements.FormalParameter;
0044: import org.enhydra.shark.xpdl.elements.Join;
0045: import org.enhydra.shark.xpdl.elements.Manual;
0046: import org.enhydra.shark.xpdl.elements.Package;
0047: import org.enhydra.shark.xpdl.elements.Participant;
0048: import org.enhydra.shark.xpdl.elements.RedefinableHeader;
0049: import org.enhydra.shark.xpdl.elements.Responsible;
0050: import org.enhydra.shark.xpdl.elements.Responsibles;
0051: import org.enhydra.shark.xpdl.elements.Split;
0052: import org.enhydra.shark.xpdl.elements.StartMode;
0053: import org.enhydra.shark.xpdl.elements.SubFlow;
0054: import org.enhydra.shark.xpdl.elements.Transition;
0055: import org.enhydra.shark.xpdl.elements.TransitionRef;
0056: import org.enhydra.shark.xpdl.elements.TransitionRefs;
0057: import org.enhydra.shark.xpdl.elements.TransitionRestriction;
0058: import org.enhydra.shark.xpdl.elements.TransitionRestrictions;
0059: import org.enhydra.shark.xpdl.elements.Transitions;
0060: import org.enhydra.shark.xpdl.elements.WorkflowProcess;
0061: import org.enhydra.shark.xpdl.elements.WorkflowProcesses;
0062: import org.w3c.dom.Document;
0063: import org.w3c.dom.Element;
0064: import org.w3c.dom.NamedNodeMap;
0065: import org.w3c.dom.Node;
0066: import org.w3c.dom.NodeList;
0067: import org.xml.sax.InputSource;
0068:
0069: /**
0070: * Class with utilities to read/write XPDLs from/to XML.
0071: *
0072: * @author Sasa Bojanic
0073: */
0074: public class XMLUtil {
0075:
0076: public final static String XMLNS = "http://www.wfmc.org/2002/XPDL1.0";
0077: public final static String XMLNS_XPDL = "http://www.wfmc.org/2002/XPDL1.0";
0078: public final static String XMLNS_XSI = "http://www.w3.org/2001/XMLSchema-instance";
0079: public final static String XSI_SCHEMA_LOCATION = "http://www.wfmc.org/2002/XPDL1.0 http://wfmc.org/standards/docs/TC-1025_schema_10_xpdl.xsd";
0080:
0081: /**
0082: * Determines the number of string toFind within string toSearch.
0083: */
0084: public static int howManyStringsWithinString(String toSearch,
0085: String toFind) {
0086: try {
0087: int startAt = 0;
0088: int howMany = 0;
0089:
0090: int fnd;
0091: while ((fnd = toSearch.indexOf(toFind, startAt)) != -1) {
0092: howMany++;
0093: startAt = (fnd + toFind.length());
0094: }
0095: return howMany;
0096: } catch (Exception ex) {
0097: return -1;
0098: }
0099: }
0100:
0101: public static String getCanonicalPath(String relpath,
0102: String basedir, boolean canBeDirectory) {
0103: try {
0104: File f = new File(relpath);
0105: if (!f.isAbsolute()) {
0106: f = f.getAbsoluteFile();
0107: if (!f.exists()) {
0108: f = new File(XMLUtil.createPath(basedir, relpath));
0109: }
0110: }
0111: if (!f.exists() || (f.isDirectory() && !canBeDirectory)) {
0112: System.err.println("The file " + f.getAbsolutePath()
0113: + " does not exist");
0114: return null;
0115: }
0116:
0117: return getCanonicalPath(f);
0118: } catch (Exception ex) {
0119: ex.printStackTrace();
0120: return null;
0121: }
0122: }
0123:
0124: public static String getCanonicalPath(String path,
0125: boolean canBeDirectory) {
0126: File f = new File(path);
0127: if (!f.isAbsolute()) {
0128: f = new File(System.getProperty("user.dir")
0129: + File.separator + path);
0130: }
0131: if (!f.exists() || (f.isDirectory() && !canBeDirectory)) {
0132: System.err.println("The file " + f.getAbsolutePath()
0133: + " does not exist");
0134: return null;
0135: }
0136:
0137: return getCanonicalPath(f);
0138: }
0139:
0140: private static String getCanonicalPath(File f) {
0141: try {
0142: return f.getCanonicalPath();
0143: } catch (Exception ex) {
0144: return f.getAbsolutePath();
0145: }
0146: }
0147:
0148: public static String getNameSpacePrefix(Node node) {
0149: String nameSpacePrefix = node.getPrefix();
0150: if (nameSpacePrefix != null) {
0151: nameSpacePrefix += ":";
0152: } else {
0153: nameSpacePrefix = "";
0154: }
0155: return nameSpacePrefix;
0156: }
0157:
0158: public static Node getChildByName(Node parent, String childName) {
0159: NodeList children = parent.getChildNodes();
0160: for (int i = 0; i < children.getLength(); ++i) {
0161: Node child = children.item(i);
0162: if (child.getNodeName().equals(childName)) {
0163: return child;
0164: }
0165: }
0166: return null;
0167: }
0168:
0169: public static String getId(Node node) {
0170: try {
0171: NamedNodeMap nnm = node.getAttributes();
0172: Node attrib = nnm.getNamedItem("Id");
0173: Object ID;
0174: if (attrib.hasChildNodes()) {
0175: ID = attrib.getChildNodes().item(0).getNodeValue();
0176: } else {
0177: ID = attrib.getNodeValue();
0178: }
0179: return ID.toString();
0180: } catch (Exception ex) {
0181: return "";
0182: }
0183: }
0184:
0185: public static synchronized String getIdFromFile(String xmlFile) {
0186: try {
0187: // Create parser
0188: DocumentBuilderFactory factory = DocumentBuilderFactory
0189: .newInstance();
0190: factory.setValidating(false);
0191: DocumentBuilder parser = factory.newDocumentBuilder();
0192: Document document = null;
0193:
0194: // Parse the Document
0195: try {
0196: //document=parser.parse(xmlFile);
0197: File f = new File(xmlFile);
0198: if (!f.exists()) {
0199: f = new File(f.getCanonicalPath());
0200: }
0201: document = parser.parse(new InputSource(
0202: new FileInputStream(f))); // Fixed by Harald Meister
0203: } catch (Exception ex) {
0204: document = parser.parse(new InputSource(
0205: new StringReader(xmlFile)));
0206: }
0207: return XMLUtil.getId(document.getDocumentElement());
0208: } catch (Exception ex) {
0209: return "";
0210: } finally {
0211:
0212: }
0213: }
0214:
0215: public static String getContent(Node node,
0216: boolean omitXMLDeclaration) {
0217: try {
0218: ByteArrayOutputStream baos = new ByteArrayOutputStream();
0219:
0220: // Use a Transformer for output
0221: TransformerFactory tFactory = TransformerFactory
0222: .newInstance();
0223: Transformer transformer = tFactory.newTransformer();
0224: transformer.setOutputProperty("indent", "yes");
0225: transformer.setOutputProperty(
0226: "{http://xml.apache.org/xslt}indent-amount", "4");
0227: transformer.setOutputProperty("encoding", "UTF-8");
0228: if (omitXMLDeclaration) {
0229: transformer.setOutputProperty("omit-xml-declaration",
0230: "yes");
0231: }
0232:
0233: DOMSource source = new DOMSource(node);
0234: StreamResult result = new StreamResult(baos);
0235: transformer.transform(source, result);
0236:
0237: String cont = baos.toString("UTF8");
0238:
0239: baos.close();
0240: return cont;
0241: } catch (Exception ex) {
0242: return "";
0243: }
0244: }
0245:
0246: public static String getChildNodesContent(Node node) {
0247: String txt = "";
0248: if (node != null) {
0249: if (node.hasChildNodes()) {
0250: txt = XMLUtil.getContent(node, true);
0251: try {
0252: Node fc = node.getFirstChild();
0253: String fcnc = XMLUtil.getContent(fc, true);
0254: String closedTag = "</" + node.getNodeName() + ">";
0255: if (fcnc.trim().length() > 0) {
0256: fcnc = fcnc.trim();
0257: }
0258:
0259: int i1, i2;
0260: i1 = txt.indexOf(fcnc);
0261: i2 = txt.lastIndexOf(closedTag);
0262: txt = txt.substring(i1, i2).trim();
0263: } catch (Exception ex) {
0264: NodeList nl = node.getChildNodes();
0265: txt = "";
0266: try {
0267: for (int i = 0; i < nl.getLength(); i++) {
0268: Node sn = nl.item(i);
0269: if (sn instanceof Element) {
0270: txt += XMLUtil.getContent(sn, true);
0271: } else {
0272: String nv = sn.getNodeValue();
0273: // trim only the begining of the string
0274: if (i > 0) {
0275: txt += nv.substring(1);
0276: } else if (i == 0
0277: && nv.trim().length() == 0) {
0278: continue;
0279: } else {
0280: txt += nv;
0281: }
0282: }
0283: }
0284: } catch (Exception ex2) {
0285: }
0286: }
0287: }
0288: }
0289: return txt;
0290: }
0291:
0292: public static String getShortClassName(String fullClassName) {
0293: int lastDot = fullClassName.lastIndexOf(".");
0294: if (lastDot >= 0) {
0295: return fullClassName.substring(lastDot + 1, fullClassName
0296: .length());
0297: }
0298: return fullClassName;
0299: }
0300:
0301: public static String getExternalPackageId(String extPkgHref) {
0302: // System.out.println("EPID1="+extPkgHref);
0303: int indBSL = extPkgHref.lastIndexOf("\\");
0304: int indSL = extPkgHref.lastIndexOf("/");
0305: int indDotXPDL = extPkgHref.lastIndexOf(".xpdl");
0306: if (indSL != -1 || indBSL != -1) {
0307: int ind = indSL;
0308: if (indBSL > indSL) {
0309: ind = indBSL;
0310: }
0311: extPkgHref = extPkgHref.substring(ind + 1);
0312: }
0313: if (indDotXPDL != -1) {
0314: extPkgHref = extPkgHref.substring(0,
0315: extPkgHref.length() - 5);
0316: }
0317: // System.out.println("EPID2="+extPkgHref);
0318: return extPkgHref;
0319: }
0320:
0321: public static Node parseSchemaNode(String toParse, boolean isFile) {
0322: Document document = null;
0323:
0324: DocumentBuilderFactory factory = DocumentBuilderFactory
0325: .newInstance();
0326: factory.setValidating(false);
0327:
0328: // Parse the Document and traverse the DOM
0329: try {
0330: ParsingErrors pErrors = new ParsingErrors();
0331:
0332: DocumentBuilder parser = factory.newDocumentBuilder();
0333: parser.setErrorHandler(pErrors);
0334: //document=parser.parse(refToFile);
0335: if (isFile) {
0336: File f = new File(toParse);
0337: if (!f.exists()) {
0338: throw new Exception();
0339: }
0340:
0341: document = parser.parse(new InputSource(
0342: new FileInputStream(f))); // Fixed by Harald Meister
0343: } else {
0344: document = parser.parse(new InputSource(
0345: new StringReader(toParse)));
0346: }
0347:
0348: List errorMessages = pErrors.getErrorMessages();
0349: if (errorMessages.size() > 0) {
0350: System.err.println("Errors in schema type");
0351: }
0352: } catch (Exception ex) {
0353: System.err
0354: .println("Fatal error while parsing xml schema document");
0355: return null;
0356: }
0357: if (document != null) {
0358: return document.getDocumentElement();
0359: }
0360:
0361: return null;
0362: }
0363:
0364: public static String stringifyExtendedAttributes(
0365: ExtendedAttributes extAttribs) throws Exception {
0366: try {
0367: ExtendedAttributes easclone = (ExtendedAttributes) extAttribs
0368: .clone();
0369: easclone.setParent(null);
0370: Iterator it = easclone.toElements().iterator();
0371: while (it.hasNext()) {
0372: ExtendedAttribute ea = (ExtendedAttribute) it.next();
0373: ea.setParent(null);
0374: ea.get("Name").setParent(null);
0375: ea.get("Value").setParent(null);
0376: }
0377:
0378: return XMLUtil.getExtendedAttributesString(easclone);
0379: // byte[] eas=XMLUtil.serialize(easclone);
0380: // return Base64.encode(eas);
0381: } catch (Throwable thr) {
0382: throw new Exception(
0383: "Can't stringify extended attributes, error="
0384: + thr.getMessage() + " !");
0385: }
0386: }
0387:
0388: public static ExtendedAttributes destringyfyExtendedAttributes(
0389: String extAttribs) throws Exception {
0390: ExtendedAttributes extAttr = null;
0391: if (extAttribs != null && !extAttribs.trim().equals("")) {
0392: try {
0393: DocumentBuilderFactory factory = DocumentBuilderFactory
0394: .newInstance();
0395: factory.setNamespaceAware(true);
0396:
0397: DocumentBuilder parser = factory.newDocumentBuilder();
0398:
0399: Document document = null;
0400: document = parser.parse(new InputSource(
0401: new StringReader(extAttribs)));
0402:
0403: extAttr = new ExtendedAttributes(null);
0404: if (document != null) {
0405: XPDLRepositoryHandler rep = new XPDLRepositoryHandler();
0406: rep.fromXML(document.getDocumentElement(), extAttr);
0407: }
0408:
0409: // byte[] eas=Base64.decode(extAttribs);
0410: // extAttr=(ExtendedAttributes)XMLUtil.deserialize(eas);
0411: return extAttr;
0412: } catch (Throwable thr) {
0413: thr.printStackTrace();
0414: throw new Exception(
0415: "Failed to destringify extended attributes, error="
0416: + thr.getMessage() + " !");
0417: }
0418: }
0419:
0420: return extAttr;
0421: }
0422:
0423: public static Node parseExtendedAttributeContent(String toParse) {
0424: Document document = null;
0425:
0426: DocumentBuilderFactory factory = DocumentBuilderFactory
0427: .newInstance();
0428: factory.setValidating(false);
0429:
0430: try {
0431: ParsingErrors pErrors = new ParsingErrors();
0432:
0433: DocumentBuilder parser = factory.newDocumentBuilder();
0434: parser.setErrorHandler(pErrors);
0435: // adding helper tag, so after parsing, all its children
0436: // will be taken into account
0437: toParse = "<ExtAttribsAddition>" + toParse
0438: + "</ExtAttribsAddition>";
0439: document = parser.parse(new InputSource(new StringReader(
0440: toParse)));
0441: List errorMessages = pErrors.getErrorMessages();
0442: if (errorMessages.size() > 0) {
0443: System.err
0444: .println("Errors in ext attribs complex content");
0445: }
0446: } catch (Exception ex) {
0447: System.err
0448: .println("Fatal error while parsing ext. attributes complex content "
0449: + toParse);
0450: return null;
0451: }
0452: if (document != null) {
0453: return document.getDocumentElement();
0454: }
0455:
0456: return null;
0457: }
0458:
0459: public static String getExtendedAttributeValue(
0460: String[][] extendedAttributes, String extAttrName) {
0461: if (extendedAttributes != null) {
0462: for (int i = 0; i < extendedAttributes.length; i++) {
0463: if (extendedAttributes[i][0].equals(extAttrName)) {
0464: return extendedAttributes[i][1];
0465: }
0466: }
0467: }
0468: return null;
0469: }
0470:
0471: public static Package getPackage(XMLElement el) {
0472: if (el == null)
0473: return null;
0474: while (!(el instanceof Package)) {
0475: el = el.getParent();
0476: if (el == null)
0477: break;
0478: }
0479: return (Package) el;
0480: }
0481:
0482: public static WorkflowProcess getWorkflowProcess(XMLElement el) {
0483: if (el == null)
0484: return null;
0485: while (!(el instanceof WorkflowProcess)) {
0486: el = el.getParent();
0487: if (el == null)
0488: break;
0489: }
0490: return (WorkflowProcess) el;
0491: }
0492:
0493: public static ActivitySet getActivitySet(XMLElement el) {
0494: if (el == null)
0495: return null;
0496: while (!(el instanceof ActivitySet)) {
0497: el = el.getParent();
0498: if (el == null)
0499: break;
0500: }
0501: return (ActivitySet) el;
0502: }
0503:
0504: public static Activity getActivity(XMLElement el) {
0505: if (el == null)
0506: return null;
0507: while (!(el instanceof Activity)) {
0508: el = el.getParent();
0509: if (el == null)
0510: break;
0511: }
0512: return (Activity) el;
0513: }
0514:
0515: public static Transition getTransition(XMLElement el) {
0516: if (el == null)
0517: return null;
0518: while (!(el instanceof Transition)) {
0519: el = el.getParent();
0520: if (el == null)
0521: break;
0522: }
0523: return (Transition) el;
0524: }
0525:
0526: public static Participant getParticipant(XMLElement el) {
0527: if (el == null)
0528: return null;
0529: while (!(el instanceof Participant)) {
0530: el = el.getParent();
0531: if (el == null)
0532: break;
0533: }
0534: return (Participant) el;
0535: }
0536:
0537: public static XMLElement getParentElement(Class type, XMLElement el) {
0538: if (el == null || type == null)
0539: return null;
0540: while (!(el.getClass() == type)) {
0541: el = el.getParent();
0542: if (el == null)
0543: break;
0544: }
0545: return el;
0546: }
0547:
0548: public static XMLElement getParentElementByAssignableType(
0549: Class assignableFrom, XMLElement el) {
0550: if (el == null || assignableFrom == null)
0551: return null;
0552: while (!assignableFrom.isAssignableFrom(el.getClass())) {
0553: el = el.getParent();
0554: if (el == null)
0555: break;
0556: }
0557: return el;
0558: }
0559:
0560: public static boolean isParentsChild(XMLElement parent,
0561: XMLElement el) {
0562: if (el == null || parent == null)
0563: return false;
0564: el = el.getParent();
0565: if (el == null)
0566: return false;
0567: while (el != parent) {
0568: el = el.getParent();
0569: if (el == null)
0570: break;
0571: }
0572: return (el != null);
0573: }
0574:
0575: public static boolean isChildsParent(XMLElement parent,
0576: XMLElement mayBeChild) {
0577: if (mayBeChild == null || parent == null)
0578: return false;
0579: XMLElement el = mayBeChild.getParent();
0580: if (el == null)
0581: return false;
0582: while (el != parent) {
0583: el = el.getParent();
0584: if (el == null)
0585: break;
0586: }
0587: return (el != null);
0588: }
0589:
0590: public static Set getAllParents(XMLElement el) {
0591: Set parents = new HashSet();
0592:
0593: while (el != null) {
0594: el = el.getParent();
0595: parents.add(el);
0596: }
0597:
0598: return parents;
0599: }
0600:
0601: public static WorkflowProcess findWorkflowProcess(
0602: XMLInterface xmlInterface, Package toBegin, String wpId) {
0603: WorkflowProcess wp = toBegin.getWorkflowProcess(wpId);
0604: if (wp == null) {
0605: List l = XMLUtil.getAllExternalPackageIds(xmlInterface,
0606: toBegin, new HashSet());
0607: Iterator it = l.iterator();
0608: while (it.hasNext()) {
0609: Package p = xmlInterface.getPackageById((String) it
0610: .next());
0611: if (p != null) {
0612: wp = p.getWorkflowProcess(wpId);
0613: if (wp != null) {
0614: break;
0615: }
0616: }
0617: }
0618: }
0619: return wp;
0620: }
0621:
0622: public static Participant findParticipant(
0623: XMLInterface xmlInterface, WorkflowProcess toBegin,
0624: String perf) {
0625: Participant p = toBegin.getParticipant(perf);
0626: if (p == null) {
0627: Package pkg = XMLUtil.getPackage(toBegin);
0628: p = XMLUtil.findParticipant(xmlInterface, pkg, perf);
0629: }
0630: return p;
0631: }
0632:
0633: public static Participant findParticipant(
0634: XMLInterface xmlInterface, Package toBegin, String perf) {
0635: Participant p = toBegin.getParticipant(perf);
0636: if (p == null) {
0637: List l = XMLUtil.getAllExternalPackageIds(xmlInterface,
0638: toBegin, new HashSet());
0639: Iterator ita = l.iterator();
0640: while (ita.hasNext()) {
0641: Package pk = xmlInterface.getPackageById((String) ita
0642: .next());
0643: if (pk != null) {
0644: p = pk.getParticipant(perf);
0645: if (p != null) {
0646: break;
0647: }
0648: }
0649: }
0650: }
0651: return p;
0652: }
0653:
0654: public static Application findApplication(
0655: XMLInterface xmlInterface, WorkflowProcess toBegin,
0656: String id) {
0657: Application a = toBegin.getApplication(id);
0658: if (a == null) {
0659: Package pkg = XMLUtil.getPackage(toBegin);
0660: a = XMLUtil.getApplication(xmlInterface, pkg, id);
0661: }
0662: return a;
0663: }
0664:
0665: public static Application getApplication(XMLInterface xmlInterface,
0666: Package toBegin, String id) {
0667: Application a = toBegin.getApplication(id);
0668: if (a == null) {
0669: List l = XMLUtil.getAllExternalPackageIds(xmlInterface,
0670: toBegin, new HashSet());
0671: Iterator ita = l.iterator();
0672: while (ita.hasNext()) {
0673: Package pk = xmlInterface.getPackageById((String) ita
0674: .next());
0675: if (pk != null) {
0676: a = pk.getApplication(id);
0677: if (a != null) {
0678: break;
0679: }
0680: }
0681: }
0682: }
0683: return a;
0684: }
0685:
0686: public static boolean canBeExpression(String expr, Map allVars,
0687: boolean evaluateToString) {
0688: String exprToParse = new String(expr);
0689:
0690: boolean canBeExpression = false;
0691:
0692: if (evaluateToString
0693: && (expr.startsWith("\"") && expr.endsWith("\""))
0694: || (expr.startsWith("'") && expr.endsWith("'"))) {
0695: canBeExpression = true;
0696: }
0697: //System.err.println("CBE1="+canBeExpression);
0698: if (!canBeExpression) {
0699: boolean validVarId = XMLUtil.isIdValid(exprToParse);
0700: if (validVarId && allVars.containsKey(exprToParse)) {
0701: canBeExpression = true;
0702: }
0703: }
0704: //System.err.println("CBE2="+canBeExpression);
0705:
0706: if (!canBeExpression) {
0707: Iterator it = allVars.keySet().iterator();
0708: while (it.hasNext()) {
0709: String varId = (String) it.next();
0710: if (XMLUtil.getUsingPositions(exprToParse, varId,
0711: allVars).size() > 0) {
0712: //System.err.println("CBE2.5 - can be expr because var "+varId+" is possibly used");
0713: canBeExpression = true;
0714: break;
0715: }
0716: }
0717: }
0718: //System.err.println("CBE3="+canBeExpression);
0719:
0720: return canBeExpression;
0721: }
0722:
0723: public static List getUsingPositions(String expr, String dfOrFpId,
0724: Map allVars) {
0725: List positions = new ArrayList();
0726: if (expr.trim().equals("") || dfOrFpId.trim().equals(""))
0727: return positions;
0728: String exprToParse = new String(expr);
0729: int foundAt = -1;
0730: while ((foundAt = exprToParse.indexOf(dfOrFpId)) >= 0) {
0731: // System.out.println("Searching for using positions of variable "+dfOrFpId+" in expression "+exprToParse+" -> found "+foundAt);
0732: if (foundAt < 0)
0733: break;
0734: if (exprToParse.equals(dfOrFpId)) {
0735: int pos = foundAt;
0736: if (positions.size() > 0) {
0737: pos += ((Integer) positions
0738: .get(positions.size() - 1)).intValue()
0739: + dfOrFpId.length();
0740: }
0741: positions.add(new Integer(pos));
0742: break;
0743: }
0744: boolean prevOK, nextOK;
0745: char prev, next;
0746: // if given Id is found within expression string
0747: // check if Id string is part of some other Id name
0748:
0749: // check if char previous to the position of found Id is OK
0750: if (foundAt == 0) {
0751: prevOK = true;
0752: } else {
0753: prev = exprToParse.charAt(foundAt - 1);
0754: prevOK = !XMLUtil.isIdValid(String.valueOf(prev));
0755: // System.out.println("Is prev char "+prev+" ok = "+prevOK);
0756: }
0757:
0758: // check if char after found ID string is OK
0759: if (foundAt + dfOrFpId.length() == exprToParse.length()) {
0760: nextOK = true;
0761: } else {
0762: next = exprToParse.charAt(foundAt + dfOrFpId.length());
0763: nextOK = !XMLUtil.isIdValid(String.valueOf(next));
0764: if (!nextOK && (next == '-' || next == '.')) {
0765: nextOK = true;
0766: List varIdsWithChar = new ArrayList(allVars
0767: .keySet());
0768: Iterator li = varIdsWithChar.iterator();
0769: while (li.hasNext()) {
0770: String vid = (String) li.next();
0771: if (vid.indexOf(next) <= 0) {
0772: li.remove();
0773: }
0774: }
0775: if (varIdsWithChar.size() > 0) {
0776: li = varIdsWithChar.iterator();
0777: while (li.hasNext()) {
0778: String vid = (String) li.next();
0779: int ovp = exprToParse.indexOf(vid);
0780: if (ovp == foundAt) {
0781: nextOK = false;
0782: break;
0783: }
0784: }
0785: }
0786: }
0787: // System.out.println("Is next char "+next+" ok = "+nextOK);
0788: }
0789:
0790: // if this is really the Id, add its position in expression
0791: if (prevOK && nextOK) {
0792: int pos = foundAt;
0793: if (positions.size() > 0) {
0794: pos += ((Integer) positions
0795: .get(positions.size() - 1)).intValue()
0796: + dfOrFpId.length();
0797: }
0798: positions.add(new Integer(pos));
0799: }
0800: exprToParse = exprToParse.substring(foundAt
0801: + dfOrFpId.length());
0802: // System.out.println("New expr to parse is "+exprToParse);
0803: }
0804: // System.out.println("Using positions of variable "+dfOrFpId+" for expression: "+expr+", "+positions);
0805: return positions;
0806: }
0807:
0808: public static Join getJoin(Activity act) {
0809: Join j = null;
0810: TransitionRestrictions trs = act.getTransitionRestrictions();
0811: if (trs.size() > 0) {
0812: j = ((TransitionRestriction) trs.get(0)).getJoin();
0813: }
0814: return j;
0815: }
0816:
0817: public static Split getSplit(Activity act) {
0818: Split s = null;
0819: TransitionRestrictions trs = act.getTransitionRestrictions();
0820: if (trs.size() > 0) {
0821: s = ((TransitionRestriction) trs.get(0)).getSplit();
0822: }
0823: return s;
0824: }
0825:
0826: public static Set getOutgoingTransitions(Activity act) {
0827: return XMLUtil.getOutgoingTransitions(act,
0828: ((Transitions) ((XMLCollectionElement) act.getParent()
0829: .getParent()).get("Transitions")));
0830: }
0831:
0832: public static Set getOutgoingTransitions(Activity act,
0833: Transitions tras) {
0834: Set s = new HashSet();
0835: Iterator it = tras.toElements().iterator();
0836: while (it.hasNext()) {
0837: Transition t = (Transition) it.next();
0838: if (t.getFrom().equals(act.getId())) {
0839: s.add(t);
0840: }
0841: }
0842: return s;
0843: }
0844:
0845: public static Set getExceptionalOutgoingTransitions(Activity act) {
0846: Transitions tras = (Transitions) ((XMLCollectionElement) act
0847: .getParent().getParent()).get("Transitions");
0848: return XMLUtil.getExceptionalOutgoingTransitions(act, tras);
0849: }
0850:
0851: public static Set getExceptionalOutgoingTransitions(Activity act,
0852: Transitions tras) {
0853: Set s = new HashSet();
0854: Iterator it = tras.toElements().iterator();
0855: while (it.hasNext()) {
0856: Transition t = (Transition) it.next();
0857: if (t.getFrom().equals(act.getId())) {
0858: if (XMLUtil.isExceptionalTransition(t)) {
0859: s.add(t);
0860: }
0861: }
0862: }
0863: return s;
0864: }
0865:
0866: public static Set getNonExceptionalOutgoingTransitions(Activity act) {
0867: Transitions tras = (Transitions) ((XMLCollectionElement) act
0868: .getParent().getParent()).get("Transitions");
0869: return XMLUtil.getNonExceptionalOutgoingTransitions(act, tras);
0870: }
0871:
0872: public static Set getNonExceptionalOutgoingTransitions(
0873: Activity act, Transitions tras) {
0874: Set s = new HashSet();
0875: Iterator it = tras.toElements().iterator();
0876: while (it.hasNext()) {
0877: Transition t = (Transition) it.next();
0878: if (t.getFrom().equals(act.getId())) {
0879: if (!XMLUtil.isExceptionalTransition(t)) {
0880: s.add(t);
0881: }
0882: }
0883: }
0884: return s;
0885: }
0886:
0887: public static Set getIncomingTransitions(Activity act) {
0888: return XMLUtil.getIncomingTransitions(act,
0889: ((Transitions) ((XMLCollectionElement) act.getParent()
0890: .getParent()).get("Transitions")));
0891: }
0892:
0893: public static Set getIncomingTransitions(Activity act,
0894: Transitions tras) {
0895: Set s = new HashSet();
0896: Iterator it = tras.toElements().iterator();
0897: while (it.hasNext()) {
0898: Transition t = (Transition) it.next();
0899: if (t.getTo().equals(act.getId())) {
0900: s.add(t);
0901: }
0902: }
0903: return s;
0904: }
0905:
0906: public static boolean isExceptionalTransition(Transition tra) {
0907: boolean isExcTra = false;
0908: if (tra != null) {
0909: String tt = tra.getCondition().getType();
0910: if (tt.equals(XPDLConstants.CONDITION_TYPE_EXCEPTION)
0911: || tt
0912: .equals(XPDLConstants.CONDITION_TYPE_DEFAULTEXCEPTION)) {
0913: isExcTra = true;
0914: }
0915: }
0916: return isExcTra;
0917: }
0918:
0919: public static Activity getFromActivity(Transition t) {
0920: return ((Activities) ((XMLCollectionElement) t.getParent()
0921: .getParent()).get("Activities")).getActivity(t
0922: .getFrom());
0923: }
0924:
0925: public static Activity getToActivity(Transition t) {
0926: return ((Activities) ((XMLCollectionElement) t.getParent()
0927: .getParent()).get("Activities")).getActivity(t.getTo());
0928: }
0929:
0930: /**
0931: * Checks if Id is valid NMTOKEN string.
0932: */
0933: public static boolean isIdValid(String id) {
0934: return id != null && XMLChar.isValidNmtoken(id)
0935: && !id.trim().equals("");
0936: }
0937:
0938: public static int cntIds(XMLCollection xmlCol, String id) {
0939: int idCnt = 0;
0940: Iterator it = xmlCol.toElements().iterator();
0941: while (it.hasNext()) {
0942: XMLElement el = (XMLElement) it.next();
0943: if (el instanceof XMLCollectionElement) {
0944: XMLCollectionElement xmlce = (XMLCollectionElement) el;
0945: String cId = xmlce.getId();
0946: if (cId.equals(id)) {
0947: idCnt++;
0948: }
0949: } else {
0950: return 0;
0951: }
0952: }
0953: return idCnt;
0954: }
0955:
0956: public static WorkflowProcess getSubflowProcess(
0957: XMLInterface xmlInterface, Activity sbflwAct) {
0958: if (sbflwAct.getActivityType() != XPDLConstants.ACTIVITY_TYPE_SUBFLOW)
0959: return null;
0960: Package pkg = XMLUtil.getPackage(sbflwAct);
0961: SubFlow s = sbflwAct.getActivityTypes().getImplementation()
0962: .getImplementationTypes().getSubFlow();
0963: String subflowID = s.getId();
0964:
0965: WorkflowProcess wp = pkg.getWorkflowProcess(subflowID);
0966: if (wp == null) {
0967: List l = XMLUtil.getAllExternalPackageIds(xmlInterface,
0968: pkg, new HashSet());
0969: Iterator it = l.iterator();
0970: while (it.hasNext()) {
0971: Package p = xmlInterface.getPackageById((String) it
0972: .next());
0973: if (p != null) {
0974: wp = p.getWorkflowProcess(subflowID);
0975: if (wp != null) {
0976: break;
0977: }
0978: }
0979: }
0980: }
0981: //System.out.println("Found Subprocess is "+((wp!=null) ? wp.getId() : "null"));
0982: return wp;
0983: }
0984:
0985: public static ActivitySet getBlockActivitySet(Activity blockAct) {
0986: if (blockAct.getActivityType() != XPDLConstants.ACTIVITY_TYPE_BLOCK)
0987: return null;
0988:
0989: String blockID = blockAct.getActivityTypes().getBlockActivity()
0990: .getBlockId();
0991: ActivitySet as = XMLUtil.getWorkflowProcess(blockAct)
0992: .getActivitySet(blockID);
0993:
0994: return as;
0995: }
0996:
0997: public static List getAllExternalPackageIds(XMLInterface xmli,
0998: Package pkg, Set alreadyGathered) {
0999: List l = new ArrayList();
1000: List workingList = new ArrayList(pkg.getExternalPackageIds());
1001: workingList.removeAll(alreadyGathered);
1002: Iterator it = workingList.iterator();
1003: while (it.hasNext()) {
1004: String pkgId = (String) it.next();
1005: Package p = xmli.getPackageById(pkgId);
1006: if (p != null && !l.contains(p.getId())) {
1007: l.add(pkgId);
1008: alreadyGathered.addAll(l);
1009: l.addAll(getAllExternalPackageIds(xmli, p,
1010: alreadyGathered));
1011: }
1012: }
1013: return l;
1014: }
1015:
1016: public static List getImmediateExternalPackages(XMLInterface xmli,
1017: Package pkg) {
1018: List l = new ArrayList();
1019: Iterator it = pkg.getExternalPackageIds().iterator();
1020: while (it.hasNext()) {
1021: String pkgId = (String) it.next();
1022: Package p = xmli.getPackageById(pkgId);
1023: if (p != null && !l.contains(p.getId())) {
1024: l.add(p);
1025: }
1026: }
1027: return l;
1028: }
1029:
1030: /**
1031: * Returns the set of (XML) activities that have split or join.
1032: * @param acts The activities graph objects that are checked if their
1033: * XML object have split or join, depending on the second parameter.
1034: * @param sOrJ if 0, activity is checked for split, otherwise it is
1035: * checked for join
1036: */
1037: public static Set getSplitOrJoinActivities(Collection acts, int sOrJ) {
1038: Set sOrJactivities = new HashSet();
1039: if (acts == null)
1040: return sOrJactivities;
1041: Iterator it = acts.iterator();
1042: while (it.hasNext()) {
1043: Activity act = (Activity) it.next();
1044: int noOfTrans = 0;
1045: if (sOrJ == 0) {
1046: noOfTrans = getOutgoingTransitions(act).size();
1047: } else {
1048: noOfTrans = getIncomingTransitions(act).size();
1049: }
1050: if (noOfTrans > 1) {
1051: sOrJactivities.add(act);
1052: }
1053: }
1054:
1055: return sOrJactivities;
1056: }
1057:
1058: /**
1059: * Returns the set of BlockActivity objects contained within given
1060: * process or block activity. If the BlockActivity objects contains
1061: * other BlockActivity objects, and the second parameter is set to true,
1062: * these are also returned, and so on - which means that
1063: * implementation is recursive.
1064: */
1065: public static Set getBlockActivities(XMLComplexElement wpOrAs,
1066: boolean recursivly) {
1067: Collection allActs = ((Activities) wpOrAs.get("Activities"))
1068: .toElements();
1069: Set bas = new HashSet();
1070: Iterator it = allActs.iterator();
1071: Activity act;
1072: while (it.hasNext()) {
1073: act = (Activity) it.next();
1074: BlockActivity ba = act.getActivityTypes()
1075: .getBlockActivity();
1076: if (ba != null) {
1077: bas.add(act);
1078: if (!recursivly)
1079: continue;
1080: ActivitySets ass = getWorkflowProcess(act)
1081: .getActivitySets();
1082: String asId = ba.getBlockId();
1083: ActivitySet as = ass.getActivitySet(asId);
1084: if (as != null) {
1085: bas.addAll(getBlockActivities(as, true));
1086: }
1087: }
1088: }
1089: return bas;
1090: }
1091:
1092: /**
1093: * Returns predefined conformanceClass number.
1094: * @param conformanceClass The conformance class we are looking for number
1095: * @return 0 if conformance class is NON_BLOCKED, 1 if conformance class is
1096: * LOOP_BLOCKED, 2 if conformance class is FULL_BLOCKED, and -1 otherwise
1097: */
1098: public static int getConformanceClassNo(String conformanceClass) {
1099: if (conformanceClass
1100: .equals(XPDLConstants.GRAPH_CONFORMANCE_NON_BLOCKED)) {
1101: return 0;
1102: } else if (conformanceClass
1103: .equals(XPDLConstants.GRAPH_CONFORMANCE_LOOP_BLOCKED)) {
1104: return 1;
1105: } else if (conformanceClass
1106: .equals(XPDLConstants.GRAPH_CONFORMANCE_FULL_BLOCKED)) {
1107: return 2;
1108: } else {
1109: return -1;
1110: }
1111: }
1112:
1113: /**
1114: * Converts a file specified by the path, to the String.
1115: */
1116: public static String fileToString(String fileName) {
1117: if (fileName != null) {
1118: //String sLine;
1119: byte[] utf8Bytes;
1120: String sFile = new String();
1121: // Reading input by lines:
1122: FileInputStream fis = null;
1123: try {
1124: fis = new FileInputStream(fileName);
1125: int noOfBytes = fis.available();
1126: if (noOfBytes > 0) {
1127: utf8Bytes = new byte[noOfBytes];
1128: fis.read(utf8Bytes);
1129: sFile = new String(utf8Bytes, "UTF8");
1130: }
1131: } catch (Exception ex) {
1132: return null;
1133: } finally {
1134: if (fis != null) {
1135: try {
1136: fis.close();
1137: } catch (Exception ex) {
1138: }
1139: }
1140: }
1141: return sFile;
1142: }
1143: return null;
1144: }
1145:
1146: //******** END OF CREATING SCROLLPANE AND EDITOR COMPONENT(PEJGRAPH) **********
1147:
1148: /** Gets the current date and time string in ISO-8601 format. */
1149: public static String getCurrentDateAndTime() {
1150: String dateSeparator = "-";
1151: String timeSeparator = ":";
1152: Calendar cal = new GregorianCalendar();
1153: String dateTime = "";
1154: dateTime = dateTime + String.valueOf(cal.get(Calendar.YEAR))
1155: + dateSeparator;
1156: int mnth = cal.get(Calendar.MONTH) + 1;
1157: if (mnth < 10) {
1158: dateTime = dateTime + "0";
1159: }
1160: dateTime = dateTime + String.valueOf(mnth) + dateSeparator;
1161: int dayOfMnth = cal.get(Calendar.DAY_OF_MONTH);
1162: if (dayOfMnth < 10) {
1163: dateTime = dateTime + "0";
1164: }
1165: dateTime = dateTime + String.valueOf(dayOfMnth) + " ";
1166: int hr = cal.get(Calendar.HOUR_OF_DAY);
1167: int ampm = cal.get(Calendar.AM_PM);
1168: if (ampm == Calendar.PM && hr < 12) {
1169: hr += 12;
1170: }
1171: if (hr < 10) {
1172: dateTime = dateTime + "0";
1173: }
1174: dateTime = dateTime + String.valueOf(hr) + timeSeparator;
1175: int min = cal.get(Calendar.MINUTE);
1176: if (min < 10) {
1177: dateTime = dateTime + "0";
1178: }
1179: dateTime = dateTime + String.valueOf(min) + timeSeparator;
1180: int sec = cal.get(Calendar.SECOND);
1181: if (sec < 10) {
1182: dateTime = dateTime + "0";
1183: }
1184: dateTime = dateTime + String.valueOf(sec);
1185:
1186: return dateTime;
1187: }
1188:
1189: public static String replaceBackslashesWithSlashes(String repBS) {
1190: if (repBS != null) {
1191: int ind = -1;
1192: while ((ind = repBS.indexOf("\\")) != -1) {
1193: repBS = repBS.substring(0, ind) + "/"
1194: + repBS.substring(ind + 1);
1195: }
1196: }
1197: return repBS;
1198: }
1199:
1200: public static String getExtendedAttributesString(
1201: ExtendedAttributes eas) throws Exception {
1202: Document document = null;
1203:
1204: DocumentBuilderFactory dbf = DocumentBuilderFactory
1205: .newInstance();
1206: DocumentBuilder dbuilder = dbf.newDocumentBuilder();
1207: document = dbuilder.newDocument();
1208: Node eac = document.createElement("EAC");
1209: XPDLRepositoryHandler repH = new XPDLRepositoryHandler();
1210: repH.toXML(eac, eas);
1211:
1212: return XMLUtil.getContent(eac.getFirstChild(), true);
1213: }
1214:
1215: public static String getExtendedAttributesString(Node node) {
1216: String nameSpacePrefix = node.getPrefix();
1217: if (nameSpacePrefix != null) {
1218: nameSpacePrefix += ":";
1219: } else {
1220: nameSpacePrefix = "";
1221: }
1222: Node eas = getChildByName(node, nameSpacePrefix
1223: + "ExtendedAttributes");
1224: return XMLUtil.getContent(eas, true);
1225: }
1226:
1227: public static Set getStartingActivities(
1228: XMLCollectionElement procOrASDef) {
1229: Activities acts = ((Activities) procOrASDef.get("Activities"));
1230: Set starts = new HashSet();
1231: Iterator it = acts.toElements().iterator();
1232: while (it.hasNext()) {
1233: Activity act = (Activity) it.next();
1234: Set trs = getIncomingTransitions(act);
1235: // the activity is starting one if it has no input transitions ...
1236: if (trs.size() == 0) {
1237: starts.add(act);
1238: // or there is a one input transition, but it is a selfreference
1239: } else if (trs.size() == 1) {
1240: Transition t = (Transition) trs.toArray()[0];
1241: if (t.getFrom().equals(t.getTo())) {
1242: starts.add(act);
1243: }
1244: }
1245: }
1246: return starts;
1247: }
1248:
1249: public static Set getEndingActivities(
1250: XMLCollectionElement procOrASDef) {
1251: Activities acts = ((Activities) procOrASDef.get("Activities"));
1252: Set ends = new HashSet();
1253: Iterator it = acts.toElements().iterator();
1254: while (it.hasNext()) {
1255: Activity act = (Activity) it.next();
1256: Set trs = getNonExceptionalOutgoingTransitions(act);
1257: // the activity is ending one if it has no output transitions ...
1258: if (trs.size() == 0) {
1259: ends.add(act);
1260: // or there is a one output transition, but it is a selfreference
1261: } else if (trs.size() == 1) {
1262: Transition t = (Transition) trs.toArray()[0];
1263: if (t.getFrom().equals(t.getTo())) {
1264: ends.add(act);
1265: }
1266: }
1267: }
1268:
1269: return ends;
1270: }
1271:
1272: /**
1273: * Returns the list of responsibles for the process, and responsibles
1274: * for whole package.
1275: */
1276: public static List getResponsibles(WorkflowProcess wp) {
1277: List resp = new ArrayList();
1278: RedefinableHeader rh = wp.getRedefinableHeader();
1279: Responsibles rsps = rh.getResponsibles();
1280: Iterator it = rsps.toElements().iterator();
1281: while (it.hasNext()) {
1282: Responsible rsp = (Responsible) it.next();
1283: if (!resp.contains(rsp)) {
1284: resp.add(rsp);
1285: }
1286: }
1287: // from package
1288: rh = getPackage(wp).getRedefinableHeader();
1289: rsps = rh.getResponsibles();
1290: it = rsps.toElements().iterator();
1291: while (it.hasNext()) {
1292: Responsible rsp = (Responsible) it.next();
1293: if (!resp.contains(rsp)) {
1294: resp.add(rsp);
1295: }
1296: }
1297: return resp;
1298: }
1299:
1300: public static SequencedHashMap getPossibleParticipants(
1301: Package forPkg, XMLInterface xmlInterface) {
1302: SequencedHashMap pars = new SequencedHashMap();
1303: List l = XMLUtil.getAllExternalPackageIds(xmlInterface, forPkg,
1304: new HashSet());
1305: Iterator itpkg = l.iterator();
1306: while (itpkg.hasNext()) {
1307: Package pkg = xmlInterface.getPackageById((String) itpkg
1308: .next());
1309: if (pkg != null) {
1310: Iterator it = pkg.getParticipants().toElements()
1311: .iterator();
1312: while (it.hasNext()) {
1313: Participant p = (Participant) it.next();
1314: pars.put(p.getId(), p);
1315: }
1316: }
1317: }
1318: Iterator it = forPkg.getParticipants().toElements().iterator();
1319: while (it.hasNext()) {
1320: Participant p = (Participant) it.next();
1321: pars.put(p.getId(), p);
1322: }
1323: return pars;
1324: }
1325:
1326: public static SequencedHashMap getPossibleParticipants(
1327: WorkflowProcess forWP, XMLInterface xmlInterface) {
1328: List ps = forWP.getParticipants().toElements();
1329: SequencedHashMap pars = XMLUtil.getPossibleParticipants(XMLUtil
1330: .getPackage(forWP), xmlInterface);
1331: Iterator it = ps.iterator();
1332: while (it.hasNext()) {
1333: Participant p = (Participant) it.next();
1334: pars.put(p.getId(), p);
1335: }
1336: return pars;
1337: }
1338:
1339: public static SequencedHashMap getPossibleApplications(
1340: Package forPkg, XMLInterface xmlInterface) {
1341: SequencedHashMap aps = new SequencedHashMap();
1342: List l = XMLUtil.getAllExternalPackageIds(xmlInterface, forPkg,
1343: new HashSet());
1344: Iterator itpkg = l.iterator();
1345: while (itpkg.hasNext()) {
1346: Package pkg = xmlInterface.getPackageById((String) itpkg
1347: .next());
1348: if (pkg != null) {
1349: Iterator it = pkg.getApplications().toElements()
1350: .iterator();
1351: while (it.hasNext()) {
1352: Application app = (Application) it.next();
1353: aps.put(app.getId(), app);
1354: }
1355: }
1356: }
1357: Iterator it = forPkg.getApplications().toElements().iterator();
1358: while (it.hasNext()) {
1359: Application app = (Application) it.next();
1360: aps.put(app.getId(), app);
1361: }
1362: return aps;
1363: }
1364:
1365: public static SequencedHashMap getPossibleApplications(
1366: WorkflowProcess forWP, XMLInterface xmlInterface) {
1367: List as = forWP.getApplications().toElements();
1368: SequencedHashMap apps = XMLUtil.getPossibleApplications(XMLUtil
1369: .getPackage(forWP), xmlInterface);
1370: Iterator it = as.iterator();
1371: while (it.hasNext()) {
1372: Application app = (Application) it.next();
1373: apps.put(app.getId(), app);
1374: }
1375:
1376: return apps;
1377: }
1378:
1379: public static SequencedHashMap getPossibleDataFields(Package forPkg) {
1380: SequencedHashMap dfs = new SequencedHashMap();
1381: Iterator it = forPkg.getDataFields().toElements().iterator();
1382: while (it.hasNext()) {
1383: DataField df = (DataField) it.next();
1384: dfs.put(df.getId(), df);
1385: }
1386: return dfs;
1387: }
1388:
1389: public static SequencedHashMap getPossibleDataFields(
1390: WorkflowProcess forWP) {
1391: List ds = forWP.getDataFields().toElements();
1392: SequencedHashMap dfs = getPossibleDataFields(XMLUtil
1393: .getPackage(forWP));
1394: Iterator it = ds.iterator();
1395: while (it.hasNext()) {
1396: DataField df = (DataField) it.next();
1397: dfs.put(df.getId(), df);
1398: }
1399: return dfs;
1400: }
1401:
1402: public static SequencedHashMap getPossibleVariables(
1403: WorkflowProcess forWP) {
1404: SequencedHashMap vars = getPossibleDataFields(forWP);
1405: Iterator it = forWP.getFormalParameters().toElements()
1406: .iterator();
1407: while (it.hasNext()) {
1408: FormalParameter fp = (FormalParameter) it.next();
1409: if (!vars.containsKey(fp.getId())) {
1410: vars.put(fp.getId(), fp);
1411: }
1412: }
1413: return vars;
1414: }
1415:
1416: public static SequencedHashMap getPossibleSubflowProcesses(
1417: SubFlow sbflw, XMLInterface xmlInterface) {
1418: SequencedHashMap wps = new SequencedHashMap();
1419: List l = XMLUtil.getAllExternalPackageIds(xmlInterface, XMLUtil
1420: .getPackage(sbflw), new HashSet());
1421: Iterator itpkg = l.iterator();
1422: while (itpkg.hasNext()) {
1423: Package p = xmlInterface.getPackageById((String) itpkg
1424: .next());
1425: if (p != null) {
1426: Iterator it = p.getWorkflowProcesses().toElements()
1427: .iterator();
1428: while (it.hasNext()) {
1429: WorkflowProcess wp = (WorkflowProcess) it.next();
1430: wps.put(wp.getId(), wp);
1431: }
1432: }
1433: }
1434: Iterator it = ((WorkflowProcesses) XMLUtil.getParentElement(
1435: WorkflowProcesses.class, sbflw)).toElements()
1436: .iterator();
1437: while (it.hasNext()) {
1438: WorkflowProcess wp = (WorkflowProcess) it.next();
1439: wps.put(wp.getId(), wp);
1440: }
1441: return wps;
1442: }
1443:
1444: /**
1445: * Returns if given activity has AND type split or join.
1446: * @param act The activity that is checked if it has a AND type
1447: * split or join, depending on the second parameter.
1448: * @param sOrJ if 0, activity is checked for AND type split, otherwise it is
1449: * checked for AND type join
1450: * @return true if given activity has AND type split or join
1451: */
1452: public static boolean isANDTypeSplitOrJoin(Activity act, int sOrJ) {
1453: String sjType = XPDLConstants.JOIN_SPLIT_TYPE_XOR; // default type is XOR
1454:
1455: if (sOrJ == 0) { // it is split that we search for
1456: Split s = getSplit(act);
1457: if (s != null) {
1458: sjType = s.getType();
1459: }
1460: } else { // it is join that we search for
1461: Join j = getJoin(act);
1462: if (j != null) {
1463: sjType = j.getType();
1464: }
1465: }
1466:
1467: if (sjType.equals(XPDLConstants.JOIN_SPLIT_TYPE_AND)) {
1468: return true;
1469: }
1470:
1471: return false;
1472: }
1473:
1474: public static boolean isSubflowSynchronous(
1475: Activity sbflwActivityDefinition) {
1476: String type = XPDLConstants.EXECUTION_SYNCHR;
1477: // Determine subflow type, if it is SYNCHR, terminate it
1478: SubFlow subflow = sbflwActivityDefinition.getActivityTypes()
1479: .getImplementation().getImplementationTypes()
1480: .getSubFlow();
1481: type = subflow.getExecution();
1482:
1483: if (type.equals(XPDLConstants.EXECUTION_ASYNCHR)) {
1484: return false;
1485: }
1486:
1487: return true;
1488: }
1489:
1490: public static int getStartMode(Activity act) {
1491: int ret = XPDLConstants.ACTIVITY_MODE_AUTOMATIC;
1492: StartMode startMode = act.getStartMode();
1493: Object mode = startMode.getStartFinishModes().getChoosen();
1494: if (mode instanceof Manual) {
1495: ret = XPDLConstants.ACTIVITY_MODE_MANUAL;
1496: }
1497: return ret;
1498: }
1499:
1500: public static int getFinishMode(Activity act) {
1501: int ret = XPDLConstants.ACTIVITY_MODE_AUTOMATIC;
1502: FinishMode finishMode = act.getFinishMode();
1503: Object mode = finishMode.getStartFinishModes().getChoosen();
1504: if (mode instanceof Manual) {
1505: ret = XPDLConstants.ACTIVITY_MODE_MANUAL;
1506: }
1507: return ret;
1508: }
1509:
1510: public static int removeXMLElementFromList(List l, XMLElement el) {
1511: int pos = XMLUtil.indexOfXMLElementWithinList(l, el);
1512: if (pos != -1) {
1513: l.remove(pos);
1514: }
1515: return pos;
1516: }
1517:
1518: public static int indexOfXMLElementWithinList(List l, XMLElement el) {
1519: int pos = -1;
1520: for (int i = 0; i < l.size(); i++) {
1521: Object o = l.get(i);
1522: if (o == el) {
1523: pos = i;
1524: break;
1525: }
1526: }
1527: return pos;
1528: }
1529:
1530: public static OutputStream packageToStream(
1531: org.enhydra.shark.xpdl.elements.Package pkg, OutputStream os) {
1532: try {
1533: Document document = null;
1534:
1535: DocumentBuilderFactory dbf = DocumentBuilderFactory
1536: .newInstance();
1537: DocumentBuilder dbuilder = dbf.newDocumentBuilder();
1538: document = dbuilder.newDocument();
1539:
1540: // Here we get all document elements set
1541: XPDLRepositoryHandler repH = new XPDLRepositoryHandler();
1542: repH.toXML(document, pkg);
1543:
1544: // Use a Transformer for output
1545: TransformerFactory tFactory = TransformerFactory
1546: .newInstance();
1547: Transformer transformer = tFactory.newTransformer();
1548: transformer.setOutputProperty("indent", "yes");
1549: transformer.setOutputProperty(
1550: "{http://xml.apache.org/xslt}indent-amount", "4");
1551: transformer.setOutputProperty("encoding", "UTF-8");
1552: DOMSource source = new DOMSource(document);
1553: StreamResult result = new StreamResult(os);
1554: transformer.transform(source, result);
1555: return os;
1556: } catch (Exception ex) {
1557: ex.printStackTrace();
1558: return null;
1559: }
1560: }
1561:
1562: public static List getOrderedOutgoingTransitions(
1563: Activity fromActDef, Set outTransitions) {
1564: // the iteration should be done on TransitionReferences collection,
1565: // in order to make ordered transition's list
1566: Set otCopy = new HashSet(outTransitions);
1567: List orderedOutTransitions = new ArrayList();
1568: Map trIdToTr = new HashMap();
1569: Iterator it = outTransitions.iterator();
1570: while (it.hasNext()) {
1571: Transition trans = (Transition) it.next();
1572: trIdToTr.put(trans.getId(), trans);
1573: }
1574: Split s = getSplit(fromActDef);
1575: if (s != null) {
1576: TransitionRefs trfs = s.getTransitionRefs();
1577: Iterator trefs = trfs.toElements().iterator();
1578: while (trefs.hasNext()) {
1579: TransitionRef tref = (TransitionRef) trefs.next();
1580: Transition trans = (Transition) trIdToTr.get(tref
1581: .getId());
1582: if (trans == null)
1583: continue;
1584: orderedOutTransitions.add(trans);
1585: otCopy.remove(trans);
1586: }
1587: }
1588: // if some of the transitions haven't been within transition refs
1589: // collection, put them into ordered transition list at the end
1590: orderedOutTransitions.addAll(otCopy);
1591: return orderedOutTransitions;
1592: }
1593:
1594: public static String createPath(String basedir, String relpath) {
1595: basedir = XMLUtil.convertToSystemPath(basedir);
1596: relpath = XMLUtil.convertToSystemPath(relpath);
1597: return (basedir + File.separator + relpath);
1598: }
1599:
1600: public static String convertToSystemPath(String path) {
1601: char separatorChar = File.separatorChar;
1602: char charToReplace;
1603: if (separatorChar == '\\') {
1604: charToReplace = '/';
1605: } else {
1606: charToReplace = '\\';
1607: }
1608:
1609: String systemPath = path.replace(charToReplace, separatorChar);
1610: return systemPath;
1611: }
1612:
1613: public static void main(String[] args) throws Throwable {
1614: long t1, t2, t3, ts, te;
1615: ts = System.currentTimeMillis();
1616: boolean readExt = false;
1617: readExt = new Boolean(args[0]).booleanValue();
1618: XMLElementChangeListener list = new XMLElementChangeListener() {
1619: public void xmlElementChanged(XMLElementChangeInfo info) {
1620: System.out.println(info.toString());
1621: }
1622: };
1623:
1624: Package first = null;
1625: String firstIF = null;
1626: Package pkg = null;
1627: XMLInterface xmli = new XMLInterfaceForJDK13();
1628: for (int i = 1; i < args.length; i++) {
1629: String inputFile = args[i];
1630: if (i == 1)
1631: firstIF = inputFile;
1632: System.out.println("Handling file " + inputFile);
1633: t1 = System.currentTimeMillis();
1634:
1635: pkg = readFromFile(xmli, inputFile, readExt);
1636: if (i == 1) {
1637: first = pkg;
1638: }
1639: pkg.addListener(list);
1640: // testCloning(pkg);
1641: System.out.println("PKGL1=" + pkg.getListeners());
1642: Package p1 = pkg;
1643: StandardPackageValidator pv = new StandardPackageValidator();
1644: pv.init(new Properties(), xmli);
1645: System.out.println("VALIDATING ...");
1646: List verrs = new ArrayList();
1647: pv.validateElement(pkg, verrs, true);
1648: System.out.println("VALID=" + (verrs.size() == 0));
1649: t2 = System.currentTimeMillis();
1650: //pkg.setReadOnly(true);
1651: writeToFile(inputFile + "r", pkg);
1652: t3 = System.currentTimeMillis();
1653: pkg = clonePackage(pkg);
1654: System.out.println("PKGL2=" + pkg.getListeners());
1655: //System.out.println(pkg.getExtendedAttributes().eaMap);
1656: //pkg.initCaches();
1657: //System.out.println(pkg.getExtendedAttributes().eaMap);
1658: Package p2 = pkg;
1659: long t4 = System.currentTimeMillis();
1660: writeToFile(inputFile + "rr", pkg);
1661: long t5 = System.currentTimeMillis();
1662: pkg = clonePackageBySerialization(pkg);
1663: System.out.println("PKGL3=" + pkg.getListeners());
1664: System.out.println("P1=P2=" + p1.equals(p2) + ", P2=P3="
1665: + p2.equals(pkg));
1666: long t6 = System.currentTimeMillis();
1667: writeToFile(inputFile + "rrr", pkg);
1668: long t7 = System.currentTimeMillis();
1669: System.out.println("TOverall =" + (t6 - t1));
1670: System.out.println("TOpenPKG " + (t2 - t1));
1671: System.out.println("TSavePKG1 =" + (t3 - t2));
1672: System.out.println("TClonePkg1 =" + (t4 - t3));
1673: System.out.println("TSavePKG2 =" + (t5 - t3));
1674: System.out.println("TClonePkg2 =" + (t6 - t5));
1675: System.out.println("TSavePKG4 =" + (t7 - t6));
1676: }
1677: if (!first.equals(pkg)) {
1678: // testMakeAs(first, pkg);
1679: writeToFile(firstIF + "testma", pkg);
1680: }
1681: te = System.currentTimeMillis();
1682: System.out.println("Handling of " + (args.length - 1)
1683: + " XPDLs lasted " + ((te - ts) / 1000) + " sec");
1684: }
1685:
1686: public static Package readFromFile(XMLInterface xmli,
1687: String inputFile, boolean readExt) throws Exception {
1688: return xmli.openPackage(inputFile, readExt);
1689: }
1690:
1691: public static void writeToFile(String outputFile, Package pkg)
1692: throws Exception {
1693: System.out.println("PKGEPS=" + pkg.getExternalPackageIds());
1694: Document document = null;
1695: DocumentBuilderFactory dbf = DocumentBuilderFactory
1696: .newInstance();
1697: DocumentBuilder dbuilder = dbf.newDocumentBuilder();
1698: document = dbuilder.newDocument();
1699: // output stream will either be the FileOutputStream in the
1700: // case of save as, or the ByteArrayOutputStream if we are
1701: // saving an existing file
1702: FileOutputStream os;
1703: // try to open random access file as rw, if it fails
1704: // the saving shouldn't occur
1705: os = new FileOutputStream(outputFile);
1706:
1707: // Here we get all document elements set
1708: XPDLRepositoryHandler repH = new XPDLRepositoryHandler();
1709: repH.toXML(document, pkg);
1710:
1711: // Use a Transformer for output
1712: TransformerFactory tFactory = TransformerFactory.newInstance();
1713: Transformer transformer = tFactory.newTransformer();
1714: transformer.setOutputProperty("indent", "yes");
1715: transformer.setOutputProperty(
1716: "{http://xml.apache.org/xslt}indent-amount", "4");
1717: transformer.setOutputProperty("encoding", "UTF8");
1718: DOMSource source = new DOMSource(document);
1719: StreamResult result = new StreamResult(os);
1720: transformer.transform(source, result);
1721:
1722: os.close();
1723: }
1724:
1725: public static Package clonePackage(Package pkg) throws Exception {
1726: Package cloned = (Package) pkg.clone();
1727: return cloned;
1728: }
1729:
1730: public static Package clonePackageBySerialization(Package pkg)
1731: throws Exception {
1732: byte[] ser = serialize(pkg);
1733: Package cloned = (Package) deserialize(ser);
1734: return cloned;
1735: }
1736:
1737: public static byte[] serialize(Object obj) throws Exception {
1738: //System.err.println(" ser ##"+obj);
1739: ByteArrayOutputStream bout = new ByteArrayOutputStream();
1740: ObjectOutputStream oout = new ObjectOutputStream(bout);
1741: oout.writeObject(obj);
1742: oout.flush();
1743: byte array[] = bout.toByteArray();
1744: oout.close();
1745: bout.close();
1746: //System.err.println(" ser #"+new String(array));
1747: return array;
1748: }
1749:
1750: public static Object deserialize(byte[] array) throws Exception {
1751: //System.err.println("neser#"+new String(array));
1752: ObjectInputStream rin = new ObjectInputStream(
1753: new ByteArrayInputStream(array));
1754: Object obj = rin.readObject();
1755: rin.close();
1756: //System.err.println("neser##"+obj);
1757: return obj;
1758: }
1759:
1760: }
|