Java Code Examples for org.jdom.Element#getChildText()

The following examples show how to use org.jdom.Element#getChildText() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PoolDefinition.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a new storage pool definition from a libvirt XML description.
 *
 * @param xmlDef libvirt XML storage pool definition
 * @return parsed definition or {@code null}
 */
public static PoolDefinition parse(String xmlDef) {
    PoolDefinition def = null;
    SAXBuilder builder = new SAXBuilder();
    builder.setValidation(false);

    try {
        Document doc = builder.build(new StringReader(xmlDef));
        def = new PoolDefinition();

        Element poolElement = doc.getRootElement();
        def.type = poolElement.getAttributeValue("type");
        def.setName(poolElement.getChildText("name"));
        def.uuid = poolElement.getChildText("uuid");

        def.setTarget(PoolTarget.parse(poolElement.getChild("target")));
        def.setSource(PoolSource.parse(poolElement.getChild("source")));
    }
    catch (Exception e) {
        LOG.error("failed to parse libvirt pool XML definition: " + e.getMessage());
        def = null;
    }

    return def;
}
 
Example 2
Source File: DAOLunaticConfiguration.java    From Llunatic with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void loadAdditionalAttributes(Element additionalAttributesElement, Scenario scenario) {
    if (additionalAttributesElement == null || additionalAttributesElement.getChildren().isEmpty()) {
        return;
    }
    List<Element> dependencies = additionalAttributesElement.getChildren("dependency");
    for (Element dependencyElement : dependencies) {
        String dependencyId = dependencyElement.getChildText("id");
        String stringAttributeRef = dependencyElement.getChildText("attribute");
        AttributeRef attributeRef = parseAttributeRef(stringAttributeRef);
        Dependency dependency = scenario.getDependency(dependencyId);
        if (dependency == null) {
            throw new it.unibas.lunatic.exceptions.DAOException("Unable to set additional attribute for unkown dependency " + dependencyId);
        }
        dependency.addAdditionalAttribute(attributeRef);
    }
}
 
Example 3
Source File: AboutCommands.java    From geoserver-shell with MIT License 6 votes vote down vote up
@CliCommand(value = "version list", help = "Get versions.")
public String versionList() throws Exception {
    String TAB = "   ";
    String xml = HTTPUtils.get(geoserver.getUrl() + "/rest/about/versions.xml", geoserver.getUser(), geoserver.getPassword());
    StringBuilder builder = new StringBuilder();
    Element root = JDOMBuilder.buildElement(xml);

    List<Element> resources = root.getChildren("resource");
    for (Element resource : resources) {
        String name = resource.getAttributeValue("name");
        String buildTime = resource.getChildText("Build-Timestamp");
        String gitRevision = resource.getChildText("Git-Revision");
        String version = resource.getChildText("Version");
        builder.append(name).append(OsUtils.LINE_SEPARATOR);
        builder.append(TAB).append("Version: ").append(version).append(OsUtils.LINE_SEPARATOR);
        builder.append(TAB).append("Build Time: ").append(buildTime).append(OsUtils.LINE_SEPARATOR);
        builder.append(TAB).append("Git Revision: ").append(gitRevision).append(OsUtils.LINE_SEPARATOR);
        builder.append(OsUtils.LINE_SEPARATOR);
    }

    return builder.toString();
}
 
Example 4
Source File: AlgorithmXML.java    From KEEL with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Builder
 * @param xml File with the description of the algorithm
 */
public AlgorithmXML(Element xml) {

    name = xml.getChildText("name");

    //System.out.println (" \n> Name: "+name);
    family = xml.getChildText("family");

    //System.out.println ("    > family: "+family);
    problemType = xml.getChildText("problem_type");

    //System.out.println ("    > problemType: "+problemType);
    jarFile = xml.getChildText("jar_file");

    if (xml.getChild("input") != null) {
        getInputVariables(xml.getChild("input"));
    }

    if (xml.getChild("output") != null) {
        getOutputVariables(xml.getChild("output"));
    }

}
 
Example 5
Source File: YahooPlaceFinderGeocoderService.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void canonicalAdd(List<String> canonical, Element locationElement,
		String tag) {
	String value = locationElement.getChildText(tag);
	if (null != value && value.length() > 0) {
		canonical.add(value);
	}
}
 
Example 6
Source File: AssessmentParser.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void 
parseContent(DefaultHandler handler,
             CartridgeLoader the_cartridge, 
             Element the_resource,
             boolean isProtected) throws ParseException {

    // this is now handled by the import object method for the appropriate testing engine.
    // I've seen this generate a spurious error, so don't do it
    if (false) {
  try {
    String href=((Element)the_resource.getChildren(FILE, handler.getNs().cc_ns()).get(0)).getAttributeValue(HREF);
    Element qti=getXML(the_cartridge,href);
    handler.startAssessment(href, isProtected);
    Element assessment=qti.getChild(ASSESSMENT, QTI_NS);
    handler.setAssessmentDetails(assessment.getAttributeValue(IDENT), 
                                 assessment.getAttributeValue(TITLE));
    handler.setAssessmentXml(qti);
    String qti_comment=assessment.getChildText(QTI_COMMENT, QTI_NS);
    if (qti_comment!=null) {
      handler.setQTIComment(qti_comment);
    }
    processQTIMetadata(assessment, handler);
    List items=assessment.getChild(SECTION, QTI_NS).getChildren(ITEM, QTI_NS);
    for (Iterator iter=items.iterator(); iter.hasNext();) {
      handler.addAssessmentItem(processItem((Element)iter.next()));
    }      
  } catch (IOException e) {
    throw new ParseException(e.getMessage(), e);
  } 
    }
  handler.endAssessment();
}
 
Example 7
Source File: RuleExtensionXmlParser.java    From rice with Educational Community License v2.0 5 votes vote down vote up
private RuleExtensionBo parseRuleExtension(Element element, RuleBaseValues rule) throws XmlException {
String attributeName = element.getChildText(ATTRIBUTE, NAMESPACE);
String templateName = element.getChildText(RULE_TEMPLATE, NAMESPACE);
Element valuesElement = element.getChild(RULE_EXTENSION_VALUES, NAMESPACE);
if (attributeName == null) {
    throw new XmlException("Rule extension must have a valid attribute.");
}
if (templateName == null) {
    throw new XmlException("Rule extension must have a valid rule template.");
}
RuleAttribute ruleAttribute = KEWServiceLocator.getRuleAttributeService().findByName(attributeName);
if (ruleAttribute == null) {
    throw new XmlException("Could not locate attribute for the given name '" + attributeName + "'");
}
RuleTemplateBo ruleTemplate = KEWServiceLocator.getRuleTemplateService().findByRuleTemplateName(templateName);
if (ruleTemplate == null) {
    throw new XmlException("Could not locate rule template for the given name '" + templateName + "'");
}
RuleExtensionBo extension = new RuleExtensionBo();
extension.setRuleBaseValues(rule);
boolean attributeFound = false;
for (Iterator iter = ruleTemplate.getActiveRuleTemplateAttributes().iterator(); iter.hasNext();) {
    RuleTemplateAttributeBo templateAttribute = (RuleTemplateAttributeBo) iter.next();
    if (templateAttribute.getRuleAttributeId().equals(ruleAttribute.getId())) {
	extension.setRuleTemplateAttribute(templateAttribute);
	extension.setRuleTemplateAttributeId(templateAttribute.getId());
	attributeFound = true;
	break;
    }
}

if (!attributeFound) {
    // TODO: need test case for this
    throw new XmlException("Attribute '" + attributeName + "' not found on template '" + ruleTemplate.getName() + "'");
}

extension.setExtensionValues(parseRuleExtensionValues(valuesElement, extension));
return extension;
   }
 
Example 8
Source File: Issue.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
@Deprecated
@Override
public String getTagValue(String name, Date date) {
	Date lastDate = null;
	String lastValue = null;

	if (mTagRoot == null) return lastValue;
	@SuppressWarnings("unchecked")
	List<Element> historyList = mTagRoot.getChildren();
	for (Element history : historyList) {
		String value = history.getChildText(name);
		Date modifyDate = DateUtil.dayFillter(history.getAttributeValue(ScrumEnum.ID_HISTORY_ATTR), DateUtil._16DIGIT_DATE_TIME_2);
		if (value != null && date.getTime() >= DateUtil.dayFilter(modifyDate).getTime()) {
			if (lastDate == null) {
				lastDate = modifyDate;
				lastValue = value;
				continue;
			}
			if (modifyDate.getTime() > lastDate.getTime()) {
				lastDate = modifyDate;
				lastValue = value;
				continue;
			}
		}
	}
	return lastValue;
}
 
Example 9
Source File: JDOMUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static boolean getBooleanVal(
    final Element e,
    final String childTag,
    final boolean defaultValue) {
  if ((e == null) || (e.getChildText(childTag) == null)) {
    return defaultValue;
  }

  final Boolean value = getBooleanVal(e, childTag);
  if (value == null) {
    return defaultValue;
  }
  return value;
}
 
Example 10
Source File: WorkspaceCommands.java    From geoserver-shell with MIT License 5 votes vote down vote up
@CliCommand(value = "workspace get", help = "Get a workspace.")
public String get(
        @CliOption(key = "name", mandatory = true, help = "The name") String name) throws Exception {
    String url = geoserver.getUrl() + "/rest/workspaces/" + name + ".xml";
    String xml = HTTPUtils.get(url, geoserver.getUser(), geoserver.getPassword());
    Element workspaceElement = JDOMBuilder.buildElement(xml);
    String nm = workspaceElement.getChildText("name");
    return nm;
}
 
Example 11
Source File: InspectionTestUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
static boolean compareFiles(Element reportedProblem, Element expectedProblem) {
  String reportedFileName = reportedProblem.getChildText("file");
  if (reportedFileName == null) {
    return true;
  }
  File reportedFile = new File(reportedFileName);

  return Comparing.equal(reportedFile.getName(), expectedProblem.getChildText("file"));
}
 
Example 12
Source File: FYIByUniversityId.java    From rice with Educational Community License v2.0 5 votes vote down vote up
public SimpleResult process(RouteContext context, RouteHelper helper)
		throws Exception {

       LOG.debug("processing FYIByUniversityId node");
       Element rootElement = getRootElement(new StandardDocumentContent(context.getDocument().getDocContent()));
		Collection<Element> fieldElements = XmlHelper.findElements(rootElement, "field");
       Iterator<Element> elementIter = fieldElements.iterator();
       while (elementIter.hasNext()) {
       	Element field = (Element) elementIter.next();
       	Element version = field.getParentElement();
       	if (version.getAttribute("current").getValue().equals("true")) {
       		LOG.debug("Looking for studentUid field:  " + field.getAttributeValue("name"));
              	if (field.getAttribute("name")!= null && field.getAttributeValue("name").equals("studentUid")) {
              		String employeeId = field.getChildText("value");
           		LOG.debug("Should send an FYI to employee ID:  " + employeeId);
              		if (!StringUtils.isBlank(employeeId)) {
              			Person person = KimApiServiceLocator.getPersonService().getPerson(employeeId);

              			if (person == null) {
              				throw new WorkflowRuntimeException("Failed to locate a Person with the given employee ID: " + employeeId);
              			}
              			if (!context.isSimulation()) {
              				KEWServiceLocator.getWorkflowDocumentService().adHocRouteDocumentToPrincipal(person.getPrincipalId(), context.getDocument(), KewApiConstants.ACTION_REQUEST_FYI_REQ, null, null, "Notification Request", person.getPrincipalId(), "Notification Request", true, null);
              			}
              			//wfDoc.adHocRouteDocumentToPrincipal(KewApiConstants.ACTION_REQUEST_FYI_REQ, "Notification Request", new EmplIdVO(field.getChildText("value")), "Notification Request", true);
               		LOG.debug("Sent FYI using the adHocRouteDocumentToPrincipal function to UniversityID:  " + person.getEmployeeId());
               		break;
              	}
       	}
       }
       }
	return super.process(context, helper);
}
 
Example 13
Source File: MailConfigDOM.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Extract the smtp configuration from the xml element and save it into the MailConfig object.
 * @param root The xml root element containing the smtp configuration.
 * @param config The configuration.
 */
private void extractSmtp(Element root, MailConfig config) {
	Element smtpElem = root.getChild(SMTP_ELEM);
	if (smtpElem != null) {
		String debug = smtpElem.getAttributeValue(SMTP_DEBUG_ATTR);
		config.setDebug("true".equalsIgnoreCase(debug));
		config.setSmtpHost(smtpElem.getChildText(SMTP_HOST_CHILD));
		String port = smtpElem.getChildText(SMTP_PORT_CHILD);
		if (port != null && port.trim().length() > 0) {
			config.setSmtpPort(new Integer(port.trim()));
		}
		String timeout = smtpElem.getChildText(SMTP_TIMEOUT_CHILD);
		if (timeout != null && timeout.trim().length() > 0) {
			config.setSmtpTimeout(new Integer(timeout.trim()));
		}
		config.setSmtpUserName(smtpElem.getChildText(SMTP_USER_CHILD));
		config.setSmtpPassword(smtpElem.getChildText(SMTP_PASSWORD_CHILD));
		String proto = smtpElem.getChildText(SMTP_PROTOCOL_CHILD);
		if (null != proto) {
			if (proto.equalsIgnoreCase(PROTO_SSL)) {
				config.setSmtpProtocol(JpmailSystemConstants.PROTO_SSL);
			} else if (proto.equalsIgnoreCase(PROTO_TLS)) {
				config.setSmtpProtocol(JpmailSystemConstants.PROTO_TLS);
			} else {
				// any unknown protocol will disable encryption
				config.setSmtpProtocol(JpmailSystemConstants.PROTO_STD);
			}
		}
	}
}
 
Example 14
Source File: LafManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void loadState(final Element element) {
  String className = null;

  Element lafElement = element.getChild(ELEMENT_LAF);
  if(lafElement != null) {
    className = lafElement.getAttributeValue(ATTRIBUTE_CLASS_NAME);
  }

  String localeText = element.getChildText(ELEMENT_LOCALE);
  if(localeText != null) {
    myLocalizeManager.setLocale(myLocalizeManager.parseLocale(localeText), false);
  }

  UIManager.LookAndFeelInfo laf = findLaf(className);
  // If LAF is undefined (wrong class name or something else) we have set default LAF anyway.
  if (laf == null) {
    laf = getDefaultLaf();
  }

  if (myCurrentLaf != null && !laf.getClassName().equals(myCurrentLaf.getClassName())) {
    setCurrentLookAndFeel(laf);
    updateUI();
  }

  myCurrentLaf = laf;
}
 
Example 15
Source File: RuleTemplateXmlParser.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
 * Updates the rule template defaults options with those in the defaults element
 * @param defaultsElement the ruleDefaults element
 * @param updatedRuleTemplate the Rule Template being updated
 */
protected void updateRuleTemplateOptions(Element defaultsElement, RuleTemplateBo updatedRuleTemplate, boolean isDelegation) throws XmlException {
    // the possible defaults options
    // NOTE: the current implementation will remove any existing RuleTemplateOption records for any values which are null, i.e. not set in the incoming XML.
    // to pro-actively set default values for omitted options, simply set those values here, and records will be added if not present
    String defaultActionRequested = null;
    Boolean supportsComplete = null;
    Boolean supportsApprove = null;
    Boolean supportsAcknowledge = null;
    Boolean supportsFYI = null;
    
    // remove any RuleTemplateOptions the template may have but that we know we aren't going to update/reset
    // (not sure if this case even exists...does anything else set rule template options?)
    updatedRuleTemplate.removeNonDefaultOptions();
    
    // read in new settings
    if (defaultsElement != null) {

    	defaultActionRequested = defaultsElement.getChildText(DEFAULT_ACTION_REQUESTED, RULE_TEMPLATE_NAMESPACE);
        supportsComplete = BooleanUtils.toBooleanObject(defaultsElement.getChildText(SUPPORTS_COMPLETE, RULE_TEMPLATE_NAMESPACE));
        supportsApprove = BooleanUtils.toBooleanObject(defaultsElement.getChildText(SUPPORTS_APPROVE, RULE_TEMPLATE_NAMESPACE));
        supportsAcknowledge = BooleanUtils.toBooleanObject(defaultsElement.getChildText(SUPPORTS_ACKNOWLEDGE, RULE_TEMPLATE_NAMESPACE));
        supportsFYI = BooleanUtils.toBooleanObject(defaultsElement.getChildText(SUPPORTS_FYI, RULE_TEMPLATE_NAMESPACE));
    }

    if (!isDelegation) {
        // if this is not a delegation template, store the template options that govern rule action constraints
        // in the RuleTemplateOptions of the template
        // we have two options for this behavior:
        // 1) conditionally parse above, and then unconditionally set/unset the properties; this will have the effect of REMOVING
        //    any of these previously specified rule template options (and is arguably the right thing to do)
        // 2) unconditionally parse above, and then conditionally set/unset the properties; this will have the effect of PRESERVING
        //    the existing rule template options on this template if it is a delegation template (which of course will be overwritten
        //    by this very same code if they subsequently upload without the delegation flag)
        // This is a minor point, but the second implementation is chosen as it preserved the current behavior
        updateOrDeleteRuleTemplateOption(updatedRuleTemplate, KewApiConstants.ACTION_REQUEST_DEFAULT_CD, defaultActionRequested);
        updateOrDeleteRuleTemplateOption(updatedRuleTemplate, KewApiConstants.ACTION_REQUEST_APPROVE_REQ, supportsApprove);
        updateOrDeleteRuleTemplateOption(updatedRuleTemplate, KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ, supportsAcknowledge);
        updateOrDeleteRuleTemplateOption(updatedRuleTemplate, KewApiConstants.ACTION_REQUEST_FYI_REQ, supportsFYI);
        updateOrDeleteRuleTemplateOption(updatedRuleTemplate, KewApiConstants.ACTION_REQUEST_COMPLETE_REQ, supportsComplete);
    }

}
 
Example 16
Source File: GappModel.java    From gate-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
MavenPlugin(Element pluginElt) {
  group = pluginElt.getChildText("group");
  artifact = pluginElt.getChildText("artifact");
  version = pluginElt.getChildText("version");
}
 
Example 17
Source File: Parser.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private void
processItem(Element the_item, 
  Element the_resources,
  DefaultHandler the_handler) throws ParseException {
 try {
  if (the_item.getAttributeValue(CC_ITEM_IDREF)!=null) {
	  Element resource=findResource(ns,the_item.getAttributeValue(CC_ITEM_IDREF), the_resources);
	  if (resource == null) {
		  the_handler.getSimplePageBean().setErrKey("simplepage.cc-noresource", the_item.getAttributeValue(CC_ITEM_IDREF));
		  return;
	  }
	  log.debug("process item " + the_item + " resources " + the_resources + " resource " + resource);

	  the_handler.startCCItem(the_item.getAttributeValue(CC_ITEM_ID),
	  the_item.getChildText(CC_ITEM_TITLE, ns.getNs()));
	  the_handler.setCCItemXml(the_item, resource, this, utils, false);
	  processResource(resource,
                    the_handler);
	  the_handler.endCCItem();
  } else {

	  //CP formats don't follow the hierarchy standard at
	  //http://www.imsglobal.org/cc/ccv1p0/imscc_profilev1p0.html#0_pgfId-1753534
	  //So we need to skip the ones where title isn't defined (which would indicate that it is a valid folder and not just containing sub-items)
	  String title = the_item.getChildText(CC_ITEM_TITLE, ns.getNs());
	  if (title != null) {
		  the_handler.startCCFolder(the_item);
	  }
	  for (Iterator iter=the_item.getChildren(CC_ITEM, ns.getNs()).iterator();iter.hasNext();) {
		  processItem((Element)iter.next(), the_resources, the_handler);
	  }
	  if (title != null) {
		  the_handler.endCCFolder();
	  }
  }
 } catch (Exception e) {
  log.error(e.getMessage(), e);
  if (the_item == null)
	  log.info("processitem the item null");
  else 
	  log.info("processitem failed " + the_item.getAttributeValue(CC_ITEM_IDREF));
 }
}
 
Example 18
Source File: Parser.java    From gate-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Given xml representation of HIT converts them into an array of hits
 * @throws IOException
 */
public static Hit[] fromXML(String xml) throws IOException, JDOMException {
  SAXBuilder saxBuilder = new SAXBuilder(false);
  org.jdom.Document jdomDoc = saxBuilder.build(new StringReader(xml));
  Element rootElement = jdomDoc.getRootElement();
  if(!rootElement.getName().equalsIgnoreCase(HITS)) {
    throw new IOException("Root element must be " + HITS);
  }

  // rootElement is HITS
  // this will internally contains instances of HIT
  List<?> hitsChildren = rootElement.getChildren(HIT);
  Hit[] hits = new Hit[hitsChildren.size()];

  for(int i = 0; i < hitsChildren.size(); i++) {
    Element hitElem = (Element)hitsChildren.get(i);
    int startOffset = Integer.parseInt(hitElem.getChildText(START_OFFSET));
    int endOffset = Integer.parseInt(hitElem.getChildText(END_OFFSET));
    String docID = hitElem.getChildText(DOC_ID);
    String annotationSetName = hitElem.getChildText(ANNOTATION_SET_NAME);
    String queryString = hitElem.getChildText(QUERY);

    Element patternAnnotations = hitElem.getChild(PATTERN_ANNOTATIONS);
    if(patternAnnotations == null) {
      hits[i] = new Hit(docID, annotationSetName, startOffset, endOffset, queryString);
      continue;
    }

    List<?> patAnnots = patternAnnotations.getChildren(PATTERN_ANNOTATION);
    List<PatternAnnotation> patAnnotsList = new ArrayList<PatternAnnotation>();
    for(int j = 0; j < patAnnots.size(); j++) {
      Element patAnnot = (Element)patAnnots.get(j);
      PatternAnnotation pa = new PatternAnnotation();
      pa.setStOffset(Integer.parseInt(patAnnot.getChildText(START)));
      pa.setEnOffset(Integer.parseInt(patAnnot.getChildText(END)));
      pa.setPosition(Integer.parseInt(patAnnot.getChildText(POSITION)));
      pa.setText(patAnnot.getChildText(TEXT));
      pa.setType(patAnnot.getChildText(TYPE));

      // we need to find out its features
      Element featuresElem = patAnnot.getChild(FEATURES);
      // more than one features possible
      List<?> featuresElemsList = featuresElem.getChildren(FEATURE);
      for(int k = 0; k < featuresElemsList.size(); k++) {
        Element featureElem = (Element)featuresElemsList.get(k);
        String key = featureElem.getChildText(KEY);
        String value = featureElem.getChildText(VALUE);
        pa.addFeature(key, value);
      }
      patAnnotsList.add(pa);
    }

    String patternText = hitElem.getChildText(PATTERN_TEXT);
    int leftCSO = Integer.parseInt(hitElem
            .getChildText(LEFT_CONTEXT_START_OFFSET));
    int rightCEO = Integer.parseInt(hitElem
            .getChildText(RIGHT_CONTEXT_END_OFFSET));

    hits[i] = new Pattern(docID, annotationSetName, patternText, startOffset, endOffset,
            leftCSO, rightCEO, patAnnotsList, queryString);
  }
  return hits;
}
 
Example 19
Source File: Samdas.java    From elexis-3-core with Eclipse Public License 1.0 4 votes vote down vote up
/** Shortcut für Dokumente, die sowieso nur einen Record haben */
public String getRecordText(){
	Element rec = getRecordElement();
	String ret = rec.getChildText(ELEM_TEXT, ns);
	return ret == null ? "" : ret; //$NON-NLS-1$
}
 
Example 20
Source File: RuleXmlParser.java    From rice with Educational Community License v2.0 4 votes vote down vote up
public RuleResponsibilityBo parseResponsibility(Element element, RuleBaseValues rule) throws XmlException {
    RuleResponsibilityBo responsibility = new RuleResponsibilityBo();
    responsibility.setRuleBaseValues(rule);
    String actionRequested = null;
    String priority = null;
    actionRequested = element.getChildText(ACTION_REQUESTED, element.getNamespace());
    if (StringUtils.isBlank(actionRequested)) {
    	actionRequested = DEFAULT_ACTION_REQUESTED;
    }
    priority = element.getChildText(PRIORITY, element.getNamespace());
    if (StringUtils.isBlank(priority)) {
    	priority = String.valueOf(DEFAULT_RULE_PRIORITY);
    }
    String approvePolicy = element.getChildText(APPROVE_POLICY, element.getNamespace());
    Element delegations = element.getChild(DELEGATIONS, element.getNamespace());
    if (actionRequested == null) {
        throw new XmlException("actionRequested is required on responsibility");
    }
    if (!actionRequested.equals(KewApiConstants.ACTION_REQUEST_COMPLETE_REQ) && !actionRequested.equals(KewApiConstants.ACTION_REQUEST_APPROVE_REQ) && !actionRequested.equals(KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ) && !actionRequested.equals(KewApiConstants.ACTION_REQUEST_FYI_REQ)) {
        throw new XmlException("Invalid action requested code '" + actionRequested + "'");
    }
    if (StringUtils.isBlank(approvePolicy)) {
        approvePolicy = DEFAULT_APPROVE_POLICY;
    }
    if (!approvePolicy.equals(ActionRequestPolicy.ALL.getCode()) && !approvePolicy.equals(ActionRequestPolicy.FIRST.getCode())) {
        throw new XmlException("Invalid approve policy '" + approvePolicy + "'");
    }
    Integer priorityNumber = Integer.valueOf(priority);
    responsibility.setActionRequestedCd(actionRequested);
    responsibility.setPriority(priorityNumber);
    responsibility.setApprovePolicy(approvePolicy);
    
    RuleResponsibilityBo responsibilityNameAndType = CommonXmlParser.parseResponsibilityNameAndType(element);
    if (responsibilityNameAndType == null) {
    	throw new XmlException("Could not locate a valid responsibility declaration on a responsibility on rule with description '" + rule.getDescription() + "'");
    }
    if (responsibilityNameAndType.getRuleResponsibilityType().equals(KewApiConstants.RULE_RESPONSIBILITY_GROUP_ID)
    		&& responsibility.getApprovePolicy().equals(ActionRequestPolicy.ALL.getCode())) {
    	throw new XmlException("Invalid approve policy '" + approvePolicy + "'.  This policy is not supported with Groups.");
    }
    responsibility.setRuleResponsibilityName(responsibilityNameAndType.getRuleResponsibilityName());
    responsibility.setRuleResponsibilityType(responsibilityNameAndType.getRuleResponsibilityType());
    
    return responsibility;
}