xmlutil.java

来自「jawe的最新版本,基于Java的图形化工作流编辑器。图形化工作流编辑器 。使用」· Java 代码 · 共 1,619 行 · 第 1/4 页

JAVA
1,619
字号
package org.enhydra.shark.xpdl;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.OutputStream;import java.io.StringReader;import java.util.ArrayList;import java.util.Calendar;import java.util.Collection;import java.util.GregorianCalendar;import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Properties;import java.util.Set;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.apache.xerces.util.XMLChar;import org.enhydra.shark.utilities.SequencedHashMap;import org.enhydra.shark.xpdl.elements.Activities;import org.enhydra.shark.xpdl.elements.Activity;import org.enhydra.shark.xpdl.elements.ActivitySet;import org.enhydra.shark.xpdl.elements.ActivitySets;import org.enhydra.shark.xpdl.elements.Application;import org.enhydra.shark.xpdl.elements.BlockActivity;import org.enhydra.shark.xpdl.elements.DataField;import org.enhydra.shark.xpdl.elements.ExtendedAttribute;import org.enhydra.shark.xpdl.elements.ExtendedAttributes;import org.enhydra.shark.xpdl.elements.FinishMode;import org.enhydra.shark.xpdl.elements.FormalParameter;import org.enhydra.shark.xpdl.elements.Join;import org.enhydra.shark.xpdl.elements.Manual;import org.enhydra.shark.xpdl.elements.Package;import org.enhydra.shark.xpdl.elements.Participant;import org.enhydra.shark.xpdl.elements.RedefinableHeader;import org.enhydra.shark.xpdl.elements.Responsible;import org.enhydra.shark.xpdl.elements.Responsibles;import org.enhydra.shark.xpdl.elements.Split;import org.enhydra.shark.xpdl.elements.StartMode;import org.enhydra.shark.xpdl.elements.SubFlow;import org.enhydra.shark.xpdl.elements.Transition;import org.enhydra.shark.xpdl.elements.TransitionRef;import org.enhydra.shark.xpdl.elements.TransitionRefs;import org.enhydra.shark.xpdl.elements.TransitionRestriction;import org.enhydra.shark.xpdl.elements.TransitionRestrictions;import org.enhydra.shark.xpdl.elements.Transitions;import org.enhydra.shark.xpdl.elements.WorkflowProcess;import org.enhydra.shark.xpdl.elements.WorkflowProcesses;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.InputSource;/** *  Class with utilities to read/write XPDLs from/to XML. * *  @author Sasa Bojanic */public class XMLUtil {   public final static String XMLNS = "http://www.wfmc.org/2002/XPDL1.0";   public final static String XMLNS_XPDL = "http://www.wfmc.org/2002/XPDL1.0";   public final static String XMLNS_XSI = "http://www.w3.org/2001/XMLSchema-instance";   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";   /**    * Determines the number of string toFind within string toSearch.    */   public static int howManyStringsWithinString (String toSearch,String toFind) {      try {         int startAt=0;         int howMany=0;         int fnd;         while ((fnd=toSearch.indexOf(toFind,startAt))!=-1) {            howMany++;            startAt=(fnd+toFind.length());         }         return howMany;      } catch (Exception ex) {         return -1;      }   }   public static String getCanonicalPath (String relpath,String basedir,boolean canBeDirectory) {      try {         File f = null;         if (basedir==null || basedir.equals("")) {            f=new File(relpath);            if (!f.isAbsolute()) {               f=f.getAbsoluteFile();               if (!f.exists()) {                  f=new File(XMLUtil.createPath(basedir,relpath));               }            }         } else {            f=new File(XMLUtil.createPath(basedir,relpath));         }         if (!f.exists() || (f.isDirectory() && !canBeDirectory)) {            System.err.println("The file "+f.getAbsolutePath()+" does not exist");            return null;         }                  return getCanonicalPath(f);      } catch (Exception ex) {         ex.printStackTrace();         return null;      }   }   public static String getCanonicalPath (String path, boolean canBeDirectory) {      File f=new File(path);      if (!f.isAbsolute()) {         f=new File(System.getProperty("user.dir")+File.separator+path);      }      if (!f.exists() || (f.isDirectory() && !canBeDirectory)) {         System.err.println("The file "+f.getAbsolutePath()+" does not exist");         return null;      }            return getCanonicalPath(f);   }   private static String getCanonicalPath (File f) {      try {         return f.getCanonicalPath();      } catch (Exception ex) {         return f.getAbsolutePath();      }   }   public static String getNameSpacePrefix (Node node) {      String nameSpacePrefix=node.getPrefix();      if (nameSpacePrefix!=null) {         nameSpacePrefix+=":";      } else {         nameSpacePrefix="";      }      return nameSpacePrefix;   }   public static Node getChildByName(Node parent,String childName) {      NodeList children = parent.getChildNodes();      for (int i = 0; i < children.getLength(); ++i) {         Node child = children.item(i);         if (child.getNodeName().equals(childName)) {            return child;         }      }      return null;   }   public static String getId (Node node) {      try {         NamedNodeMap nnm=node.getAttributes();         Node attrib=nnm.getNamedItem("Id");         Object ID;         if (attrib.hasChildNodes()) {            ID=attrib.getChildNodes().item(0).getNodeValue();         } else {            ID=attrib.getNodeValue();         }         return ID.toString();      } catch (Exception ex) {         return "";      }   }   public static synchronized String getIdFromFile (String xmlFile) {      try {         //  Create parser         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();         factory.setValidating(false);         DocumentBuilder parser = factory.newDocumentBuilder();         Document document=null;         //  Parse the Document         try {            //document=parser.parse(xmlFile);            File f=new File(xmlFile);            if (!f.exists()) {               f=new File(f.getCanonicalPath());            }            document=parser.parse(new InputSource(new FileInputStream(f))); // Fixed by Harald Meister         } catch (Exception ex) {            document=parser.parse(new InputSource(new StringReader(xmlFile)));         }         return XMLUtil.getId(document.getDocumentElement());      } catch (Exception ex) {         return "";      } finally {               }   }   public static String getContent (Node node,boolean omitXMLDeclaration) {      try {         ByteArrayOutputStream baos=new ByteArrayOutputStream();         // Use a Transformer for output         TransformerFactory tFactory =            TransformerFactory.newInstance();         Transformer transformer = tFactory.newTransformer();         transformer.setOutputProperty("indent","yes");         transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");         transformer.setOutputProperty("encoding","UTF-8");         if (omitXMLDeclaration) {            transformer.setOutputProperty("omit-xml-declaration","yes");         }         DOMSource source = new DOMSource(node);         StreamResult result = new StreamResult(baos);         transformer.transform(source,result);         String cont=baos.toString("UTF8");         baos.close();         return cont;      } catch (Exception ex) {         return "";      }   }   public static String getChildNodesContent (Node node) {      String txt="";      if (node!=null) {         if (node.hasChildNodes()) {            txt=XMLUtil.getContent(node,true);            try {               Node fc=node.getFirstChild();               String fcnc=XMLUtil.getContent(fc,true);               String closedTag="</"+node.getNodeName()+">";               if (fcnc.trim().length()>0) {                  fcnc=fcnc.trim();               }               int i1,i2;               i1=txt.indexOf(fcnc);               i2=txt.lastIndexOf(closedTag);               txt=txt.substring(i1,i2).trim();            } catch (Exception ex) {               NodeList nl=node.getChildNodes();               txt="";               try {                  for (int i=0; i<nl.getLength(); i++) {                     Node sn=nl.item(i);                     if (sn instanceof Element) {                        txt+=XMLUtil.getContent(sn,true);                     } else {                        String nv=sn.getNodeValue();                        // trim only the begining of the string                        if (i>0) {                           txt+=nv.substring(1);                        } else if (i==0 && nv.trim().length()==0) {                           continue;                        } else {                           txt+=nv;                        }                     }                  }               } catch (Exception ex2){}            }         }      }      return txt;   }   public static String getShortClassName (String fullClassName) {      int lastDot=fullClassName.lastIndexOf(".");      if (lastDot>=0) {         return fullClassName.substring(lastDot+1,fullClassName.length());      }      return fullClassName;   }   public static String getExternalPackageId (String extPkgHref) {//      System.out.println("EPID1="+extPkgHref);      int indBSL=extPkgHref.lastIndexOf("\\");      int indSL=extPkgHref.lastIndexOf("/");      int indDotXPDL=extPkgHref.lastIndexOf(".xpdl");      if (indSL!=-1 || indBSL!=-1) {         int ind=indSL;         if (indBSL>indSL) {            ind=indBSL;         }         extPkgHref=extPkgHref.substring(ind+1);      }      if (indDotXPDL!=-1) {         extPkgHref=extPkgHref.substring(0,extPkgHref.length()-5);      }//      System.out.println("EPID2="+extPkgHref);      return extPkgHref;   }   public static Node parseSchemaNode (String toParse,boolean isFile) {      Document document=null;      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();      factory.setValidating(false);      //  Parse the Document and traverse the DOM      try {         ParsingErrors pErrors=new ParsingErrors();         DocumentBuilder parser = factory.newDocumentBuilder();         parser.setErrorHandler(pErrors);         //document=parser.parse(refToFile);         if (isFile) {            File f=new File(toParse);            if (!f.exists()) {               throw new Exception();                        }                        document=parser.parse(new InputSource(new FileInputStream(f))); // Fixed by Harald Meister         } else {            document=parser.parse(new InputSource(new StringReader(toParse)));         }         List errorMessages = pErrors.getErrorMessages();         if (errorMessages.size()>0) {            System.err.println("Errors in schema type");         }      } catch (Exception ex) {         System.err.println("Fatal error while parsing xml schema document");         return null;      }      if (document!=null) {         return document.getDocumentElement();      }            return null;   }   public static String stringifyExtendedAttributes(ExtendedAttributes extAttribs) throws Exception {      try {         ExtendedAttributes easclone=(ExtendedAttributes)extAttribs.clone();         easclone.setParent(null);         Iterator it=easclone.toElements().iterator();         while (it.hasNext()) {            ExtendedAttribute ea=(ExtendedAttribute)it.next();            ea.setParent(null);            ea.get("Name").setParent(null);            ea.get("Value").setParent(null);         }                  return XMLUtil.getExtendedAttributesString(easclone);//         byte[] eas=XMLUtil.serialize(easclone);//         return Base64.encode(eas);      } catch (Throwable thr) {         throw new Exception("Can't stringify extended attributes, error="+thr.getMessage()+" !");      }   }   public static ExtendedAttributes destringyfyExtendedAttributes(String extAttribs) throws Exception {      ExtendedAttributes extAttr=null;      if (extAttribs != null && !extAttribs.trim().equals("")) {         try {            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();            factory.setNamespaceAware(true);            DocumentBuilder parser = factory.newDocumentBuilder();            Document document=null;            document=parser.parse(new InputSource(new StringReader(extAttribs)));            extAttr=new ExtendedAttributes(null);            if (document!=null) {               XPDLRepositoryHandler rep = new XPDLRepositoryHandler();               rep.fromXML(document.getDocumentElement(),extAttr);            }            //            byte[] eas=Base64.decode(extAttribs);//            extAttr=(ExtendedAttributes)XMLUtil.deserialize(eas);            return extAttr;         } catch (Throwable thr) {            thr.printStackTrace();            throw new Exception("Failed to destringify extended attributes, error="+thr.getMessage()+" !");         }      }      return extAttr;   }   public static Node parseExtendedAttributeContent (String toParse) {      Document document=null;      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();      factory.setValidating(false);

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?