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