Java Code Examples for org.w3c.dom.Element#getAttribute()

The following examples show how to use org.w3c.dom.Element#getAttribute() . 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: XPathAttributeMatcher.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
public boolean match(Node testNode, Collection<String> wildcardValues) {
	if (testNode.getNodeType() == Node.ELEMENT_NODE) {
		// Node to test is element
		Element element = (Element) testNode;
		if (indexWildcard != -1) {
			// wildcard is defined in the attribute matcher.
			if (element.hasAttribute(attrName)) {
				// element define, attribute, match is OK.
				if (wildcardValues != null) {
					// wildcard values is filled, add the attribute value
					wildcardValues.add(element.getAttribute(attrName));
				}
				// element tested define the attribute, match is OK
				return true;
			}
			return false;
		}
		// No wildcard defined, test if element has attribute attrName and
		// if value is OK.
		String testAttrValue = element.getAttribute(attrName);
		return attrValue.equals(testAttrValue);
	}
	return false;
}
 
Example 2
Source File: SimpleParameterSet.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void loadValuesFromXML(Element xmlElement) {
  NodeList list = xmlElement.getElementsByTagName(parameterElement);
  for (int i = 0; i < list.getLength(); i++) {
    Element nextElement = (Element) list.item(i);
    String paramName = nextElement.getAttribute(nameAttribute);
    for (Parameter<?> param : parameters) {
      if (param.getName().equals(paramName)) {
        try {
          param.loadValueFromXML(nextElement);
        } catch (Exception e) {
          logger.log(Level.WARNING, "Error while loading parameter values for " + param.getName(),
              e);
        }
      }
    }
  }
}
 
Example 3
Source File: EntityData.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
public EntityData(Element element, SimpleMethod simpleMethod) throws MiniLangException {
    super(element, simpleMethod);
    if (MiniLangValidate.validationOn()) {
        MiniLangValidate.attributeNames(simpleMethod, element, "location", "timeout", "delegator-name", "error-list-name", "mode");
        MiniLangValidate.requiredAttributes(simpleMethod, element, "location");
        MiniLangValidate.expressionAttributes(simpleMethod, element, "delegator-name");
        MiniLangValidate.constantAttributes(simpleMethod, element, "timeout", "mode");
        MiniLangValidate.noChildElements(simpleMethod, element);
    }
    locationFse = FlexibleStringExpander.getInstance(element.getAttribute("location"));
    mode = MiniLangValidate.checkAttribute(element.getAttribute("mode"), "load");
    String timeoutAttribute = element.getAttribute("timeout");
    if (!"load".equals(mode) && !timeoutAttribute.isEmpty()) {
        MiniLangValidate.handleError("timeout attribute is valid only when mode=\"load\".", simpleMethod, element);
    }
    int timeout = -1;
    if (!timeoutAttribute.isEmpty()) {
        try {
            timeout = Integer.parseInt(timeoutAttribute);
        } catch (NumberFormatException e) {
            MiniLangValidate.handleError("Exception thrown while parsing timeout attribute: " + e.getMessage(), simpleMethod, element);
        }
    }
    this.timeout = timeout;
    errorListFma = FlexibleMapAccessor.getInstance(MiniLangValidate.checkAttribute(element.getAttribute("error-list-name"), "error_list"));
}
 
Example 4
Source File: MessageBrokerBeanDefinitionParser.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Nullable
private RuntimeBeanReference getValidator(
		Element messageBrokerElement, @Nullable Object source, ParserContext context) {

	if (messageBrokerElement.hasAttribute("validator")) {
		return new RuntimeBeanReference(messageBrokerElement.getAttribute("validator"));
	}
	else if (javaxValidationPresent) {
		RootBeanDefinition validatorDef = new RootBeanDefinition(
				"org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean");
		validatorDef.setSource(source);
		validatorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		String validatorName = context.getReaderContext().registerWithGeneratedName(validatorDef);
		context.registerComponent(new BeanComponentDefinition(validatorDef, validatorName));
		return new RuntimeBeanReference(validatorName);
	}
	else {
		return null;
	}
}
 
Example 5
Source File: mxUtils.java    From blog-codes with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the given value is an XML node with the node name and if
 * the optional attribute has the specified value.
 * 
 * @param value
 *            Object that should be examined as a node.
 * @param nodeName
 *            String that specifies the node name.
 * @param attributeName
 *            Optional attribute name to check.
 * @param attributeValue
 *            Optional attribute value to check.
 * @return Returns true if the value matches the given conditions.
 */
public static boolean isNode(Object value, String nodeName,
		String attributeName, String attributeValue)
{
	if (value instanceof Element)
	{
		Element element = (Element) value;

		if (nodeName == null
				|| element.getNodeName().equalsIgnoreCase(nodeName))
		{
			String tmp = (attributeName != null) ? element
					.getAttribute(attributeName) : null;

			return attributeName == null
					|| (tmp != null && tmp.equals(attributeValue));
		}
	}

	return false;
}
 
Example 6
Source File: ComplexType.java    From hop with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new complex type for the specified element.
 *
 * @param type      DOM element of the complex type.
 * @param wsdlTypes Namespace resolver instance.
 */
ComplexType( Element type, WsdlTypes wsdlTypes ) {

  _name = type.getAttribute( "name" );
  _wsdlTypes = wsdlTypes;

  // annotation?, (simpleContent | complexContent
  // | ((group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute?))
  Element child;
  if ( ( child = DomUtils.getChildElementByName( type, "simpleContent" ) ) != null ) {
    processSimpleContent( child );
  } else if ( ( child = DomUtils.getChildElementByName( type, "complexContent" ) ) != null ) {
    processComplexContent( child );
  } else if ( ( child = DomUtils.getChildElementByName( type, "group" ) ) != null ) {
    processGroup( child );
  } else if ( ( child = DomUtils.getChildElementByName( type, "all" ) ) != null ) {
    processAll( child );
  } else if ( ( child = DomUtils.getChildElementByName( type, "choice" ) ) != null ) {
    processChoice( child );
  } else if ( ( child = DomUtils.getChildElementByName( type, "sequence" ) ) != null ) {
    processSequence( child );
  }

  // release the resolver, we don't need it after the parse is complete
  _wsdlTypes = null;
}
 
Example 7
Source File: WsdlParserUtils.java    From gvnix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Find the first compatible binding name of the root.
 * <p>
 * Compatible binding should be SOAP protocol version 1.1 and 1.2.
 * </p>
 * 
 * @param root Root element of wsdl
 * @return First compatible binding element
 */
private static Element findFirstCompatibleBinding(Element root) {

    Validate.notNull(root, ROOT_ELEMENT_REQUIRED);

    // Find all binding elements
    List<Element> bindings = XmlUtils.findElements(BINDINGS_XPATH, root);
    Validate.notEmpty(bindings, "No valid binding format");

    Element port = findFirstCompatiblePort(root);
    String bindingRef = port.getAttribute(BINDING_ATTRIBUTE);
    StringUtils.isNotEmpty(bindingRef);
    Element binding = getReferencedElement(root, bindings, bindingRef);
    Validate.notNull(binding, "No valid binding reference");

    return binding;
}
 
Example 8
Source File: FlowEncodingVersion.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the 'encoding-version' attribute of the given XML Element as FlowEncodingVersion.
 * The attribute value is expected to be in the format &lt;major version&gt;.&lt;minor version&lt;
 *
 * @param xmlElement the XML Element that contains an 'encoding-version' attribute
 * @return a FlowEncodingVersion that has the major and minor versions specified in the String, or <code>null</code> if the input is null or the input
 *         does not have an 'encoding-version' attribute
 *
 * @throws IllegalArgumentException if the value is not in the format &lt;major version&gt;.&lt;minor version&gt;, if either major version or minor
 *             version is not an integer, or if either the major or minor version is less than 0.
 */
public static FlowEncodingVersion parse(final Element xmlElement) {
    if (xmlElement == null) {
        return null;
    }

    final String version = xmlElement.getAttribute(ENCODING_VERSION_ATTRIBUTE);
    if (version == null) {
        return null;
    }

    return parse(version);
}
 
Example 9
Source File: DigesterBeanDefinitionParser.java    From jasypt with Apache License 2.0 5 votes vote down vote up
@Override
protected void doParse(final Element element, final BeanDefinitionBuilder builder) {

    builder.addConstructorArgValue(new Integer(this.digesterType));
    
    processStringAttribute(element, builder, PARAM_ALGORITHM, "algorithm");
    processBeanAttribute(element, builder, PARAM_CONFIG_BEAN, "config");
    processIntegerAttribute(element, builder, PARAM_ITERATIONS, "iterations");
    processIntegerAttribute(element, builder, PARAM_SALT_SIZE_BYTES, "saltSizeBytes");
    processBeanAttribute(element, builder, PARAM_SALT_GENERATOR_BEAN, "saltGenerator");
    processBeanAttribute(element, builder, PARAM_PROVIDER_BEAN, "provider");
    processStringAttribute(element, builder, PARAM_PROVIDER_NAME, "providerName");
    processBooleanAttribute(element, builder, PARAM_INVERT_POSITION_OF_SALT_IN_MESSAGE_BEFORE_DIGESTING, "invertPositionOfSaltInMessageBeforeDigesting");
    processBooleanAttribute(element, builder, PARAM_INVERT_POSITION_OF_PLAIN_SALT_IN_ENCRYPTION_RESULTS, "invertPositionOfPlainSaltInEncryptionResults");
    processBooleanAttribute(element, builder, PARAM_USE_LENIENT_SALT_SIZE_CHECK, "useLenientSaltSizeCheck");
    processIntegerAttribute(element, builder, PARAM_POOL_SIZE, "poolSize");
    
    processStringAttribute(element, builder, PARAM_STRING_OUTPUT_TYPE, "stringOutputType");
    processBooleanAttribute(element, builder, PARAM_UNICODE_NORMALIZATION_IGNORED, "unicodeNormalizationIgnored");
    processStringAttribute(element, builder, PARAM_PREFIX, "prefix");
    processStringAttribute(element, builder, PARAM_SUFFIX, "suffix");
    
    String scope = element.getAttribute(SCOPE_ATTRIBUTE);
    if (StringUtils.hasLength(scope)) {
        builder.setScope(scope);
    }
    
}
 
Example 10
Source File: SqlXmlParser.java    From sumk with Apache License 2.0 5 votes vote down vote up
public static void parseXml(Map<String, SqlParser> map, DocumentBuilder dbd, String fileName, InputStream in)
		throws Exception {
	Document doc = dbd.parse(in);
	Element root = doc.getDocumentElement();
	String namespace = root.getAttribute("namespace");
	if (namespace != null) {
		namespace = namespace.trim();
		if (namespace.isEmpty()) {
			namespace = null;
		}
	}
	NodeList sqlNodeList = root.getChildNodes();
	if (sqlNodeList == null || sqlNodeList.getLength() == 0) {
		return;
	}
	int len = sqlNodeList.getLength();
	Node tmp;
	for (int i = 0; i < len; i++) {
		tmp = sqlNodeList.item(i);
		if (!Element.class.isInstance(tmp)) {
			continue;
		}
		Element el = (Element) tmp;
		if (!el.hasChildNodes()) {
			continue;
		}
		SqlParser parser = parseSqlNode(el.getChildNodes());
		if (parser != null) {
			if (map.putIfAbsent(name(namespace, el.getAttribute(ID)), parser) != null) {
				SumkException.throwException(435436,
						fileName + "-" + name(namespace, el.getAttribute(ID)) + " is duplicate");
			}
		}
	}
}
 
Example 11
Source File: MULParser.java    From megamek with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parse a kf tag for the given <code>Entity</code>.
 *
 * @param kfTag
 * @param entity
 */
private void parseKF(Element kfTag, Entity entity){
    String value = kfTag.getAttribute(INTEGRITY);
    try {
        int newIntegrity = Integer.parseInt(value);
        ((Jumpship) entity).setKFIntegrity(newIntegrity);
    } catch (Exception e) {
        warning.append("Invalid KF integrity value in KF integrity tag.\n");
    }
}
 
Example 12
Source File: PluginManifestParser.java    From nutch-htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @param rootElement
 * @param pluginDescriptor
 */
private void parseExtension(Element pRootElement,
    PluginDescriptor pPluginDescriptor) {
  NodeList extensions = pRootElement.getElementsByTagName("extension");
  if (extensions != null) {
    for (int i = 0; i < extensions.getLength(); i++) {
      Element oneExtension = (Element) extensions.item(i);
      String pointId = oneExtension.getAttribute("point");

      NodeList extensionImplementations = oneExtension.getChildNodes();
      if (extensionImplementations != null) {
        for (int j = 0; j < extensionImplementations.getLength(); j++) {
          Node node = extensionImplementations.item(j);
          if (!node.getNodeName().equals("implementation")) {
            continue;
          }
          Element oneImplementation = (Element) node;
          String id = oneImplementation.getAttribute(ATTR_ID);
          String extensionClass = oneImplementation.getAttribute(ATTR_CLASS);
          LOG.debug("impl: point=" + pointId + " class=" + extensionClass);
          Extension extension = new Extension(pPluginDescriptor, pointId, id,
              extensionClass, this.conf, this.pluginRepository);
          NodeList parameters = oneImplementation
              .getElementsByTagName("parameter");
          if (parameters != null) {
            for (int k = 0; k < parameters.getLength(); k++) {
              Element param = (Element) parameters.item(k);
              extension.addAttribute(param.getAttribute(ATTR_NAME), param
                  .getAttribute("value"));
            }
          }
          pPluginDescriptor.addExtension(extension);
        }
      }
    }
  }
}
 
Example 13
Source File: CDANarrativeFormat.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
private void processAttributes(Element element, XhtmlNode xn, String... names) {
  for (String n : names) {
    if (element.hasAttribute(n)) {
      String v = element.getAttribute(n);
      switch(n) {
        case "ID":
          xn.attribute("id", v);
          break;
        case "styleCode":
          String style = v;
          switch(v) {
            // according Table 15.2 CSS rendering, The CDAtm book, Keith W. Boone
            case "Bold":
              style = "font-weight: bold";
              break;
            case "Underline":
              style = "text-decoration: underline";
              break;
            case "Italics":
              style = "font-style: italic";
              break;
            case "Emphasis":
              style = "font-weight: small-caps";
              break;
            case "Lrule":
              style = "border-left: 1px";
              break;
            case "Rrule":
              style = "border-right: 1px";
              break;
            case "Toprule":
              style = "border-top: 1px";
              break;
            case "Botrule":
              style = "border-bottom: 1px";
              break;
            case "Arabic":
              style = "list-style-type: decimal";
              break;
            case "LittleRoman":
              style = "list-style-type: lower-roman";
              break;
            case "BigRoman":
              style = "list-style-type: upper-roman";
              break;
            case "LittleAlpha":
              style = "list-style-type: lower-alpha";
              break;
            case "BigAlpha":
              style = "list-style-type: upper-alpha";
              break;
            case "Disc":
              style = "list-style-type: disc";
              break;
            case "Circle":
              style = "list-style-type: circle";
              break;
            case "Square":
              style = "list-style-type: square";
              break;
          }
          xn.attribute("style", style);
          break;
        default:
          xn.attribute(n, v);
      }
    }
  }
}
 
Example 14
Source File: PDF_XMLSerializer.java    From pdfxtk with Apache License 2.0 4 votes vote down vote up
/**
 * Get the path of the PDF file if working with a XML file.
 * 
 * @param xml The XML file
 * @return The path of the PDF document that corresponds to the content of the XML file
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public static String getPDFPath(File xml) throws ParserConfigurationException, SAXException, IOException {
	
	//Initialization stuff
	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	
	Document doc = dBuilder.parse(xml);
	doc.getDocumentElement().normalize();
	
	//Get the root element
	NodeList nList = doc.getElementsByTagName("PDFDocument");
	
	Node nNode = nList.item(0);
		
	Element eElement = (Element) nNode;
	
	return eElement.getAttribute("path");
}
 
Example 15
Source File: SimSettings.java    From EdgeCloudSim with GNU General Public License v3.0 4 votes vote down vote up
private void parseApplicatinosXML(String filePath)
{
	Document doc = null;
	try {	
		File devicesFile = new File(filePath);
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		doc = dBuilder.parse(devicesFile);
		doc.getDocumentElement().normalize();

		NodeList appList = doc.getElementsByTagName("application");
		taskLookUpTable = new double[appList.getLength()][13];
		taskNames = new String[appList.getLength()];
		for (int i = 0; i < appList.getLength(); i++) {
			Node appNode = appList.item(i);

			Element appElement = (Element) appNode;
			isAttribtuePresent(appElement, "name");
			isElementPresent(appElement, "usage_percentage");
			isElementPresent(appElement, "prob_cloud_selection");
			isElementPresent(appElement, "poisson_interarrival");
			isElementPresent(appElement, "active_period");
			isElementPresent(appElement, "idle_period");
			isElementPresent(appElement, "data_upload");
			isElementPresent(appElement, "data_download");
			isElementPresent(appElement, "task_length");
			isElementPresent(appElement, "required_core");
			isElementPresent(appElement, "vm_utilization_on_edge");
			isElementPresent(appElement, "vm_utilization_on_cloud");
			isElementPresent(appElement, "vm_utilization_on_mobile");
			isElementPresent(appElement, "delay_sensitivity");

			String taskName = appElement.getAttribute("name");
			taskNames[i] = taskName;
			
			double usage_percentage = Double.parseDouble(appElement.getElementsByTagName("usage_percentage").item(0).getTextContent());
			double prob_cloud_selection = Double.parseDouble(appElement.getElementsByTagName("prob_cloud_selection").item(0).getTextContent());
			double poisson_interarrival = Double.parseDouble(appElement.getElementsByTagName("poisson_interarrival").item(0).getTextContent());
			double active_period = Double.parseDouble(appElement.getElementsByTagName("active_period").item(0).getTextContent());
			double idle_period = Double.parseDouble(appElement.getElementsByTagName("idle_period").item(0).getTextContent());
			double data_upload = Double.parseDouble(appElement.getElementsByTagName("data_upload").item(0).getTextContent());
			double data_download = Double.parseDouble(appElement.getElementsByTagName("data_download").item(0).getTextContent());
			double task_length = Double.parseDouble(appElement.getElementsByTagName("task_length").item(0).getTextContent());
			double required_core = Double.parseDouble(appElement.getElementsByTagName("required_core").item(0).getTextContent());
			double vm_utilization_on_edge = Double.parseDouble(appElement.getElementsByTagName("vm_utilization_on_edge").item(0).getTextContent());
			double vm_utilization_on_cloud = Double.parseDouble(appElement.getElementsByTagName("vm_utilization_on_cloud").item(0).getTextContent());
			double vm_utilization_on_mobile = Double.parseDouble(appElement.getElementsByTagName("vm_utilization_on_mobile").item(0).getTextContent());
			double delay_sensitivity = Double.parseDouble(appElement.getElementsByTagName("delay_sensitivity").item(0).getTextContent());
			
		    taskLookUpTable[i][0] = usage_percentage; //usage percentage [0-100]
		    taskLookUpTable[i][1] = prob_cloud_selection; //prob. of selecting cloud [0-100]
		    taskLookUpTable[i][2] = poisson_interarrival; //poisson mean (sec)
		    taskLookUpTable[i][3] = active_period; //active period (sec)
		    taskLookUpTable[i][4] = idle_period; //idle period (sec)
		    taskLookUpTable[i][5] = data_upload; //avg data upload (KB)
		    taskLookUpTable[i][6] = data_download; //avg data download (KB)
		    taskLookUpTable[i][7] = task_length; //avg task length (MI)
		    taskLookUpTable[i][8] = required_core; //required # of core
		    taskLookUpTable[i][9] = vm_utilization_on_edge; //vm utilization on edge vm [0-100]
		    taskLookUpTable[i][10] = vm_utilization_on_cloud; //vm utilization on cloud vm [0-100]
		    taskLookUpTable[i][11] = vm_utilization_on_mobile; //vm utilization on mobile vm [0-100]
		    taskLookUpTable[i][12] = delay_sensitivity; //delay_sensitivity [0-1]
		}

	} catch (Exception e) {
		SimLogger.printLine("Edge Devices XML cannot be parsed! Terminating simulation...");
		e.printStackTrace();
		System.exit(0);
	}
}
 
Example 16
Source File: VendorOptionManager.java    From sldeditor with GNU General Public License v3.0 4 votes vote down vote up
/** Populate. */
private void populate() {
    InputStream fXmlFile = VendorOptionManager.class.getResourceAsStream(RESOURCE_FILE);

    if (fXmlFile == null) {
        ConsoleManager.getInstance()
                .error(
                        VendorOptionManager.class,
                        Localisation.getField(ParseXML.class, "ParseXML.failedToFindResource")
                                + RESOURCE_FILE);
        return;
    }

    try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);

        // optional, but recommended
        // read this -
        // http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getFirstChild().getChildNodes();

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                String nodeName = nNode.getNodeName();
                if ((nodeName != null) && (nodeName.compareToIgnoreCase("VendorOption") == 0)) {
                    String className = eElement.getAttribute("class");

                    Class<?> classType = Class.forName(className);

                    VendorOptionTypeInterface veType = getClass(classType);

                    // Add the 'Not Set' option
                    veType.addVersion(new VersionData());

                    addVendorOptionVersion(eElement, veType);
                }
            }
        }
    } catch (Exception e) {
        ConsoleManager.getInstance().exception(this, e);
    }
}
 
Example 17
Source File: TaskHandler.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
protected String getTaskName(final Element element) {
    return element.getAttribute("taskName");
}
 
Example 18
Source File: MetadataListPcsMetFileWriter.java    From oodt with Apache License 2.0 4 votes vote down vote up
@Override
protected Metadata getSciPgeSpecificMetadata(File sciPgeCreatedDataFile,
        Metadata inputMetadata, Object... customArgs)
    throws FileNotFoundException, ParseException, CommonsException, CasMetadataException {
    Metadata metadata = new Metadata();
    for (Object arg : customArgs) {
        Element root = XMLUtils.getDocumentRoot(
                new FileInputStream(new File((String) arg)))
                .getDocumentElement();
        NodeList metadataNodeList = root.getElementsByTagName(METADATA_TAG);
        for (int i = 0; i < metadataNodeList.getLength(); i++) {
            Element metadataElement = (Element) metadataNodeList.item(i);
            String key = metadataElement.getAttribute(KEY_ATTR);
            if (key.equals("")) {
              key = PathUtils.doDynamicReplacement(metadataElement.getAttribute(KEY_GEN_ATTR), inputMetadata);
            }
            String val = metadataElement.getAttribute(VAL_ATTR);
        	if (val.equals("")) {
              val = metadataElement.getTextContent();
            }
            if (val != null && !val.equals("")) {
                if (!metadataElement.getAttribute(ENV_REPLACE_ATTR).toLowerCase().equals("false")) {
                  val = PathUtils.doDynamicReplacement(val, inputMetadata);
                }
                String[] vals;
                if (metadataElement.getAttribute(SPLIT_ATTR).toLowerCase().equals("false")) {
                    vals = new String[] { val };
                } else {
                    String delimiter = metadataElement.getAttribute("delimiter");
                    if (delimiter == null || delimiter.equals("")) {
                      delimiter = ",";
                    }
                    vals = (val + delimiter).split(delimiter);
                }
                metadata.replaceMetadata(key, Arrays.asList(vals));
                inputMetadata.replaceMetadata(key, Arrays.asList(vals));
            } else if (inputMetadata.getMetadata(key) != null
                    && !inputMetadata.getMetadata(key).equals("")) {
                metadata.replaceMetadata(key, inputMetadata
                        .getAllMetadata(key));
            }
        }
    }
    return metadata;
}
 
Example 19
Source File: FreeformProjectGenerator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static void readProperty(Element propertyElement, EditableProperties props) {
    String key = propertyElement.getAttribute("name"); // NOI18N
    String value = XMLUtil.findText(propertyElement);
    props.setProperty(key, value);
}
 
Example 20
Source File: GenericDelegator.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
@Override
public GenericValue makeValue(Element element) {
    if (element == null) {
        return null;
    }
    String entityName = element.getTagName();

    // if a dash or colon is in the tag name, grab what is after it
    if (entityName.indexOf('-') > 0) {
        entityName = entityName.substring(entityName.indexOf('-') + 1);
    }
    if (entityName.indexOf(':') > 0) {
        entityName = entityName.substring(entityName.indexOf(':') + 1);
    }
    GenericValue value = this.makeValue(entityName);

    ModelEntity modelEntity = value.getModelEntity();

    Iterator<ModelField> modelFields = modelEntity.getFieldsIterator();

    while (modelFields.hasNext()) {
        ModelField modelField = modelFields.next();
        String name = modelField.getName();
        String attr = element.getAttribute(name);

        if (UtilValidate.isNotEmpty(attr)) {
            // GenericEntity.makeXmlElement() sets null values to GenericEntity.NULL_FIELD.toString(), so look for
            //     that and treat it as null
            if (GenericEntity.NULL_FIELD.toString().equals(attr)) {
                value.set(name, null);
            } else {
                value.setString(name, attr);
            }
        } else {
            // if no attribute try a subelement
            Element subElement = UtilXml.firstChildElement(element, name);

            if (subElement != null) {
                value.setString(name, UtilXml.elementValue(subElement));
            }
        }
    }

    return value;
}