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