Coverage Report - org.kuali.rice.kew.xml.DocumentTypeXmlParser
 
Classes in this File Line Coverage Branch Coverage Complexity
DocumentTypeXmlParser
0%
0/778
0%
0/344
13.12
DocumentTypeXmlParser$1
N/A
N/A
13.12
DocumentTypeXmlParser$DocTypeNode
0%
0/4
N/A
13.12
DocumentTypeXmlParser$RoutePathContext
0%
0/2
N/A
13.12
 
 1  
 /*
 2  
  * Copyright 2005-2007 The Kuali Foundation
 3  
  *
 4  
  *
 5  
  * Licensed under the Educational Community License, Version 2.0 (the "License");
 6  
  * you may not use this file except in compliance with the License.
 7  
  * You may obtain a copy of the License at
 8  
  *
 9  
  * http://www.opensource.org/licenses/ecl2.php
 10  
  *
 11  
  * Unless required by applicable law or agreed to in writing, software
 12  
  * distributed under the License is distributed on an "AS IS" BASIS,
 13  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 14  
  * See the License for the specific language governing permissions and
 15  
  * limitations under the License.
 16  
  */
 17  
 package org.kuali.rice.kew.xml;
 18  
 
 19  
 import java.io.BufferedInputStream;
 20  
 import java.io.ByteArrayInputStream;
 21  
 import java.io.IOException;
 22  
 import java.io.InputStream;
 23  
 import java.util.ArrayList;
 24  
 import java.util.HashMap;
 25  
 import java.util.HashSet;
 26  
 import java.util.Iterator;
 27  
 import java.util.LinkedList;
 28  
 import java.util.List;
 29  
 import java.util.Map;
 30  
 import java.util.Set;
 31  
 
 32  
 import javax.xml.parsers.ParserConfigurationException;
 33  
 import javax.xml.transform.TransformerException;
 34  
 import javax.xml.xpath.XPath;
 35  
 import javax.xml.xpath.XPathConstants;
 36  
 import javax.xml.xpath.XPathExpressionException;
 37  
 
 38  
 import org.apache.commons.lang.StringUtils;
 39  
 import org.kuali.rice.kew.doctype.ApplicationDocumentStatus;
 40  
 import org.kuali.rice.kew.doctype.DocumentTypeAttribute;
 41  
 import org.kuali.rice.kew.doctype.DocumentTypePolicy;
 42  
 import org.kuali.rice.kew.doctype.DocumentTypePolicyEnum;
 43  
 import org.kuali.rice.kew.doctype.bo.DocumentType;
 44  
 import org.kuali.rice.kew.document.DocumentTypeMaintainable;
 45  
 import org.kuali.rice.kew.engine.node.ActivationTypeEnum;
 46  
 import org.kuali.rice.kew.engine.node.BranchPrototype;
 47  
 import org.kuali.rice.kew.engine.node.NodeType;
 48  
 import org.kuali.rice.kew.engine.node.Process;
 49  
 import org.kuali.rice.kew.engine.node.RoleNode;
 50  
 import org.kuali.rice.kew.engine.node.RouteNode;
 51  
 import org.kuali.rice.kew.engine.node.RouteNodeConfigParam;
 52  
 import org.kuali.rice.kew.exception.InvalidParentDocTypeException;
 53  
 import org.kuali.rice.kew.exception.InvalidXmlException;
 54  
 import org.kuali.rice.kew.exception.WorkflowException;
 55  
 import org.kuali.rice.kew.exception.WorkflowRuntimeException;
 56  
 import org.kuali.rice.kew.export.ExportDataSet;
 57  
 import org.kuali.rice.kew.role.RoleRouteModule;
 58  
 import org.kuali.rice.kew.rule.FlexRM;
 59  
 import org.kuali.rice.kew.rule.bo.RuleAttribute;
 60  
 import org.kuali.rice.kew.rule.bo.RuleTemplate;
 61  
 import org.kuali.rice.kew.rule.xmlrouting.XPathHelper;
 62  
 import org.kuali.rice.kew.service.KEWServiceLocator;
 63  
 import org.kuali.rice.kew.util.KEWConstants;
 64  
 import org.kuali.rice.kew.util.Utilities;
 65  
 import org.kuali.rice.kew.util.XmlHelper;
 66  
 import org.kuali.rice.kim.bo.Group;
 67  
 import org.kuali.rice.kim.service.IdentityManagementService;
 68  
 import org.kuali.rice.kim.service.KIMServiceLocator;
 69  
 import org.kuali.rice.kns.exception.GroupNotFoundException;
 70  
 import org.kuali.rice.kns.maintenance.Maintainable;
 71  
 import org.kuali.rice.kns.util.MaintenanceUtils;
 72  
 import org.kuali.rice.kns.util.ObjectUtils;
 73  
 import org.w3c.dom.Document;
 74  
 import org.w3c.dom.Element;
 75  
 import org.w3c.dom.NamedNodeMap;
 76  
 import org.w3c.dom.Node;
 77  
 import org.w3c.dom.NodeList;
 78  
 import org.xml.sax.SAXException;
 79  
 
 80  
 
 81  
 /**
 82  
  * A parser for parsing an XML file into {@link DocumentType}s.
 83  
  *
 84  
  * @author Kuali Rice Team (rice.collab@kuali.org)
 85  
  */
 86  0
 public class DocumentTypeXmlParser implements XmlConstants {
 87  
 
 88  0
     private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(DocumentTypeXmlParser.class);
 89  
 
 90  
     private static final String NEXT_NODE_EXP = "./@nextNode";
 91  
     private static final String PARENT_NEXT_NODE_EXP = "../@nextNode";
 92  
     private static final String NEXT_DOC_STATUS_EXP = "./@nextAppDocStatus";
 93  
     /**
 94  
      * Default route node activation type to use if omitted
 95  
      */
 96  
     private static final String DEFAULT_ACTIVATION_TYPE = "S";
 97  
 
 98  
     public List docTypeRouteNodes;
 99  
     private Map nodesMap;
 100  
     private XPath xpath;
 101  
     private Group defaultExceptionWorkgroup;
 102  
     
 103  
     protected XPath getXPath() {
 104  0
         if (this.xpath == null) {
 105  0
             this.xpath = XPathHelper.newXPath();
 106  
         }
 107  0
         return xpath;
 108  
     }
 109  
     
 110  
     public List parseDocumentTypes(InputStream input) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, WorkflowException, TransformerException, GroupNotFoundException {
 111  0
         Document routeDocument=XmlHelper.trimXml(input);
 112  0
         Map documentTypesByName = new HashMap();
 113  0
         for (Iterator iterator = parseAllDocumentTypes(routeDocument).iterator(); iterator.hasNext();) {
 114  0
             DocumentType type = (DocumentType) iterator.next();
 115  0
             documentTypesByName.put(type.getName(), type);
 116  0
         }
 117  0
         return new ArrayList(documentTypesByName.values());
 118  
     }
 119  
 
 120  
     /**
 121  
      * Parses all document types, both standard and routing.
 122  
      * 
 123  
      * @param routeDocument The DOM document to parse.
 124  
      * @return A list containing the desired document types.
 125  
      */
 126  
     private List<DocumentType> parseAllDocumentTypes(Document routeDocument) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, WorkflowException, TransformerException, GroupNotFoundException {
 127  
             // A mapping from the names of uninitialized parent doc types to the child nodes that depend on the parent doc.
 128  0
             Map<String,List<DocTypeNode>> pendingChildDocs = new HashMap<String,List<DocTypeNode>>();
 129  
             // A mapping from the names of uninitialized parent doc types to the names of the dependent children.
 130  0
             Map<String,List<String>> pendingChildNames = new HashMap<String,List<String>>();
 131  
             // A stack containing Iterators over the various lists of unprocessed nodes; this allows for faster parent-child resolution
 132  
             // without having to use recursion.
 133  0
         List<Iterator<DocTypeNode>> docInitStack = new ArrayList<Iterator<DocTypeNode>>();
 134  
         // The first List of document types.
 135  0
         List<DocTypeNode> initialList = new ArrayList<DocTypeNode>();
 136  
             // The current size of the stack.
 137  0
             int stackLen = 0;
 138  
             // The current Iterator instance.
 139  0
             Iterator<DocTypeNode> currentIter = null;
 140  
         // The current document type node.
 141  0
         DocTypeNode currDocNode = null;
 142  
 
 143  0
         List<DocumentType> docTypeBeans = new ArrayList<DocumentType>();
 144  
                 
 145  
         // Acquire the "standard" and "routing" document types.
 146  0
         NodeList initialNodes = null;
 147  0
         xpath = XPathHelper.newXPath();
 148  0
         initialNodes = (NodeList) getXPath().evaluate("/" + DATA_ELEMENT + "/" + DOCUMENT_TYPES + "/" + DOCUMENT_TYPE, routeDocument, XPathConstants.NODESET);
 149  
         // Take each NodeList's nodes and insert them into a List implementation.
 150  0
         for (int j = 0; j < initialNodes.getLength(); j++) {
 151  0
             Node documentTypeNode = initialNodes.item(j);
 152  0
             boolean docIsStandard = true;
 153  
             try {
 154  0
                 String xpathModeExpression = "./@" + DOCUMENT_TYPE_OVERWRITE_MODE;
 155  0
                 if (XmlHelper.pathExists(xpath, xpathModeExpression, documentTypeNode)) {
 156  0
                     String overwriteMode = (String) getXPath().evaluate(xpathModeExpression, documentTypeNode, XPathConstants.STRING);
 157  0
                     docIsStandard = !StringUtils.equalsIgnoreCase("true", overwriteMode);
 158  
                 }
 159  0
             } catch (XPathExpressionException xpee) {
 160  0
                 LOG.error("Error trying to check for '" + DOCUMENT_TYPE_OVERWRITE_MODE + "' attribute on document type element", xpee);
 161  0
                 throw xpee;
 162  0
             }
 163  0
                 initialList.add(new DocTypeNode(documentTypeNode, docIsStandard));
 164  
         }
 165  
 
 166  
         // Setup the Iterator instance to start with.
 167  0
         currentIter = initialList.iterator();
 168  
         
 169  
         // Keep looping until all Iterators are complete or an uncaught exception is thrown.
 170  0
         while (stackLen >= 0) {
 171  
                 // Determine the action to take based on whether there are remaining nodes in the present iterator.
 172  0
                 if (currentIter.hasNext()) {
 173  
                         // If the current iterator still has more nodes, process the next one.
 174  0
                         String newParentName = null;
 175  0
                         currDocNode = currentIter.next();
 176  
                         // Initialize the document, and catch any child initialization problems.
 177  
                         try {
 178  
                                 // Take appropriate action based on whether the document is a standard one or a routing one.
 179  0
                                 DocumentType docType = parseDocumentType(!currDocNode.isStandard, currDocNode.docNode); 
 180  
                                 // Insert into appropriate position in the final list, based on the doc type's location in the XML file's list.
 181  0
                                       docTypeBeans.add(docType);
 182  
                             // Store the document's name for reference.
 183  0
                             newParentName = docType.getName();
 184  
                         }
 185  0
                         catch (InvalidParentDocTypeException exc) {
 186  
                                 // If the parent document has not been processed yet, then store the child document.
 187  0
                             List<DocTypeNode> tempList = null;
 188  0
                             List<String> tempStrList = null;
 189  0
                             String parentName = exc.getParentName();
 190  0
                             String childName = exc.getChildName();
 191  0
                             if (parentName == null || childName == null) { // Make sure the parent & child documents' names are defined.
 192  0
                                     throw exc;
 193  
                             }
 194  0
                             tempList = pendingChildDocs.get(parentName);
 195  0
                             tempStrList = pendingChildNames.get(parentName);
 196  0
                             if (tempList == null) { // Initialize a new child document list if necessary.
 197  0
                                     tempList = new ArrayList<DocTypeNode>();
 198  0
                                     tempStrList = new ArrayList<String>();
 199  0
                                     pendingChildDocs.put(parentName, tempList);
 200  0
                                     pendingChildNames.put(parentName, tempStrList);
 201  
                             }
 202  0
                                 tempList.add(currDocNode);
 203  0
                                 tempStrList.add(childName);
 204  0
                         }
 205  
                         
 206  
                     // Check for any delayed child documents that are dependent on the current document.
 207  0
                         List<DocTypeNode> childrenToProcess = pendingChildDocs.remove(newParentName);
 208  0
                         pendingChildNames.remove(newParentName);
 209  0
                         if (childrenToProcess != null) {
 210  0
                                 LOG.info("'" + newParentName + "' has children that were delayed; now processing them...");
 211  
                                 // If there are any pending children, push the old Iterator onto the stack and process the new Iterator on the next
 212  
                                 // iteration of the loop.
 213  0
                                 stackLen++;
 214  0
                                 docInitStack.add(currentIter);
 215  0
                                 currentIter = childrenToProcess.iterator();
 216  
                         }
 217  0
                 }
 218  
                 else {
 219  
                         // If the current Iterator has reached its end, discard it and pop the next one (if any) from the stack.
 220  0
                         stackLen--;
 221  0
                         currentIter = ((stackLen >= 0) ? docInitStack.remove(stackLen) : null);
 222  
                  }
 223  
         }
 224  
         
 225  
         // Throw an error if there are still any uninitialized child documents.
 226  0
         if (pendingChildDocs.size() > 0) {
 227  0
                 StringBuilder errMsg = new StringBuilder("Invalid parent document types: ");
 228  
                 // Construct the error message.
 229  0
                 for (Iterator<String> unknownParents = pendingChildNames.keySet().iterator(); unknownParents.hasNext();) {
 230  0
                         String currParent = unknownParents.next();
 231  0
                         errMsg.append("Invalid parent doc type '").append(currParent).append("' is needed by child doc types ");
 232  0
                         for (Iterator<String> failedChildren = pendingChildNames.get(currParent).iterator(); failedChildren.hasNext();) {
 233  0
                                 String currChild = failedChildren.next();
 234  0
                                 errMsg.append('\'').append(currChild).append((failedChildren.hasNext()) ? "', " : "'; ");
 235  0
                         }
 236  0
                 }
 237  
                 // Throw the exception.
 238  0
                 throw new InvalidParentDocTypeException(null, null, errMsg.toString());
 239  
         }
 240  
         
 241  0
             return docTypeBeans;
 242  
     }
 243  
 
 244  
     private DocumentType parseDocumentType(boolean isOverwrite, Node documentTypeNode) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, WorkflowException, TransformerException, GroupNotFoundException {
 245  0
         DocumentType documentType = getFullDocumentType(isOverwrite, documentTypeNode);
 246  
 //        parseStructure(isOverwrite, documentTypeNode, documentType, new RoutePathContext());
 247  
         // reset variables
 248  0
         docTypeRouteNodes = null;
 249  0
         nodesMap = null;
 250  0
         xpath = null;
 251  0
         defaultExceptionWorkgroup = null;
 252  
 
 253  0
         LOG.debug("Saving document type " + documentType.getName());
 254  0
         routeDocumentType(documentType);
 255  0
         return documentType;
 256  
     }
 257  
 
 258  
     private DocumentType getFullDocumentType(boolean isOverwrite, Node documentTypeNode) throws XPathExpressionException, GroupNotFoundException, InvalidXmlException, WorkflowException, SAXException, IOException, ParserConfigurationException, TransformerException {
 259  0
         DocumentType documentType = getDocumentType(isOverwrite, documentTypeNode);
 260  
         /*
 261  
          * The following code does not need to apply the isOverwrite mode logic because it already checks to see if each node
 262  
          * is available on the ingested XML. If the node is ingested then it doesn't matter if we're in overwrite mode or not
 263  
          * the ingested code should save.
 264  
          */
 265  0
         NodeList policiesList = (NodeList) getXPath().evaluate("./" + POLICIES, documentTypeNode, XPathConstants.NODESET);
 266  0
         if (policiesList.getLength() > 1) {
 267  
             // more than one <policies> tag is invalid
 268  0
             throw new InvalidXmlException("More than one " + POLICIES + " node is present in a document type node");
 269  
         }
 270  0
         else if (policiesList.getLength() > 0) {
 271  
             // if there is exactly one <policies> tag then parse it and use the values
 272  0
             NodeList policyNodes = (NodeList) getXPath().evaluate("./" + POLICY, policiesList.item(0), XPathConstants.NODESET);
 273  0
             documentType.setPolicies(getDocumentTypePolicies(policyNodes, documentType));
 274  
         }
 275  
 
 276  0
         NodeList attributeList = (NodeList) getXPath().evaluate("./attributes", documentTypeNode, XPathConstants.NODESET);
 277  0
         if (attributeList.getLength() > 1) {
 278  0
             throw new InvalidXmlException("More than one attributes node is present in a document type node");
 279  
         }
 280  0
         else if (attributeList.getLength() > 0) {
 281  0
             NodeList attributeNodes = (NodeList) getXPath().evaluate("./attribute", attributeList.item(0), XPathConstants.NODESET);
 282  0
             documentType.setDocumentTypeAttributes(getDocumentTypeAttributes(attributeNodes, documentType));
 283  
         }
 284  
 
 285  0
         NodeList securityList = (NodeList) getXPath().evaluate("./" + SECURITY, documentTypeNode, XPathConstants.NODESET);
 286  0
         if (securityList.getLength() > 1) {
 287  0
             throw new InvalidXmlException("More than one " + SECURITY + " node is present in a document type node");
 288  
         }
 289  0
         else if (securityList.getLength() > 0) {
 290  
            try {
 291  0
              Node securityNode = securityList.item(0);
 292  0
              String securityText = XmlHelper.writeNode(securityNode);
 293  0
              documentType.setDocumentTypeSecurityXml(securityText);
 294  
            }
 295  0
            catch (Exception e) {
 296  0
              throw new InvalidXmlException(e);
 297  0
            }
 298  
         }
 299  0
         parseStructure(isOverwrite, documentTypeNode, documentType, new RoutePathContext());
 300  0
         return documentType;
 301  
     }
 302  
 
 303  
     private void parseStructure(boolean isOverwrite, Node documentTypeNode, DocumentType documentType, RoutePathContext context) throws XPathExpressionException, InvalidXmlException, GroupNotFoundException, TransformerException {
 304  
         // TODO have a validation function that takes an xpath statement and blows chunks if that
 305  
         // statement returns false
 306  0
         boolean hasRoutePathsElement = false;
 307  
         try {
 308  0
             hasRoutePathsElement = XmlHelper.pathExists(xpath, "./" + ROUTE_PATHS, documentTypeNode);
 309  0
         } catch (XPathExpressionException xpee) {
 310  0
             LOG.error("Error obtaining document type " + ROUTE_PATHS, xpee);
 311  0
             throw xpee;
 312  0
         }
 313  0
         boolean hasRouteNodesElement = false;
 314  
         try {
 315  0
             hasRouteNodesElement = XmlHelper.pathExists(xpath, "./" + ROUTE_NODES, documentTypeNode);
 316  0
         } catch (XPathExpressionException xpee) {
 317  0
             LOG.error("Error obtaining document type " + ROUTE_NODES, xpee);
 318  0
             throw xpee;
 319  0
         }
 320  
 
 321  
         // check to see if we're in overwrite mode
 322  0
         if (isOverwrite) {
 323  
             // since we're in overwrite mode, if we don't have a routeNodes element or a routePaths element we simply return
 324  0
             if (!hasRouteNodesElement && !hasRoutePathsElement) {
 325  0
                 return;
 326  
             }
 327  
             // if we have route nodes and route paths we're going to overwrite all existing processes so we can clear the current list
 328  0
             else if (hasRouteNodesElement && hasRoutePathsElement) {
 329  0
                 documentType.setProcesses(new ArrayList());
 330  
             }
 331  
             // check to see if we have one but not the other element of routePaths and routeNodes
 332  0
             else if (!hasRouteNodesElement || !hasRoutePathsElement) {
 333  
                 // throw an exception since an ingestion can only have neither or both of the routePaths and routeNodes elements
 334  0
                 throw new InvalidXmlException("A overwriting document type ingestion can not have only one of the " + ROUTE_PATHS + " and " + ROUTE_NODES + " elements.  Either both or neither should be defined.");
 335  
             }
 336  
         }
 337  
 
 338  
         NodeList processNodes;
 339  
 
 340  
         try {
 341  0
             if (XmlHelper.pathExists(xpath, "./" + ROUTE_PATHS + "/" + ROUTE_PATH, documentTypeNode)) {
 342  0
                 processNodes = (NodeList) getXPath().evaluate("./" + ROUTE_PATHS + "/" + ROUTE_PATH, documentTypeNode, XPathConstants.NODESET);
 343  
             } else {
 344  0
                 if (hasRoutePathsElement) {
 345  0
                     createEmptyProcess(documentType);
 346  
                 }
 347  0
                 return;
 348  
             }
 349  0
         } catch (XPathExpressionException xpee) {
 350  0
             LOG.error("Error obtaining document type routePaths", xpee);
 351  0
             throw xpee;
 352  0
         }
 353  
 
 354  0
         createProcesses(processNodes, documentType);
 355  
 
 356  0
         NodeList nodeList = null;
 357  
         try {
 358  0
             nodeList = (NodeList) getXPath().evaluate("./" + ROUTE_PATHS + "/" + ROUTE_PATH + "/start", documentTypeNode, XPathConstants.NODESET);
 359  0
         } catch (XPathExpressionException xpee) {
 360  0
             LOG.error("Error obtaining document type routePath start", xpee);
 361  0
             throw xpee;
 362  0
         }
 363  0
         if (nodeList.getLength() > 1) {
 364  0
             throw new InvalidXmlException("More than one start node is present in route path");
 365  0
         } else if (nodeList.getLength() == 0) {
 366  0
             throw new InvalidXmlException("No start node is present in route path");
 367  
         }
 368  
         try {
 369  0
             nodeList = (NodeList) getXPath().evaluate(".//" + ROUTE_NODES, documentTypeNode, XPathConstants.NODESET);
 370  0
         } catch (XPathExpressionException xpee) {
 371  0
             LOG.error("Error obtaining document type routeNodes", xpee);
 372  0
             throw xpee;
 373  0
         }
 374  0
         if (nodeList.getLength() > 1) {
 375  0
             throw new InvalidXmlException("More than one routeNodes node is present in documentType node");
 376  0
         } else if (nodeList.getLength() == 0) {
 377  0
             throw new InvalidXmlException("No routeNodes node is present in documentType node");
 378  
         }
 379  0
         Node routeNodesNode = nodeList.item(0);
 380  0
         checkForOrphanedRouteNodes(documentTypeNode, routeNodesNode);
 381  
 
 382  
         // passed validation.
 383  0
         nodesMap = new HashMap();
 384  0
         for (int index = 0; index < processNodes.getLength(); index++) {
 385  0
             Node processNode = processNodes.item(index);
 386  
             String startName;
 387  
             try {
 388  0
                 startName = (String) getXPath().evaluate("./start/@name", processNode, XPathConstants.STRING);
 389  0
             } catch (XPathExpressionException xpee) {
 390  0
                 LOG.error("Error obtaining routePath start name attribute", xpee);
 391  0
                 throw xpee;
 392  0
             }
 393  0
             String processName = KEWConstants.PRIMARY_PROCESS_NAME;
 394  0
             if (Utilities.isEmpty(startName)) {
 395  
                 try {
 396  0
                     startName = (String) getXPath().evaluate("./@" + INITIAL_NODE, processNode, XPathConstants.STRING);
 397  0
                 } catch (XPathExpressionException xpee) {
 398  0
                     LOG.error("Error obtaining routePath initialNode attribute", xpee);
 399  0
                     throw xpee;
 400  0
                 }
 401  
                 try {
 402  0
                     processName = (String) getXPath().evaluate("./@" + PROCESS_NAME, processNode, XPathConstants.STRING);
 403  0
                 } catch (XPathExpressionException xpee) {
 404  0
                     LOG.error("Error obtaining routePath processName attribute", xpee);
 405  0
                     throw xpee;
 406  0
                 }
 407  0
                 if (Utilities.isEmpty(startName)) {
 408  0
                     throw new InvalidXmlException("Invalid routePath: no initialNode attribute defined!");
 409  
                 }
 410  
             }
 411  0
             RouteNode routeNode = createRouteNode(null, startName, processNode, routeNodesNode, documentType, context);
 412  0
             if (routeNode != null) {
 413  0
                 Process process = documentType.getNamedProcess(processName);
 414  0
                 process.setInitialRouteNode(routeNode);
 415  
             }
 416  
         }
 417  
 
 418  0
     }
 419  
 
 420  
     private DocumentType getDocumentType(boolean isOverwrite, Node documentTypeNode) throws XPathExpressionException, GroupNotFoundException, InvalidXmlException, WorkflowException, SAXException, IOException, ParserConfigurationException, TransformerException {
 421  0
         DocumentType documentType = null;
 422  0
         String documentTypeName = getDocumentTypeNameFromNode(documentTypeNode);
 423  0
         DocumentType previousDocumentType = KEWServiceLocator.getDocumentTypeService().findByName(documentTypeName);
 424  0
         if (isOverwrite) {
 425  
             // we don't need the isOverwrite value to be passed here because we're only temporarily creating this document type in memory
 426  0
             documentType = generateNewDocumentTypeFromExisting(documentTypeName);
 427  
             // export the document type that exists in the database
 428  
         }
 429  
         // if we don't have a valid value for documentType create a brand new instance
 430  0
         if (ObjectUtils.isNull(documentType)) {
 431  0
             documentType = new DocumentType();
 432  
         }
 433  0
         documentType.setName(documentTypeName);
 434  
 
 435  
         // set the description on the document type
 436  
         // the description is always taken from the previous document type unless specified in the ingested file
 437  0
         String description = null;
 438  
         try {
 439  0
             description = (String) getXPath().evaluate("./" + DESCRIPTION, documentTypeNode, XPathConstants.STRING);
 440  0
         } catch (XPathExpressionException xpee) {
 441  0
             LOG.error("Error obtaining document type description", xpee);
 442  0
             throw xpee;
 443  0
         }
 444  
         // if the ingestion has produced a valid value then set it on the document
 445  0
         if (StringUtils.isNotBlank(description)) {
 446  0
             documentType.setDescription(description);
 447  
         }
 448  
         // at this point we know the ingested value is blank
 449  0
         else if (!isOverwrite) {
 450  
             // if this is not an overwrite we need to check the previous document type version for a value to pull forward
 451  0
             if ( (ObjectUtils.isNotNull(previousDocumentType)) && (StringUtils.isNotBlank(previousDocumentType.getDescription())) ) {
 452  
                 // keep the same value from the previous version of the document type from the database
 453  0
                 description = previousDocumentType.getDescription();
 454  
             }
 455  0
             documentType.setDescription(description);
 456  
         }
 457  
 
 458  
         // set the label on the document type
 459  0
         String label = null;
 460  
         try {
 461  0
             label = (String) getXPath().evaluate("./" + LABEL, documentTypeNode, XPathConstants.STRING);
 462  0
         } catch (XPathExpressionException xpee) {
 463  0
             LOG.error("Error obtaining document type label", xpee);
 464  0
             throw xpee;
 465  0
         }
 466  
         // if the ingestion has produced a valid value then set it on the document
 467  0
         if (StringUtils.isNotBlank(label)) {
 468  0
             documentType.setLabel(label);
 469  
         }
 470  
         // at this point we know the ingested value is blank
 471  0
         else if (!isOverwrite) {
 472  
             // if this is not an overwrite we need to check the previous document type version for a value to pull forward
 473  0
             if (ObjectUtils.isNotNull(previousDocumentType) && StringUtils.isNotBlank(previousDocumentType.getLabel())) {
 474  
                 // keep the same value from the previous version of the document type from the database
 475  0
                 label = previousDocumentType.getLabel();
 476  
             } else {
 477  
                 // otherwise set it to undefined
 478  0
                 label = KEWConstants.DEFAULT_DOCUMENT_TYPE_LABEL;
 479  
             }
 480  0
             documentType.setLabel(label);
 481  
         }
 482  
 
 483  
         // set the post processor class on the document type
 484  
         try {
 485  
             /*
 486  
              * - if the element tag is ingested... take whatever value is given, even if it's empty 
 487  
              * - we disregard the isOverwrite because if the element tag does not exist in the ingestion
 488  
              * then the documentType should already carry the value from the previous document type
 489  
              */
 490  0
             if (XmlHelper.pathExists(xpath, "./" + POST_PROCESSOR_NAME, documentTypeNode)) {
 491  0
                 String postProcessor = (String) getXPath().evaluate("./" + POST_PROCESSOR_NAME, documentTypeNode, XPathConstants.STRING);
 492  0
                 if (StringUtils.isEmpty(postProcessor)) {
 493  0
                     documentType.setPostProcessorName(KEWConstants.POST_PROCESSOR_NON_DEFINED_VALUE);
 494  
                 } else {
 495  0
                     documentType.setPostProcessorName((String) getXPath().evaluate("./" + POST_PROCESSOR_NAME, documentTypeNode, XPathConstants.STRING));
 496  
                 }    
 497  
             }
 498  
                 
 499  0
         } catch (XPathExpressionException xpee) {
 500  0
             LOG.error("Error obtaining document type postProcessorName", xpee);
 501  0
             throw xpee;
 502  0
         }
 503  
 
 504  
         // set the document handler URL on the document type
 505  
         try {
 506  
             /*
 507  
              * - if the element tag is ingested... take whatever value is given, even if it's empty 
 508  
              * - we disregard the isOverwrite because if the element tag does not exist in the ingestion
 509  
              * then the documentType should already carry the value from the previous document type
 510  
              */
 511  0
             if (XmlHelper.pathExists(xpath, "./" + DOC_HANDLER, documentTypeNode)) {
 512  0
                 documentType.setUnresolvedDocHandlerUrl((String) getXPath().evaluate("./" + DOC_HANDLER, documentTypeNode, XPathConstants.STRING));
 513  
             }
 514  0
         } catch (XPathExpressionException xpee) {
 515  0
             LOG.error("Error obtaining document type docHandler", xpee);
 516  0
             throw xpee;
 517  0
         }
 518  
 
 519  
         // set the help definition URL on the document type
 520  0
         String helpDefUrl = null;
 521  
         try {
 522  0
             helpDefUrl = (String) getXPath().evaluate("./" + HELP_DEFINITION_URL, documentTypeNode, XPathConstants.STRING);
 523  0
         } catch (XPathExpressionException xpee) {
 524  0
             LOG.error("Error obtaining document type help definition url", xpee);
 525  0
             throw xpee;
 526  0
         }
 527  
         // if the ingestion has produced a valid value then set it on the document
 528  0
         if (StringUtils.isNotBlank(helpDefUrl)) {
 529  0
             documentType.setUnresolvedHelpDefinitionUrl(helpDefUrl);
 530  
         }
 531  
         // at this point we know the ingested value is blank
 532  0
         else if (!isOverwrite) {
 533  
             // if this is not an overwrite, we need to check the previous document type version for a value to pull forward
 534  0
             if ( (ObjectUtils.isNotNull(previousDocumentType)) && (StringUtils.isNotBlank(previousDocumentType.getUnresolvedHelpDefinitionUrl())) ) {
 535  
                 // keep the same value from the previous version of the document type from the database
 536  0
                 helpDefUrl = previousDocumentType.getUnresolvedHelpDefinitionUrl();
 537  
             }
 538  0
             documentType.setUnresolvedHelpDefinitionUrl(helpDefUrl);
 539  
         }
 540  
         
 541  
         // set the doc search help URL on the document type
 542  0
         String docSearchHelpUrl = null;
 543  
         try {
 544  0
             docSearchHelpUrl = (String) getXPath().evaluate("./" + DOC_SEARCH_HELP_URL, documentTypeNode, XPathConstants.STRING);
 545  0
         } catch (XPathExpressionException xpee) {
 546  0
             LOG.error("Error obtaining document type document search help url", xpee);
 547  0
             throw xpee;
 548  0
         }
 549  
         // if the ingestion has produced a valid value then set it on the document
 550  0
         if (StringUtils.isNotBlank(docSearchHelpUrl)) {
 551  0
             documentType.setUnresolvedDocSearchHelpUrl(docSearchHelpUrl);
 552  
         }
 553  
         // at this point we know the ingested value is blank
 554  0
         else if (!isOverwrite) {
 555  
             // if this is not an overwrite, we need to check the previous document type version for a value to pull forward
 556  0
             if ( (ObjectUtils.isNotNull(previousDocumentType)) && (StringUtils.isNotBlank(previousDocumentType.getUnresolvedDocSearchHelpUrl())) ) {
 557  
                 // keep the same value from the previous version of the document type from the database
 558  0
                 docSearchHelpUrl = previousDocumentType.getUnresolvedDocSearchHelpUrl();
 559  
             }
 560  0
             documentType.setUnresolvedDocSearchHelpUrl(docSearchHelpUrl);
 561  
         }
 562  
 
 563  
         // set the service namespace on the document type
 564  
         try {
 565  
             /*
 566  
              * - if the element tag is ingested... take whatever value is given, even if it's empty 
 567  
              * - we disregard the isOverwrite because if the element tag does not exist in the ingestion
 568  
              * then the documentType should already carry the value from the previous document type
 569  
              */
 570  0
             if (XmlHelper.pathExists(xpath, "./" + SERVICE_NAMESPACE, documentTypeNode)) {
 571  0
                 documentType.setActualServiceNamespace((String) getXPath().evaluate("./" + SERVICE_NAMESPACE, documentTypeNode, XPathConstants.STRING));
 572  
             }
 573  0
         } catch (XPathExpressionException xpee) {
 574  0
             LOG.error("Error obtaining document type ServiceNamespace", xpee);
 575  0
             throw xpee;
 576  0
         }
 577  
 
 578  
         // set the notification from address on the document type
 579  
         try {
 580  
             /*
 581  
              * - if the element tag is ingested... take whatever value is given, even if it's empty 
 582  
              * - we disregard the isOverwrite because if the element tag does not exist in the ingestion
 583  
              * then the documentType should already carry the value from the previous document type
 584  
              */
 585  0
             if (XmlHelper.pathExists(xpath, "./" + NOTIFICATION_FROM_ADDRESS, documentTypeNode)) {
 586  0
                 documentType.setActualNotificationFromAddress((String) getXPath().evaluate("./" + NOTIFICATION_FROM_ADDRESS, documentTypeNode, XPathConstants.STRING));
 587  
             }
 588  0
         } catch (XPathExpressionException xpee) {
 589  0
             LOG.error("Error obtaining document type " + NOTIFICATION_FROM_ADDRESS, xpee);
 590  0
             throw xpee;
 591  0
         }
 592  
 
 593  
         try {
 594  
             /*
 595  
              * - if the element tag is ingested... take whatever value is given, even if it's empty 
 596  
              * - we disregard the isOverwrite because if the element tag does not exist in the ingestion
 597  
              * then the documentType should already carry the value from the previous document type
 598  
              */
 599  0
             if (XmlHelper.pathExists(xpath, "./" + CUSTOM_EMAIL_STYLESHEET, documentTypeNode)) {
 600  0
                 documentType.setCustomEmailStylesheet((String) getXPath().evaluate("./" + CUSTOM_EMAIL_STYLESHEET, documentTypeNode, XPathConstants.STRING));
 601  
             }
 602  0
         } catch (XPathExpressionException xpee) {
 603  0
             LOG.error("Error obtaining document type " + CUSTOM_EMAIL_STYLESHEET, xpee);
 604  0
             throw xpee;
 605  0
         }
 606  
 
 607  
         // any ingested document type by default becomes the current document type
 608  0
         documentType.setCurrentInd(Boolean.TRUE);
 609  
 
 610  
         // set up the default exception workgroup for the document type
 611  0
         String exceptionWg = null;
 612  0
         String exceptionWgName = null;
 613  0
         String exceptionWgNamespace = null;
 614  
         try {
 615  0
                 if (XmlHelper.pathExists(xpath, "./" + DEFAULT_EXCEPTION_GROUP_NAME, documentTypeNode)) {
 616  0
                         exceptionWgName = (String) getXPath().evaluate("./" + DEFAULT_EXCEPTION_GROUP_NAME, documentTypeNode, XPathConstants.STRING);
 617  0
                         exceptionWgNamespace = (String) getXPath().evaluate("./" + DEFAULT_EXCEPTION_GROUP_NAME + "/@" + NAMESPACE, documentTypeNode, XPathConstants.STRING);
 618  0
                         exceptionWg = exceptionWgName;
 619  
                 } else {
 620  0
                         exceptionWg = (String) getXPath().evaluate("./" + DEFAULT_EXCEPTION_WORKGROUP_NAME, documentTypeNode, XPathConstants.STRING);
 621  
                 }
 622  0
         } catch (XPathExpressionException xpee) {
 623  0
             LOG.error("Error obtaining document type " + DEFAULT_EXCEPTION_GROUP_NAME, xpee);
 624  0
             throw xpee;
 625  0
         }
 626  
         // we don't need to take the isOverwrite into account here because this ingestion method is a shortcut to use the same workgroup in all route nodes
 627  0
         if (StringUtils.isNotBlank(exceptionWg)) {
 628  0
                 if (StringUtils.isNotBlank(exceptionWgName)) { // Found a "defaultExceptionGroupName" element.
 629  
                         // allow core config parameter replacement in documenttype workgroups
 630  0
                         exceptionWgName = Utilities.substituteConfigParameters(exceptionWgName).trim();
 631  0
                         exceptionWgNamespace = Utilities.substituteConfigParameters(exceptionWgNamespace).trim();
 632  
                 } else { // Found a deprecated "defaultExceptionWorkgroupName" element.
 633  0
                         LOG.warn((new StringBuilder(160)).append("Document Type XML is using deprecated element '").append(DEFAULT_EXCEPTION_WORKGROUP_NAME).append(
 634  
                                         "', please use '").append(DEFAULT_EXCEPTION_GROUP_NAME).append("' instead.").toString());
 635  
                     // allow core config parameter replacement in documenttype workgroups
 636  0
                     exceptionWg = Utilities.substituteConfigParameters(exceptionWg);
 637  0
                     exceptionWgName = Utilities.parseGroupName(exceptionWg);
 638  0
                     exceptionWgNamespace = Utilities.parseGroupNamespaceCode(exceptionWg);
 639  
                 }
 640  0
             Group exceptionGroup = getIdentityManagementService().getGroupByName(exceptionWgNamespace, exceptionWgName);
 641  0
             if(exceptionGroup == null) {
 642  0
                        throw new WorkflowRuntimeException("Exception workgroup name " + exceptionWgName + " does not exist");
 643  
             }
 644  0
             documentType.setDefaultExceptionWorkgroup(exceptionGroup);
 645  0
             defaultExceptionWorkgroup = exceptionGroup;
 646  
         }
 647  
 
 648  
         // set up the active indicator on the document type
 649  
         try {
 650  
              // if the element tag is ingested... take whatever value is given
 651  0
             if (XmlHelper.pathExists(xpath, "./" + ACTIVE, documentTypeNode)) {
 652  0
                 documentType.setActive(Boolean.valueOf((String) getXPath().evaluate("./" + ACTIVE, documentTypeNode, XPathConstants.STRING)));
 653  
             } 
 654  
             // if isOverwrite is false set the default value
 655  0
             else if (!isOverwrite) {
 656  0
                 documentType.setActive(Boolean.TRUE);
 657  
             }
 658  0
         } catch (XPathExpressionException xpee) {
 659  0
             LOG.error("Error obtaining document type active flag", xpee);
 660  0
             throw xpee;
 661  0
         }
 662  
 
 663  
         // check for a parent document type for the ingested document type
 664  0
         boolean parentElementExists = false;
 665  
         try {
 666  0
             parentElementExists = XmlHelper.pathExists(xpath, "./" + PARENT, documentTypeNode);
 667  0
         } catch (XPathExpressionException xpee) {
 668  0
             LOG.error("Error obtaining document type parent", xpee);
 669  0
             throw xpee;
 670  0
         }
 671  
         /*
 672  
          * - if the element tag is ingested... take whatever value is given 
 673  
          * - we disregard the isOverwrite because if the element tag does not exist in the ingestion
 674  
          * then the documentType should already carry the value from the previous document type
 675  
          */
 676  0
         if (parentElementExists) {
 677  
             // the tag was ingested so we'll use whatever the user attempted to set
 678  0
             String parentDocumentTypeName = null;
 679  
             try {
 680  0
                 parentDocumentTypeName = (String) getXPath().evaluate("./" + PARENT, documentTypeNode, XPathConstants.STRING);
 681  0
             } catch (XPathExpressionException xpee) {
 682  0
                 LOG.error("Error obtaining document type parent", xpee);
 683  0
                 throw xpee;
 684  0
             }
 685  0
             DocumentType parentDocumentType = KEWServiceLocator.getDocumentTypeService().findByName(parentDocumentTypeName);
 686  0
             if (parentDocumentType == null) {
 687  
                 //throw new InvalidXmlException("Invalid parent document type: '" + parentDocumentTypeName + "'");
 688  0
                 LOG.info("Parent document type '" + parentDocumentTypeName +
 689  
                         "' could not be found; attempting to delay processing of '" + documentTypeName + "'...");
 690  0
                 throw new InvalidParentDocTypeException(parentDocumentTypeName, documentTypeName,
 691  
                         "Invalid parent document type: '" + parentDocumentTypeName + "'");
 692  
             }
 693  0
             documentType.setDocTypeParentId(parentDocumentType.getDocumentTypeId());
 694  
         }
 695  
 
 696  
         // set the super user workgroup name on the document type
 697  
         try {
 698  
             /*
 699  
              * - if the element tag is ingested... take whatever value is given
 700  
              * - we disregard the isOverwrite because if the element tag does not exist in the ingestion
 701  
              * then the documentType should already carry the value from the previous document type
 702  
              */
 703  0
                 if (XmlHelper.pathExists(xpath, "./" + SUPER_USER_GROUP_NAME, documentTypeNode)) {
 704  0
                         documentType.setSuperUserWorkgroupNoInheritence(retrieveValidKimGroup("./" + SUPER_USER_GROUP_NAME, documentTypeNode, false));
 705  
                 }
 706  0
                 else if (XmlHelper.pathExists(xpath, "./" + SUPER_USER_WORKGROUP_NAME, documentTypeNode)) {
 707  0
                         LOG.warn((new StringBuilder(160)).append("Document Type XML is using deprecated element '").append(SUPER_USER_WORKGROUP_NAME).append(
 708  
                                         "', please use '").append(SUPER_USER_GROUP_NAME).append("' instead.").toString());
 709  0
                 documentType.setSuperUserWorkgroupNoInheritence(retrieveValidKimGroup("./" + SUPER_USER_WORKGROUP_NAME, documentTypeNode, true));
 710  
             }
 711  0
         } catch (XPathExpressionException xpee) {
 712  0
             LOG.error("Error obtaining document type " + SUPER_USER_GROUP_NAME, xpee);
 713  0
             throw xpee;
 714  0
         }
 715  
 
 716  
         // set the blanket approve workgroup name on the document type
 717  0
         String blanketWorkGroup = null;
 718  0
         String blanketGroupName = null;
 719  0
         String blanketNamespace = null;
 720  0
         String blanketApprovePolicy = null;
 721  
         try {
 722  
             // check if the blanket approve workgroup name element tag was set on the ingested document type and get value if it was
 723  0
                 if (XmlHelper.pathExists(xpath, "./" + BLANKET_APPROVE_GROUP_NAME, documentTypeNode)) {
 724  0
                         blanketGroupName = (String) getXPath().evaluate("./" + BLANKET_APPROVE_GROUP_NAME, documentTypeNode, XPathConstants.STRING);
 725  0
                         blanketNamespace = (String) getXPath().evaluate("./" + BLANKET_APPROVE_GROUP_NAME + "/@" + NAMESPACE, documentTypeNode, XPathConstants.STRING);
 726  0
                         blanketWorkGroup = blanketGroupName;
 727  
                 }
 728  0
                 else if (XmlHelper.pathExists(xpath, "./" + BLANKET_APPROVE_WORKGROUP_NAME, documentTypeNode)) {
 729  0
                 blanketWorkGroup = (String) getXPath().evaluate("./" + BLANKET_APPROVE_WORKGROUP_NAME, documentTypeNode, XPathConstants.STRING);
 730  
             }
 731  0
         } catch (XPathExpressionException xpee) {
 732  0
             LOG.error("Error obtaining document type " + BLANKET_APPROVE_GROUP_NAME, xpee);
 733  0
             throw xpee;
 734  0
         }
 735  
         try {
 736  
             // check if the blanket approve policy element tag was set on the ingested document type and get value if it was
 737  0
             if (XmlHelper.pathExists(xpath, "./" + BLANKET_APPROVE_POLICY, documentTypeNode)) {
 738  0
                 blanketApprovePolicy =(String) getXPath().evaluate("./" + BLANKET_APPROVE_POLICY, documentTypeNode, XPathConstants.STRING);
 739  
             }
 740  0
         } catch (XPathExpressionException xpee) {
 741  0
             LOG.error("Error obtaining document type " + BLANKET_APPROVE_POLICY, xpee);
 742  0
             throw xpee;
 743  0
         }
 744  
         // first check to see if the user ingested both a workgroup name and a policy
 745  0
         if (StringUtils.isNotBlank(blanketWorkGroup) && StringUtils.isNotBlank(blanketApprovePolicy)) {
 746  0
             throw new InvalidXmlException("Only one of the blanket approve xml tags can be set");
 747  
         }
 748  0
         else if (StringUtils.isNotBlank(blanketWorkGroup)) {
 749  0
             if (isOverwrite) {
 750  
                 // if overwrite mode is on we need to make sure we clear out the blanket approve policy in case that was the previous document type's method
 751  0
                 documentType.setBlanketApprovePolicy(null);
 752  
             }
 753  0
             if (StringUtils.isNotBlank(blanketGroupName)) { // Found a "blanketApproveGroupName" element.
 754  0
                     documentType.setBlanketApproveWorkgroup(retrieveValidKimGroupUsingGroupNameAndNamespace(blanketGroupName, blanketNamespace));
 755  
             } else { // Found a deprecated "blanketApproveWorkgroupName" element.
 756  0
                     LOG.warn((new StringBuilder(160)).append("Document Type XML is using deprecated element '").append(BLANKET_APPROVE_WORKGROUP_NAME).append(
 757  
                                         "', please use '").append(BLANKET_APPROVE_GROUP_NAME).append("' instead.").toString());
 758  0
                     documentType.setBlanketApproveWorkgroup(retrieveValidKimGroupUsingUnparsedGroupName(blanketWorkGroup));
 759  
             }
 760  
         }
 761  0
         else if (StringUtils.isNotBlank(blanketApprovePolicy)) {
 762  0
             if (isOverwrite) {
 763  
                 // if overwrite mode is on we need to make sure we clear out the blanket approve workgroup in case that was the previous document type's method
 764  0
                 documentType.setBlanketApproveWorkgroup(null);
 765  
             }
 766  0
             documentType.setBlanketApprovePolicy(blanketApprovePolicy);
 767  
         }
 768  
 
 769  
         // set the reporting workgroup name on the document type
 770  
         try {
 771  0
                 if (XmlHelper.pathExists(xpath, "./" + REPORTING_GROUP_NAME, documentTypeNode)) {
 772  0
                         documentType.setReportingWorkgroup(retrieveValidKimGroup("./" + REPORTING_GROUP_NAME, documentTypeNode, false));
 773  
                 }
 774  0
                 else if (XmlHelper.pathExists(xpath, "./" + REPORTING_WORKGROUP_NAME, documentTypeNode)) {
 775  0
                         LOG.warn((new StringBuilder(160)).append("Document Type XML is using deprecated element '").append(REPORTING_WORKGROUP_NAME).append(
 776  
                                         "', please use '").append(REPORTING_GROUP_NAME).append("' instead.").toString());
 777  0
                 documentType.setReportingWorkgroup(retrieveValidKimGroup("./" + REPORTING_WORKGROUP_NAME, documentTypeNode, true));
 778  
             }
 779  0
         } catch (XPathExpressionException xpee) {
 780  0
             LOG.error("Error obtaining document type " + REPORTING_GROUP_NAME, xpee);
 781  0
             throw xpee;
 782  0
         }
 783  
 
 784  
         // set the routing version on the document type
 785  
         try {
 786  
             /*
 787  
              * - if the element tag is ingested... take whatever value is given 
 788  
              * - we disregard the isOverwrite because if the element tag does not exist in the ingestion
 789  
              * then the documentType should already carry the value from the previous document type
 790  
              */
 791  0
             if (XmlHelper.pathExists(xpath, "./" + ROUTING_VERSION, documentTypeNode)) {
 792  
                 String version;
 793  
                 try {
 794  0
                     version = (String) getXPath().evaluate("./" + ROUTING_VERSION, documentTypeNode, XPathConstants.STRING);
 795  0
                 } catch (XPathExpressionException xpee) {
 796  0
                     LOG.error("Error obtaining document type routingVersion", xpee);
 797  0
                     throw xpee;
 798  0
                 }
 799  
                 // verify that the routing version is one of the two valid values
 800  0
                 if (!(version.equals(KEWConstants.ROUTING_VERSION_ROUTE_LEVEL) || version.equals(KEWConstants.ROUTING_VERSION_NODAL))) {
 801  0
                     throw new WorkflowRuntimeException("Invalid routing version on document type: " + version);
 802  
                 }
 803  0
                 documentType.setRoutingVersion(version);
 804  
             }
 805  0
         } catch (XPathExpressionException xpee) {
 806  0
             LOG.error("Error obtaining document type routingVersion", xpee);
 807  0
             throw xpee;
 808  0
         }
 809  
 
 810  
         // set the valid application document statuses for the document type
 811  
         /*
 812  
          * The following code does not need to apply the isOverwrite mode logic because it already checks to see if each node
 813  
          * is available on the ingested XML. If the node is ingested then it doesn't matter if we're in overwrite mode or not
 814  
          * the ingested code should save.
 815  
          */
 816  0
         NodeList appDocStatusList = (NodeList) getXPath().evaluate("./" + APP_DOC_STATUSES, documentTypeNode, XPathConstants.NODESET);
 817  0
         if (appDocStatusList.getLength() > 1) {
 818  
             // more than one <validDocumentStatuses> tag is invalid
 819  0
             throw new InvalidXmlException("More than one " + APP_DOC_STATUSES + " node is present in a document type node");
 820  
         }
 821  0
         else if (appDocStatusList.getLength() > 0) {
 822  
             // if there is exactly one <validDocumentStatuses> tag then parse it and use the values
 823  
 //                NodeList statusNodes = appDocStatusList.item(0).getChildNodes();
 824  0
             NodeList statusNodes = (NodeList) getXPath().evaluate("./" + STATUS, appDocStatusList.item(0), XPathConstants.NODESET);
 825  0
             documentType.setValidApplicationStatuses(getDocumentTypeStatuses(statusNodes, documentType));
 826  
         }
 827  
         
 828  
         
 829  0
         return documentType;
 830  
     }
 831  
 
 832  
     private Group retrieveValidKimGroup(String xpathExpression, Node documentTypeNode, boolean deprecatedGroupElement) throws XPathExpressionException, GroupNotFoundException {
 833  
         String groupName;
 834  0
         String groupNamespace = null;
 835  
         try {
 836  0
             groupName = (String) getXPath().evaluate(xpathExpression, documentTypeNode, XPathConstants.STRING);
 837  
             // If not using the deprecated "namespaceCode:GroupName" format for group names, obtain the namespace from the element's "namespace" attribute.
 838  0
             if (!deprecatedGroupElement) {
 839  0
                     groupNamespace = (String) getXPath().evaluate(xpathExpression + "/@" + NAMESPACE, documentTypeNode, XPathConstants.STRING);
 840  
             }
 841  0
         } catch (XPathExpressionException xpee) {
 842  0
             LOG.error("Error obtaining document type workgroup using xpath expression: " + xpathExpression, xpee);
 843  0
             throw xpee;
 844  0
         }
 845  
         // Use the appropriate method to retrieve the group, based on whether or not the deprecated "namespaceCode:groupName" naming pattern is in use. 
 846  0
         return (deprecatedGroupElement) ?
 847  
                         retrieveValidKimGroupUsingUnparsedGroupName(groupName) : retrieveValidKimGroupUsingGroupNameAndNamespace(groupName, groupNamespace);
 848  
     }
 849  
 
 850  
     private Group retrieveValidKimGroupUsingGroupNameAndNamespace(String groupName, String groupNamespace) throws GroupNotFoundException {
 851  
             // allow core config parameter replacement in documenttype workgroups
 852  0
             groupName = Utilities.substituteConfigParameters(groupName).trim();
 853  0
             groupNamespace = Utilities.substituteConfigParameters(groupNamespace).trim();
 854  0
             return retrieveValidKimGroupUsingProcessedGroupNameAndNamespace(groupName, groupNamespace);
 855  
     }
 856  
     
 857  
     private Group retrieveValidKimGroupUsingUnparsedGroupName(String unparsedGroupName) throws GroupNotFoundException {
 858  
         // allow core config parameter replacement in documenttype workgroups
 859  0
         unparsedGroupName = Utilities.substituteConfigParameters(unparsedGroupName);
 860  0
         String groupName = Utilities.parseGroupName(unparsedGroupName);
 861  0
         String groupNamespace = Utilities.parseGroupNamespaceCode(unparsedGroupName);
 862  0
         return retrieveValidKimGroupUsingProcessedGroupNameAndNamespace(groupName, groupNamespace);
 863  
     }
 864  
 
 865  
     private Group retrieveValidKimGroupUsingProcessedGroupNameAndNamespace(String groupName, String groupNamespace) throws GroupNotFoundException {
 866  0
         Group workgroup = getIdentityManagementService().getGroupByName(groupNamespace, groupName);
 867  0
         if (workgroup == null) {
 868  0
             throw new GroupNotFoundException("Valid Workgroup could not be found... Namespace: " + groupNamespace + "  Name: " + groupName);
 869  
         }
 870  0
         return workgroup;
 871  
     }
 872  
     
 873  
     public DocumentType generateNewDocumentTypeFromExisting(String documentTypeName) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, GroupNotFoundException, WorkflowException, TransformerException {
 874  
         // export the document type that exists in the database
 875  0
         DocumentType docTypeFromDatabase = KEWServiceLocator.getDocumentTypeService().findByName(documentTypeName);
 876  0
         if (ObjectUtils.isNotNull(docTypeFromDatabase)) {
 877  0
             ExportDataSet exportDataSet = new ExportDataSet();
 878  0
             exportDataSet.getDocumentTypes().add(docTypeFromDatabase);
 879  0
             byte[] xmlBytes = KEWServiceLocator.getXmlExporterService().export(exportDataSet);
 880  
             // use the exported document type from the database to generate the new document type
 881  0
             Document tempDocument = XmlHelper.trimXml(new BufferedInputStream(new ByteArrayInputStream(xmlBytes)));
 882  0
             Node documentTypeNode = (Node) getXPath().evaluate("/" + DATA_ELEMENT + "/" + DOCUMENT_TYPES + "/" + DOCUMENT_TYPE, tempDocument, XPathConstants.NODE);
 883  0
             return getFullDocumentType(false, documentTypeNode);
 884  
         }
 885  0
         return null;
 886  
     }
 887  
 
 888  
     private void routeDocumentType(DocumentType documentType) {
 889  0
         DocumentType docType = KEWServiceLocator.getDocumentTypeService().findByName(documentType.getName());
 890  
         // if the docType exists then check locking
 891  0
         if (ObjectUtils.isNotNull(docType)) {
 892  0
             Maintainable docTypeMaintainable = new DocumentTypeMaintainable();
 893  0
             docTypeMaintainable.setBusinessObject(docType);
 894  0
             docTypeMaintainable.setBoClass(docType.getClass());
 895  
             // below will throw a ValidationException if a valid locking document exists
 896  0
             MaintenanceUtils.checkForLockingDocument(docTypeMaintainable, true);
 897  
         }
 898  0
         KEWServiceLocator.getDocumentTypeService().versionAndSave(documentType);
 899  0
     }
 900  
 
 901  
     private String getDocumentTypeNameFromNode(Node documentTypeNode) throws XPathExpressionException {
 902  
         try {
 903  0
             return (String) getXPath().evaluate("./name", documentTypeNode, XPathConstants.STRING);
 904  0
         } catch (XPathExpressionException xpee) {
 905  0
             LOG.error("Error obtaining document type name", xpee);
 906  0
             throw xpee;
 907  
         }
 908  
     }
 909  
 
 910  
     /**
 911  
      * Checks for route nodes that are declared but never used and throws an InvalidXmlException if one is discovered.
 912  
      */
 913  
     private void checkForOrphanedRouteNodes(Node documentTypeNode, Node routeNodesNode) throws XPathExpressionException, InvalidXmlException {
 914  0
         NodeList nodesInPath = (NodeList) getXPath().evaluate("./routePaths/routePath//*/@name", documentTypeNode, XPathConstants.NODESET);
 915  0
         List<String> nodeNamesInPath = new ArrayList<String>(nodesInPath.getLength());
 916  0
         for (int index = 0; index < nodesInPath.getLength(); index++) {
 917  0
             Node nameNode = nodesInPath.item(index);
 918  0
             nodeNamesInPath.add(nameNode.getNodeValue());
 919  
         }
 920  
 
 921  0
         NodeList declaredNodes = (NodeList) getXPath().evaluate("./*/@name", routeNodesNode, XPathConstants.NODESET);
 922  0
         List<String> declaredNodeNames = new ArrayList<String>(declaredNodes.getLength());
 923  0
         for (int index = 0; index < declaredNodes.getLength(); index++) {
 924  0
             Node nameNode = declaredNodes.item(index);
 925  0
             declaredNodeNames.add(nameNode.getNodeValue());
 926  
         }
 927  
 
 928  
         // now compare the declared nodes to the ones actually used
 929  0
         List<String> orphanedNodes = new ArrayList<String>();
 930  0
         for (String declaredNode : declaredNodeNames) {
 931  0
             boolean foundNode = false;
 932  0
             for (String nodeInPath : nodeNamesInPath) {
 933  0
                 if (nodeInPath.equals(declaredNode)) {
 934  0
                     foundNode = true;
 935  0
                     break;
 936  
                 }
 937  
             }
 938  0
             if (!foundNode) {
 939  0
                 orphanedNodes.add(declaredNode);
 940  
             }
 941  0
         }
 942  0
         if (!orphanedNodes.isEmpty()) {
 943  0
             String message = "The following nodes were declared but never used: ";
 944  0
             for (Iterator iterator = orphanedNodes.iterator(); iterator.hasNext();) {
 945  0
                 String orphanedNode = (String) iterator.next();
 946  0
                 message += orphanedNode + (iterator.hasNext() ? ", " : "");
 947  0
             }
 948  0
             throw new InvalidXmlException(message);
 949  
         }
 950  0
     }
 951  
 
 952  
     private void createProcesses(NodeList processNodes, DocumentType documentType) {
 953  0
         for (int index = 0; index < processNodes.getLength(); index++) {
 954  0
             Node processNode = processNodes.item(index);
 955  0
             NamedNodeMap attributes = processNode.getAttributes();
 956  0
             Node processNameNode = attributes.getNamedItem(PROCESS_NAME);
 957  0
             String processName = (processNameNode == null ? null : processNameNode.getNodeValue());
 958  0
             Process process = new Process();
 959  0
             if (Utilities.isEmpty(processName)) {
 960  0
                 process.setInitial(true);
 961  0
                 process.setName(KEWConstants.PRIMARY_PROCESS_NAME);
 962  
             } else {
 963  0
                 process.setInitial(false);
 964  0
                 process.setName(processName);
 965  
             }
 966  0
             process.setDocumentType(documentType);
 967  0
             documentType.addProcess(process);
 968  
         }
 969  0
     }
 970  
     
 971  
     private void createEmptyProcess(DocumentType documentType) {
 972  0
             Process process = new Process();
 973  
             
 974  0
             process.setInitial(true);
 975  0
             process.setName(KEWConstants.PRIMARY_PROCESS_NAME);
 976  
 
 977  0
             process.setDocumentType(documentType);
 978  0
             documentType.addProcess(process);
 979  0
     }
 980  
 
 981  
     private RouteNode createRouteNode(RouteNode previousRouteNode, String nodeName, Node routePathNode, Node routeNodesNode, DocumentType documentType, RoutePathContext context) throws XPathExpressionException, InvalidXmlException, GroupNotFoundException, TransformerException {
 982  0
         if (nodeName == null) return null;
 983  
 
 984  
         Node currentNode;
 985  
         try {
 986  0
             currentNode = (Node) getXPath().evaluate(".//*[@name = '" + nodeName + "']", routePathNode, XPathConstants.NODE);
 987  0
         } catch (XPathExpressionException xpee) {
 988  0
             LOG.error("Error obtaining routePath for routeNode", xpee);
 989  0
             throw xpee;
 990  0
         }
 991  0
         if (currentNode == null) {
 992  0
             String message = "Next node '" + nodeName + "' for node '" + previousRouteNode.getRouteNodeName() + "' not found!";
 993  0
             LOG.error(message);
 994  0
             throw new InvalidXmlException(message);
 995  
         }
 996  
         boolean nodeIsABranch;
 997  
         try {
 998  0
             nodeIsABranch = ((Boolean) getXPath().evaluate("self::node()[local-name() = 'branch']", currentNode, XPathConstants.BOOLEAN)).booleanValue();
 999  0
         } catch (XPathExpressionException xpee) {
 1000  0
             LOG.error("Error testing whether node is a branch", xpee);
 1001  0
             throw xpee;
 1002  0
         }
 1003  0
         if (nodeIsABranch) {
 1004  0
             throw new InvalidXmlException("Next node cannot be a branch node");
 1005  
         }
 1006  
 
 1007  
         String localName;
 1008  
         try {
 1009  0
             localName = (String) getXPath().evaluate("local-name(.)", currentNode, XPathConstants.STRING);
 1010  0
         } catch (XPathExpressionException xpee) {
 1011  0
             LOG.error("Error obtaining node local-name", xpee);
 1012  0
             throw xpee;
 1013  0
         }
 1014  0
         RouteNode currentRouteNode = null;
 1015  0
         if (nodesMap.containsKey(nodeName)) {
 1016  0
             currentRouteNode = (RouteNode) nodesMap.get(nodeName);
 1017  
         } else {
 1018  0
             String nodeExpression = ".//*[@name='" + nodeName + "']";
 1019  0
             currentRouteNode = makeRouteNodePrototype(localName, nodeName, nodeExpression, routeNodesNode, documentType, context);
 1020  
         }
 1021  
 
 1022  0
         if ("split".equalsIgnoreCase(localName)) {
 1023  0
             getSplitNextNodes(currentNode, routePathNode, currentRouteNode, routeNodesNode, documentType, context);
 1024  
         }
 1025  
 
 1026  0
         if (previousRouteNode != null) {
 1027  0
             previousRouteNode.getNextNodes().add(currentRouteNode);
 1028  0
             nodesMap.put(previousRouteNode.getRouteNodeName(), previousRouteNode);
 1029  0
             currentRouteNode.getPreviousNodes().add(previousRouteNode);
 1030  
         }
 1031  
 
 1032  0
         String nextNodeName = null;
 1033  
         boolean hasNextNodeAttrib;
 1034  
         try {
 1035  0
             hasNextNodeAttrib = ((Boolean) getXPath().evaluate(NEXT_NODE_EXP, currentNode, XPathConstants.BOOLEAN)).booleanValue();
 1036  0
         } catch (XPathExpressionException xpee) {
 1037  0
             LOG.error("Error obtaining node nextNode attrib", xpee);
 1038  0
             throw xpee;
 1039  0
         }
 1040  0
         if (hasNextNodeAttrib) {
 1041  
             // if the node has a nextNode but is not a split node, the nextNode is used for its node
 1042  0
             if (!"split".equalsIgnoreCase(localName)) {
 1043  
                 try {
 1044  0
                     nextNodeName = (String) getXPath().evaluate(NEXT_NODE_EXP, currentNode, XPathConstants.STRING);
 1045  0
                 } catch (XPathExpressionException xpee) {
 1046  0
                     LOG.error("Error obtaining node nextNode attrib", xpee);
 1047  0
                     throw xpee;
 1048  0
                 }
 1049  0
                 createRouteNode(currentRouteNode, nextNodeName, routePathNode, routeNodesNode, documentType, context);
 1050  
             } else {
 1051  
                 // if the node has a nextNode but is a split node, the nextNode must be used for that split node's join node
 1052  0
                 nodesMap.put(currentRouteNode.getRouteNodeName(), currentRouteNode);
 1053  
             }
 1054  
         } else {
 1055  
             // if the node has no nextNode of its own and is not a join which gets its nextNode from its parent split node
 1056  0
             if (!"join".equalsIgnoreCase(localName)) {
 1057  0
                 nodesMap.put(currentRouteNode.getRouteNodeName(), currentRouteNode);
 1058  
                 // if join has a parent nextNode (on its split node) and join has not already walked this path
 1059  
             } else {
 1060  
                 boolean parentHasNextNodeAttrib;
 1061  
                 try {
 1062  0
                     parentHasNextNodeAttrib = ((Boolean) getXPath().evaluate(PARENT_NEXT_NODE_EXP, currentNode, XPathConstants.BOOLEAN)).booleanValue();
 1063  0
                 } catch (XPathExpressionException xpee) {
 1064  0
                     LOG.error("Error obtaining parent node nextNode attrib", xpee);
 1065  0
                     throw xpee;
 1066  0
                 }
 1067  0
                 if (parentHasNextNodeAttrib && !nodesMap.containsKey(nodeName)) {
 1068  
                     try {
 1069  0
                         nextNodeName = (String) getXPath().evaluate(PARENT_NEXT_NODE_EXP, currentNode, XPathConstants.STRING);
 1070  0
                     } catch (XPathExpressionException xpee) {
 1071  0
                         LOG.error("Error obtaining parent node nextNode attrib", xpee);
 1072  0
                         throw xpee;
 1073  0
                     }
 1074  0
                     createRouteNode(currentRouteNode, nextNodeName, routePathNode, routeNodesNode, documentType, context);
 1075  
                 } else {
 1076  
                     // if join's parent split node does not have a nextNode
 1077  0
                     nodesMap.put(currentRouteNode.getRouteNodeName(), currentRouteNode);
 1078  
                 }
 1079  
             }
 1080  
         }
 1081  
         
 1082  
         // handle nextAppDocStatus route node attribute
 1083  0
         String nextDocStatusName = null;
 1084  
         boolean hasNextDocStatus;
 1085  
         try {
 1086  0
             hasNextDocStatus = ((Boolean) getXPath().evaluate(NEXT_DOC_STATUS_EXP, currentNode, XPathConstants.BOOLEAN)).booleanValue();
 1087  0
         } catch (XPathExpressionException xpee) {
 1088  0
             LOG.error("Error obtaining node nextAppDocStatus attrib", xpee);
 1089  0
             throw xpee;
 1090  0
         }
 1091  0
         if (hasNextDocStatus){
 1092  
                 try {
 1093  0
                         nextDocStatusName = (String) getXPath().evaluate(NEXT_DOC_STATUS_EXP, currentNode, XPathConstants.STRING);
 1094  0
                 } catch (XPathExpressionException xpee) {
 1095  0
                         LOG.error("Error obtaining node nextNode attrib", xpee);
 1096  0
                         throw xpee;
 1097  0
                 }
 1098  
                 
 1099  
                 //validate against allowable values if defined
 1100  0
                 if (documentType.getValidApplicationStatuses() != null  && documentType.getValidApplicationStatuses().size() > 0){
 1101  0
                         Iterator iter = documentType.getValidApplicationStatuses().iterator();
 1102  0
                         boolean statusValidated = false;
 1103  0
                         while (iter.hasNext())
 1104  
                         {
 1105  0
                                 ApplicationDocumentStatus myAppDocStat = (ApplicationDocumentStatus) iter.next();
 1106  0
                                 if (nextDocStatusName.compareToIgnoreCase(myAppDocStat.getStatusName()) == 0)
 1107  
                                 {
 1108  0
                                         statusValidated = true;
 1109  0
                                         break;
 1110  
                                 }
 1111  0
                         }
 1112  0
                         if (!statusValidated){
 1113  0
                                         InvalidXmlException xpee = new InvalidXmlException("AppDocStatus value " +  nextDocStatusName + " not allowable."); 
 1114  0
                                         LOG.error("Error validating nextAppDocStatus name: " +  nextDocStatusName + " against acceptable values.", xpee);
 1115  0
                                         throw xpee; 
 1116  
                         }
 1117  
                 }
 1118  0
                 currentRouteNode.setNextDocStatus(nextDocStatusName);
 1119  
         }
 1120  
         
 1121  0
         return currentRouteNode;
 1122  
     }
 1123  
 
 1124  
     private void getSplitNextNodes(Node splitNode, Node routePathNode, RouteNode splitRouteNode, Node routeNodesNode, DocumentType documentType, RoutePathContext context) throws XPathExpressionException, InvalidXmlException, GroupNotFoundException, TransformerException {
 1125  
         NodeList splitBranchNodes;
 1126  
         try {
 1127  0
             splitBranchNodes = (NodeList) getXPath().evaluate("./branch", splitNode, XPathConstants.NODESET);
 1128  0
         } catch (XPathExpressionException xpee) {
 1129  0
             LOG.error("Error obtaining split node branch", xpee);
 1130  0
             throw xpee;
 1131  0
         }
 1132  0
         for (int i = 0; i < splitBranchNodes.getLength(); i++) {
 1133  
             String branchName;
 1134  
             try {
 1135  0
                 branchName = (String) getXPath().evaluate("./@name", splitBranchNodes.item(i), XPathConstants.STRING);
 1136  0
             } catch (XPathExpressionException xpee) {
 1137  0
                 LOG.error("Error obtaining branch name attribute", xpee);
 1138  0
                 throw xpee;
 1139  0
             }
 1140  
             String name;
 1141  
             try {
 1142  0
                 name = (String) getXPath().evaluate("./*[1]/@name", splitBranchNodes.item(i), XPathConstants.STRING);
 1143  0
             } catch (XPathExpressionException xpee) {
 1144  0
                 LOG.error("Error obtaining first split branch node name", xpee);
 1145  0
                 throw xpee;
 1146  0
             }
 1147  0
             context.branch = new BranchPrototype();
 1148  0
             context.branch.setName(branchName);
 1149  
 
 1150  0
             createRouteNode(splitRouteNode, name, routePathNode, routeNodesNode, documentType, context);
 1151  
         }
 1152  0
     }
 1153  
 
 1154  
     private RouteNode makeRouteNodePrototype(String nodeTypeName, String nodeName, String nodeExpression, Node routeNodesNode, DocumentType documentType, RoutePathContext context) throws XPathExpressionException, GroupNotFoundException, InvalidXmlException, TransformerException {
 1155  
         NodeList nodeList;
 1156  
         try {
 1157  0
             nodeList = (NodeList) getXPath().evaluate(nodeExpression, routeNodesNode, XPathConstants.NODESET);
 1158  0
         } catch (XPathExpressionException xpee) {
 1159  0
             LOG.error("Error evaluating node expression: '" + nodeExpression + "'");
 1160  0
             throw xpee;
 1161  0
         }
 1162  0
         if (nodeList.getLength() > 1) {
 1163  0
             throw new InvalidXmlException("More than one node under routeNodes has the same name of '" + nodeName + "'");
 1164  
         }
 1165  0
         if (nodeList.getLength() == 0) {
 1166  0
             throw new InvalidXmlException("No node definition was found with the name '" + nodeName + "'");
 1167  
         }
 1168  0
         Node node = nodeList.item(0);
 1169  
 
 1170  0
         RouteNode routeNode = new RouteNode();
 1171  
         // set fields that all route nodes of all types should have defined
 1172  0
         routeNode.setDocumentType(documentType);
 1173  0
         routeNode.setRouteNodeName((String) getXPath().evaluate("./@name", node, XPathConstants.STRING));
 1174  0
         routeNode.setContentFragment(XmlHelper.writeNode(node));
 1175  
 
 1176  0
         if (XmlHelper.pathExists(xpath, "./activationType", node)) {
 1177  0
             routeNode.setActivationType(ActivationTypeEnum.parse((String) getXPath().evaluate("./activationType", node, XPathConstants.STRING)).getCode());
 1178  
         } else {
 1179  0
             routeNode.setActivationType(DEFAULT_ACTIVATION_TYPE);
 1180  
         }
 1181  
 
 1182  0
         Group exceptionWorkgroup = defaultExceptionWorkgroup;
 1183  
 
 1184  0
         String exceptionWg = null;
 1185  0
         String exceptionWorkgroupName = null;
 1186  0
         String exceptionWorkgroupNamespace = null;
 1187  
 
 1188  0
         if (XmlHelper.pathExists(xpath, "./" + EXCEPTION_GROUP_NAME, node)) {
 1189  0
                 exceptionWorkgroupName = Utilities.substituteConfigParameters(
 1190  
                                 (String) getXPath().evaluate("./" + EXCEPTION_GROUP_NAME, node, XPathConstants.STRING)).trim();
 1191  0
                 exceptionWorkgroupNamespace = Utilities.substituteConfigParameters(
 1192  
                                 (String) getXPath().evaluate("./" + EXCEPTION_GROUP_NAME + "/@" + NAMESPACE, node, XPathConstants.STRING)).trim();
 1193  
         }
 1194  0
         if (Utilities.isEmpty(exceptionWorkgroupName) && XmlHelper.pathExists(xpath, "./" + EXCEPTION_WORKGROUP_NAME, node)) {
 1195  0
                 LOG.warn((new StringBuilder(160)).append("Document Type XML is using deprecated element '").append(EXCEPTION_WORKGROUP_NAME).append(
 1196  
                                 "', please use '").append(EXCEPTION_GROUP_NAME).append("' instead.").toString());
 1197  
                 // for backward compatibility we also need to be able to support exceptionWorkgroupName
 1198  0
                 exceptionWg = Utilities.substituteConfigParameters((String) getXPath().evaluate("./" + EXCEPTION_WORKGROUP_NAME, node, XPathConstants.STRING));
 1199  0
                 exceptionWorkgroupName = Utilities.parseGroupName(exceptionWg);
 1200  0
                 exceptionWorkgroupNamespace = Utilities.parseGroupNamespaceCode(exceptionWg);
 1201  
         }
 1202  0
         if (Utilities.isEmpty(exceptionWorkgroupName) && XmlHelper.pathExists(xpath, "./" + EXCEPTION_WORKGROUP, node)) {
 1203  0
                 LOG.warn((new StringBuilder(160)).append("Document Type XML is using deprecated element '").append(EXCEPTION_WORKGROUP).append(
 1204  
                                 "', please use '").append(EXCEPTION_GROUP_NAME).append("' instead.").toString());
 1205  
             // for backward compatibility we also need to be able to support exceptionWorkgroup
 1206  0
             exceptionWg = Utilities.substituteConfigParameters((String) getXPath().evaluate("./" + EXCEPTION_WORKGROUP, node, XPathConstants.STRING));
 1207  0
             exceptionWorkgroupName = Utilities.parseGroupName(exceptionWg);
 1208  0
             exceptionWorkgroupNamespace = Utilities.parseGroupNamespaceCode(exceptionWg);
 1209  
         }
 1210  0
         if (Utilities.isEmpty(exceptionWorkgroupName)) {
 1211  0
             if (routeNode.getDocumentType().getDefaultExceptionWorkgroup() != null) {
 1212  0
                 exceptionWorkgroupName = routeNode.getDocumentType().getDefaultExceptionWorkgroup().getGroupName();
 1213  0
                 exceptionWorkgroupNamespace = routeNode.getDocumentType().getDefaultExceptionWorkgroup().getNamespaceCode();
 1214  
             }
 1215  
         }
 1216  0
         if (!Utilities.isEmpty(exceptionWorkgroupName)) {
 1217  0
             exceptionWorkgroup = getIdentityManagementService().getGroupByName(exceptionWorkgroupNamespace, exceptionWorkgroupName);
 1218  0
             if (exceptionWorkgroup == null) {
 1219  0
                 throw new GroupNotFoundException("Could not locate exception workgroup with namespace '" + exceptionWorkgroupNamespace + "' and name '" + exceptionWorkgroupName + "'");
 1220  
             }
 1221  
         }
 1222  0
         if (exceptionWorkgroup != null) {
 1223  0
             routeNode.setExceptionWorkgroupName(exceptionWorkgroup.getGroupName());
 1224  0
             routeNode.setExceptionWorkgroupId(exceptionWorkgroup.getGroupId());
 1225  
         }
 1226  
 
 1227  0
         if (((Boolean) getXPath().evaluate("./mandatoryRoute", node, XPathConstants.BOOLEAN)).booleanValue()) {
 1228  0
             routeNode.setMandatoryRouteInd(Boolean.valueOf((String)getXPath().evaluate("./mandatoryRoute", node, XPathConstants.STRING)));
 1229  
         } else {
 1230  0
             routeNode.setMandatoryRouteInd(Boolean.FALSE);
 1231  
         }
 1232  0
         if (((Boolean) getXPath().evaluate("./finalApproval", node, XPathConstants.BOOLEAN)).booleanValue()) {
 1233  0
             routeNode.setFinalApprovalInd(Boolean.valueOf((String)getXPath().evaluate("./finalApproval", node, XPathConstants.STRING)));
 1234  
         } else {
 1235  0
             routeNode.setFinalApprovalInd(Boolean.FALSE);
 1236  
         }
 1237  
 
 1238  
         // for every simple child element of the node, store a config parameter of the element name and text content
 1239  0
         NodeList children = node.getChildNodes();
 1240  0
         for (int i = 0; i < children.getLength(); i++) {
 1241  0
             Node n = children.item(i);
 1242  0
             if (n instanceof Element) {
 1243  0
                 Element e = (Element) n;
 1244  0
                 String name = e.getNodeName();
 1245  0
                 String content = XmlHelper.getTextContent(e);
 1246  0
                 routeNode.getConfigParams().add(new RouteNodeConfigParam(routeNode, name, content));
 1247  
             }
 1248  
         }
 1249  
 
 1250  
         // make sure a default rule selector is set
 1251  0
         Map<String, String> cfgMap = Utilities.getKeyValueCollectionAsMap(routeNode.getConfigParams());
 1252  0
         if (!cfgMap.containsKey(RouteNode.RULE_SELECTOR_CFG_KEY)) {
 1253  0
             routeNode.getConfigParams().add(new RouteNodeConfigParam(routeNode, RouteNode.RULE_SELECTOR_CFG_KEY, FlexRM.DEFAULT_RULE_SELECTOR));
 1254  
         }
 1255  
 
 1256  0
         if (((Boolean) getXPath().evaluate("./ruleTemplate", node, XPathConstants.BOOLEAN)).booleanValue()) {
 1257  0
             String ruleTemplateName = (String) getXPath().evaluate("./ruleTemplate", node, XPathConstants.STRING);
 1258  0
             RuleTemplate ruleTemplate = KEWServiceLocator.getRuleTemplateService().findByRuleTemplateName(ruleTemplateName);
 1259  0
             if (ruleTemplate == null) {
 1260  0
                 throw new InvalidXmlException("Rule template for node '" + routeNode.getRouteNodeName() + "' not found: " + ruleTemplateName);
 1261  
             }
 1262  0
             routeNode.setRouteMethodName(ruleTemplateName);
 1263  0
             routeNode.setRouteMethodCode(KEWConstants.ROUTE_LEVEL_FLEX_RM);
 1264  0
         } else if (((Boolean) getXPath().evaluate("./routeModule", node, XPathConstants.BOOLEAN)).booleanValue()) {
 1265  0
             routeNode.setRouteMethodName((String) getXPath().evaluate("./routeModule", node, XPathConstants.STRING));
 1266  0
             routeNode.setRouteMethodCode(KEWConstants.ROUTE_LEVEL_ROUTE_MODULE);
 1267  
         }
 1268  
 
 1269  0
         String nodeType = null;
 1270  0
         if (((Boolean) getXPath().evaluate("./type", node, XPathConstants.BOOLEAN)).booleanValue()) {
 1271  0
             nodeType = (String) getXPath().evaluate("./type", node, XPathConstants.STRING);
 1272  
         } else {
 1273  0
             String localName = (String) getXPath().evaluate("local-name(.)", node, XPathConstants.STRING);
 1274  0
             if ("start".equalsIgnoreCase(localName)) {
 1275  0
                 nodeType = "org.kuali.rice.kew.engine.node.InitialNode";
 1276  0
             } else if ("split".equalsIgnoreCase(localName)) {
 1277  0
                 nodeType = "org.kuali.rice.kew.engine.node.SimpleSplitNode";
 1278  0
             } else if ("join".equalsIgnoreCase(localName)) {
 1279  0
                 nodeType = "org.kuali.rice.kew.engine.node.SimpleJoinNode";
 1280  0
             } else if ("requests".equalsIgnoreCase(localName)) {
 1281  0
                 nodeType = "org.kuali.rice.kew.engine.node.RequestsNode";
 1282  0
             } else if ("process".equalsIgnoreCase(localName)) {
 1283  0
                 nodeType = "org.kuali.rice.kew.engine.node.SimpleSubProcessNode";
 1284  0
             } else if (NodeType.ROLE.getName().equalsIgnoreCase(localName)) {
 1285  0
                 nodeType = RoleNode.class.getName();
 1286  
             }
 1287  
         }
 1288  0
         if (Utilities.isEmpty(nodeType)) {
 1289  0
             throw new InvalidXmlException("Could not determine node type for the node named '" + routeNode.getRouteNodeName() + "'");
 1290  
         }
 1291  0
         routeNode.setNodeType(nodeType);
 1292  
 
 1293  0
         String localName = (String) getXPath().evaluate("local-name(.)", node, XPathConstants.STRING);
 1294  0
         if ("split".equalsIgnoreCase(localName)) {
 1295  0
             context.splitNodeStack.addFirst(routeNode);
 1296  0
         } else if ("join".equalsIgnoreCase(localName) && context.splitNodeStack.size() != 0) {
 1297  
             // join node should have same branch prototype as split node
 1298  0
             RouteNode splitNode = (RouteNode)context.splitNodeStack.removeFirst();
 1299  0
             context.branch = splitNode.getBranch();
 1300  0
         } else if (NodeType.ROLE.getName().equalsIgnoreCase(localName)) {
 1301  0
             routeNode.setRouteMethodName(RoleRouteModule.class.getName());
 1302  0
             routeNode.setRouteMethodCode(KEWConstants.ROUTE_LEVEL_ROUTE_MODULE);
 1303  
         }
 1304  0
         routeNode.setBranch(context.branch);
 1305  
 
 1306  0
         return routeNode;
 1307  
     }
 1308  
 
 1309  
     private List getDocumentTypePolicies(NodeList documentTypePolicies, DocumentType documentType) throws XPathExpressionException, InvalidXmlException {
 1310  0
         List policies = new ArrayList();
 1311  0
         Set policyNames = new HashSet();
 1312  
 
 1313  0
         for (int i = 0; i < documentTypePolicies.getLength(); i++) {
 1314  0
             DocumentTypePolicy policy = new DocumentTypePolicy();
 1315  0
             policy.setDocumentTypeId(documentType.getDocumentTypeId());
 1316  
             try {
 1317  0
                 String policyName = (String) getXPath().evaluate("./name", documentTypePolicies.item(i), XPathConstants.STRING);
 1318  0
                 policy.setPolicyName(DocumentTypePolicyEnum.lookup(policyName).getName().toUpperCase());
 1319  0
             } catch (XPathExpressionException xpee) {
 1320  0
                 LOG.error("Error obtaining document type policy name", xpee);
 1321  0
                 throw xpee;
 1322  0
             }
 1323  
             try {
 1324  0
                 if (((Boolean) getXPath().evaluate("./value", documentTypePolicies.item(i), XPathConstants.BOOLEAN)).booleanValue()) {
 1325  0
                     policy.setPolicyValue(Boolean.valueOf((String) getXPath().evaluate("./value", documentTypePolicies.item(i), XPathConstants.STRING)));
 1326  
                 } else {
 1327  0
                     policy.setPolicyValue(Boolean.FALSE);
 1328  
                 }
 1329  0
             } catch (XPathExpressionException xpee) {
 1330  0
                 LOG.error("Error obtaining document type policy value", xpee);
 1331  0
                 throw xpee;
 1332  0
             }
 1333  
             try {
 1334  0
                     String policyStringValue = (String) getXPath().evaluate("./stringValue", documentTypePolicies.item(i), XPathConstants.STRING);
 1335  0
                     if (!StringUtils.isEmpty(policyStringValue)){
 1336  0
                             policy.setPolicyStringValue(policyStringValue.toUpperCase());
 1337  0
                             policy.setPolicyValue(Boolean.TRUE);
 1338  
                             // if DocumentStatusPolicy, check against allowable values
 1339  0
                             if (KEWConstants.DOCUMENT_STATUS_POLICY.equalsIgnoreCase(DocumentTypePolicyEnum.lookup(policy.getPolicyName()).getName())){
 1340  0
                                     boolean found = false;
 1341  0
                                     for (int index=0; index<KEWConstants.DOCUMENT_STATUS_POLICY_VALUES.length; index++) {
 1342  0
                                             if (KEWConstants.DOCUMENT_STATUS_POLICY_VALUES[index].equalsIgnoreCase(policyStringValue)){
 1343  0
                                                     found = true;
 1344  0
                                                     break;
 1345  
                                             }                                                    
 1346  
                                     }
 1347  0
                                     if (!found){
 1348  0
                                             throw new InvalidXmlException("Application Document Status string value: " + policyStringValue + " is invalid.");
 1349  
                                     }
 1350  0
                             }
 1351  
                             
 1352  
                     } else {
 1353  
                             //DocumentStatusPolicy requires a <stringValue> tag
 1354  0
                             if (KEWConstants.DOCUMENT_STATUS_POLICY.equalsIgnoreCase(DocumentTypePolicyEnum.lookup(policy.getPolicyName()).getName())){
 1355  0
                                     throw new InvalidXmlException("Application Document Status Policy requires a <stringValue>");                                    
 1356  
                             }
 1357  
                     }
 1358  0
             } catch (XPathExpressionException xpee) {
 1359  0
                 LOG.error("Error obtaining document type policy string value", xpee);
 1360  0
                 throw xpee;
 1361  0
             }
 1362  
             
 1363  0
             if (!policyNames.add(policy.getPolicyName())) {
 1364  0
                 throw new InvalidXmlException("Policy '" + policy.getPolicyName() + "' has already been defined on this document");
 1365  
             } else {
 1366  0
                 policies.add(policy);
 1367  
             }
 1368  
         }
 1369  
 
 1370  0
         return policies;
 1371  
     }
 1372  
 
 1373  
     private List getDocumentTypeStatuses(NodeList documentTypeStatuses, DocumentType documentType) throws XPathExpressionException, InvalidXmlException {
 1374  0
         List statuses = new ArrayList();
 1375  0
         Set statusNames = new HashSet();
 1376  
 
 1377  0
         for (int i = 0; i < documentTypeStatuses.getLength(); i++) {
 1378  0
                 ApplicationDocumentStatus status = new ApplicationDocumentStatus();
 1379  0
                 status.setDocumentTypeId(documentType.getDocumentTypeId());
 1380  0
                 Node myNode = documentTypeStatuses.item(i);  
 1381  0
                 String statusName = myNode.getFirstChild().getNodeValue();
 1382  0
                 status.setStatusName(statusName);
 1383  0
                 if (!statusNames.add(status.getStatusName())) {
 1384  0
                         throw new InvalidXmlException("Application Status '" + status.getStatusName() + "' has already been defined on this document");
 1385  
                 } else {
 1386  0
                         statuses.add(status);
 1387  
                 }      
 1388  
         }
 1389  0
         return statuses;
 1390  
     }
 1391  
 
 1392  
     private List getDocumentTypeAttributes(NodeList documentTypeAttributes, DocumentType documentType) throws XPathExpressionException, WorkflowException {
 1393  0
         List attributes = new ArrayList();
 1394  
 
 1395  0
         for (int i = 0; i < documentTypeAttributes.getLength(); i++) {
 1396  0
             DocumentTypeAttribute attribute = new DocumentTypeAttribute();
 1397  0
             attribute.setDocumentType(documentType);
 1398  
             String ruleAttributeName;
 1399  
             try {
 1400  0
                 ruleAttributeName = (String) getXPath().evaluate("./name", documentTypeAttributes.item(i), XPathConstants.STRING);
 1401  0
             } catch (XPathExpressionException xpee) {
 1402  0
                 LOG.error("Error obtaining rule attribute name", xpee);
 1403  0
                 throw xpee;
 1404  0
             }
 1405  0
             RuleAttribute ruleAttribute = KEWServiceLocator.getRuleAttributeService().findByName(ruleAttributeName);
 1406  0
             if (ruleAttribute == null) {
 1407  0
                 throw new WorkflowException("Could not find rule attribute: " + ruleAttributeName);
 1408  
             }
 1409  0
             attribute.setDocumentType(documentType);
 1410  0
             attribute.setRuleAttribute(ruleAttribute);
 1411  0
             attribute.setOrderIndex(i+1);
 1412  0
             attributes.add(attribute);
 1413  
         }
 1414  0
         return attributes;
 1415  
     }
 1416  
 
 1417  0
     private class RoutePathContext {
 1418  
         public BranchPrototype branch;
 1419  0
         public LinkedList splitNodeStack = new LinkedList();
 1420  
     }
 1421  
 
 1422  
     protected IdentityManagementService getIdentityManagementService() {
 1423  0
         return KIMServiceLocator.getIdentityManagementService();
 1424  
     }
 1425  
 
 1426  
     /**
 1427  
      * This is a helper class for indicating if an unprocessed document type node is "standard" or "routing."
 1428  
      * 
 1429  
      * @author Kuali Rice Team (rice.collab@kuali.org)
 1430  
      */
 1431  0
     private class DocTypeNode {
 1432  
         /** The Node that needs to be converted into a doc type. */
 1433  
         public final Node docNode;
 1434  
         /** A flag for indicating the document's type; true indicates "standard," false indicates "routing." */
 1435  
         public final boolean isStandard;
 1436  
         
 1437  
         /**
 1438  
          * Constructs a DocTypeNode instance containing the specified Node and flag.
 1439  
          * 
 1440  
          * @param newNode The unprocessed document type.
 1441  
          * @param newFlag An indicator of what type of document this is (true for "standard," false for "routing").
 1442  
          */
 1443  0
         public DocTypeNode(Node newNode, boolean newFlag) {
 1444  0
             docNode = newNode;
 1445  0
             isStandard = newFlag;
 1446  0
         }
 1447  
     }
 1448  
 
 1449  
 }