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

The following examples show how to use org.w3c.dom.Element#getAttributeNode() . 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: FullBackupContentDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@NonNull
private static String validatePath(@NonNull XmlContext context, @NonNull Element element) {
    Attr pathNode = element.getAttributeNode(ATTR_PATH);
    if (pathNode == null) {
        return "";
    }
    String value = pathNode.getValue();
    if (value.contains("//")) {
        context.report(ISSUE, element, context.getValueLocation(pathNode),
                "Paths are not allowed to contain `//`");
    } else if (value.contains("..")) {
        context.report(ISSUE, element, context.getValueLocation(pathNode),
                "Paths are not allowed to contain `..`");
    } else if (value.contains("/")) {
        String domain = element.getAttribute(ATTR_DOMAIN);
        if (DOMAIN_SHARED_PREF.equals(domain) || DOMAIN_DATABASE.equals(domain)) {
            context.report(ISSUE, element, context.getValueLocation(pathNode),
                    String.format("Subdirectories are not allowed for domain `%1$s`",
                            domain));
        }
    }
    return value;
}
 
Example 2
Source File: XmlCombiner.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
private static CombineSelf getCombineSelf(@Nullable Element element) {
	CombineSelf combine = null;
	if (element == null) {
		return null;
	}
	Attr combineAttribute = element.getAttributeNode(CombineSelf.ATTRIBUTE_NAME);
	if (combineAttribute != null) {
		try {
			combine = CombineSelf.valueOf(combineAttribute.getValue().toUpperCase());
		} catch (IllegalArgumentException e) {
			throw new RuntimeException("The attribute 'combine' of element '"
					+ element.getTagName() + "' has invalid value '"
					+ combineAttribute.getValue(), e);
		}
	}
	return combine;
}
 
Example 3
Source File: RSSConfigReader.java    From oodt with Apache License 2.0 6 votes vote down vote up
protected static void readTags(Element root, RSSConfig conf) {
  NodeList tagList = root.getElementsByTagName(TAG_TAG);
  if (tagList != null && tagList.getLength() > 0) {
    for (int i = 0; i < tagList.getLength(); i++) {
      Element tagElem = (Element) tagList.item(i);
      RSSTag tag = new RSSTag();
      tag.setName(tagElem.getAttribute(TAG_ATTR_NAME));

      // check to see if it has a source
      if (tagElem.getAttributeNode(TAG_ATTR_SOURCE) != null) {
        tag.setSource(tagElem.getAttribute(TAG_ATTR_SOURCE));
      }

      readAttrs(tagElem, tag);
      conf.getTags().add(tag);
    }
  }
}
 
Example 4
Source File: ElementMatcherSafeCI.java    From jStyleParser with GNU Lesser General Public License v3.0 5 votes vote down vote up
public boolean matchesAttribute(Element e, String name, String value, Selector.Operator o) 
{
    final Node attributeNode = e.getAttributeNode(name);
    if (attributeNode != null && o != null)
    {
        String attributeValue = attributeNode.getNodeValue();
        
        switch(o) {
            case EQUALS:
                return attributeValue.equals(value);
            case INCLUDES:
                if (value.isEmpty() || containsWhitespace(value))
                    return false;
                else
                {
                    attributeValue = " " + attributeValue + " ";
                    return attributeValue.matches(".* " + value + " .*");
                }
            case DASHMATCH:
                return attributeValue.matches("^" + value + "(-.*|$)");
            case CONTAINS:
                return !value.isEmpty() && attributeValue.matches(".*" + value + ".*");
            case STARTSWITH:
                return !value.isEmpty() && attributeValue.matches("^" + value + ".*");
            case ENDSWITH:
                return !value.isEmpty() && attributeValue.matches(".*" + value + "$");
            default:
                return true;
        }
    }
    else
        return false;
}
 
Example 5
Source File: ManifestDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private static void checkDocumentElement(XmlContext context, Element element) {
    Attr codeNode = element.getAttributeNodeNS(ANDROID_URI, ATTR_VERSION_CODE);
    if (codeNode != null && codeNode.getValue().startsWith(PREFIX_RESOURCE_REF)
            && context.isEnabled(ILLEGAL_REFERENCE)) {
        context.report(ILLEGAL_REFERENCE, element, context.getLocation(codeNode),
                "The `android:versionCode` cannot be a resource url, it must be "
                        + "a literal integer");
    } else if (codeNode == null && context.isEnabled(SET_VERSION)
            // Not required in Gradle projects; typically defined in build.gradle instead
            // and inserted at build time
            && !context.getMainProject().isGradleProject()) {
        context.report(SET_VERSION, element, context.getLocation(element),
                "Should set `android:versionCode` to specify the application version");
    }
    Attr nameNode = element.getAttributeNodeNS(ANDROID_URI, ATTR_VERSION_NAME);
    if (nameNode == null && context.isEnabled(SET_VERSION)
            // Not required in Gradle projects; typically defined in build.gradle instead
            // and inserted at build time
            && !context.getMainProject().isGradleProject()) {
        context.report(SET_VERSION, element, context.getLocation(element),
                "Should set `android:versionName` to specify the application version");
    }

    checkOverride(context, element, ATTR_VERSION_CODE);
    checkOverride(context, element, ATTR_VERSION_NAME);

    Attr pkgNode = element.getAttributeNode(ATTR_PACKAGE);
    if (pkgNode != null) {
        String pkg = pkgNode.getValue();
        if (pkg.contains("${") && context.getMainProject().isGradleProject()) {
            context.report(GRADLE_OVERRIDES, pkgNode, context.getLocation(pkgNode),
                    "Cannot use placeholder for the package in the manifest; "
                            + "set `applicationId` in `build.gradle` instead");
        }
    }
}
 
Example 6
Source File: XML.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Attr requireAttr(Element parent, String name) throws ParseException {
    final Attr attr = parent.getAttributeNode(name);
    if(attr == null) {
        throw new MissingException("attribute", name);
    }
    return attr;
}
 
Example 7
Source File: ConnectionPropertiesPatcher.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
private static Attr getConnectionProperties(Document doc) throws Exception {
	XPath xPath = XPathFactory.newInstance().newXPath();
	XPathExpression expr = xPath.compile("/persistence/persistence-unit/properties/property[@name='openjpa.ConnectionProperties']");

	Element element = (Element)expr.evaluate(doc, XPathConstants.NODE);
	return element.getAttributeNode("value");
}
 
Example 8
Source File: ElementMatcherSimpleCI.java    From jStyleParser with GNU Lesser General Public License v3.0 5 votes vote down vote up
public boolean matchesAttribute(final Element e, final String name, final String value, final Selector.Operator o) 
{
    final Node attributeNode = e.getAttributeNode(name);
    if (attributeNode != null && o != null)
    {
        String attributeValue = attributeNode.getNodeValue();
        
        switch(o) {
            case EQUALS:
                return attributeValue.equals(value);
            case INCLUDES:
                if (value.isEmpty() || containsWhitespace(value))
                    return false;
                else
                {
                    attributeValue = " " + attributeValue + " ";
                    return attributeValue.matches(".* " + value + " .*");
                }
            case DASHMATCH:
                return attributeValue.matches("^" + value + "(-.*|$)");
            case CONTAINS:
                return !value.isEmpty() && attributeValue.matches(".*" + value + ".*");
            case STARTSWITH:
                return !value.isEmpty() && attributeValue.matches("^" + value + ".*");
            case ENDSWITH:
                return !value.isEmpty() && attributeValue.matches(".*" + value + "$");
            default:
                return true;
        }
    }
    else
        return false;
}
 
Example 9
Source File: DOMHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Support for getParentOfNode; walks a DOM tree until it finds
 * the Element which owns the Attr. This is hugely expensive, and
 * if at all possible you should use the DOM Level 2 Attr.ownerElement()
 * method instead.
 *  <p>
 * The DOM Level 1 developers expected that folks would keep track
 * of the last Element they'd seen and could recover the info from
 * that source. Obviously that doesn't work very well if the only
 * information you've been presented with is the Attr. The DOM Level 2
 * getOwnerElement() method fixes that, but only for Level 2 and
 * later DOMs.
 *
 * @param elem Element whose subtree is to be searched for this Attr
 * @param attr Attr whose owner is to be located.
 *
 * @return the first Element whose attribute list includes the provided
 * attr. In modern DOMs, this will also be the only such Element. (Early
 * DOMs had some hope that Attrs might be sharable, but this idea has
 * been abandoned.)
 */
private static Node locateAttrParent(Element elem, Node attr)
{

  Node parent = null;

      // This should only be called for Level 1 DOMs, so we don't have to
      // worry about namespace issues. In later levels, it's possible
      // for a DOM to have two Attrs with the same NodeName but
      // different namespaces, and we'd need to get getAttributeNodeNS...
      // but later levels also have Attr.getOwnerElement.
      Attr check=elem.getAttributeNode(attr.getNodeName());
      if(check==attr)
              parent = elem;

  if (null == parent)
  {
    for (Node node = elem.getFirstChild(); null != node;
            node = node.getNextSibling())
    {
      if (Node.ELEMENT_NODE == node.getNodeType())
      {
        parent = locateAttrParent((Element) node, attr);

        if (null != parent)
          break;
      }
    }
  }

  return parent;
}
 
Example 10
Source File: DOMUtils.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
public static String getAttribute(Element element, QName attName) {
    Attr attr;
    if (StringUtils.isEmpty(attName.getNamespaceURI())) {
        attr = element.getAttributeNode(attName.getLocalPart());
    } else {
        attr = element.getAttributeNodeNS(attName.getNamespaceURI(), attName.getLocalPart());
    }
    return attr == null ? null : attr.getValue();
}
 
Example 11
Source File: W3CNamespaceContext.java    From cxf with Apache License 2.0 5 votes vote down vote up
private String getNamespaceURI(Element e, String name) {
    Attr attr = e.getAttributeNode(name);
    if (attr == null) {
        Node n = e.getParentNode();
        if (n instanceof Element && n != e) {
            return getNamespaceURI((Element)n, name);
        }
    } else {
        return attr.getValue();
    }

    return null;
}
 
Example 12
Source File: AttrTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testGetSpecified2() throws Exception {

    Document document = createDOM("Attr2.xml");
    Element elemNode = (Element) document.getElementsByTagName("Name").item(0);
    Attr attr = elemNode.getAttributeNode("type");

    assertFalse(attr.getSpecified());
}
 
Example 13
Source File: XmlUtil.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public static String getAttributeOrNull(Element e, String name) {
    Attr a = e.getAttributeNode(name);
    if (a == null)
        return null;
    return a.getValue();
}
 
Example 14
Source File: AbstractBindingBuilder.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Identifies the portions of the message to be signed/encrypted.
 * 
 * @param encryptionModifier
 *            indicates the scope of the crypto operation over matched
 *            elements. Either "Content" or "Element".
 * @param xpaths
 *            any XPath expressions to sign/encrypt matches
 * @param namespaces
 *            namespace prefix to namespace mappings for XPath expressions
 *            in {@code xpaths}
 * @param found
 *            a list of elements that have previously been tagged for
 *            signing/encryption. Populated with additional matches found by
 *            this method and used to prevent including the same element
 *            twice under the same operation.
 * @param forceId 
 *         force adding a wsu:Id onto the elements.  Recommended for signatures.
 * @return a configured list of {@code WSEncryptionPart}s suitable for
 *         processing by WSS4J
 * @throws XPathExpressionException
 *             if a provided XPath is invalid
 * @throws SOAPException
 *             if there is an error extracting SOAP content from the SAAJ
 *             model
 */
protected List<WSEncryptionPart> getElements(String encryptionModifier,
        List<String> xpaths, Map<String, String> namespaces,
        List<Element> found,
        boolean forceId) throws XPathExpressionException, SOAPException {
    
    List<WSEncryptionPart> result = new ArrayList<WSEncryptionPart>();
    
    if (xpaths != null && !xpaths.isEmpty()) {
        XPathFactory factory = XPathFactory.newInstance();
        for (String expression : xpaths) {
            XPath xpath = factory.newXPath();
            if (namespaces != null) {
                xpath.setNamespaceContext(new MapNamespaceContext(namespaces));
            }
           
            NodeList list = (NodeList)xpath.evaluate(expression, saaj.getSOAPPart().getEnvelope(),
                                           XPathConstants.NODESET);
            for (int x = 0; x < list.getLength(); x++) {
                Element el = (Element)list.item(x);
                
                if (!found.contains(el)) {
                    String id = null;
                    if (forceId) {
                        id = this.addWsuIdToElement(el);
                    } else {
                        //not forcing an ID on this.  Use one if there is one 
                        //there already, but don't force one
                        Attr idAttr = el.getAttributeNode("Id");
                        if (idAttr == null) {
                            //then try the wsu:Id value
                            idAttr = el.getAttributeNodeNS(PolicyConstants.WSU_NAMESPACE_URI, "Id");
                        }
                        if (idAttr != null) {
                            id = idAttr.getValue();
                        }
                    }
                    WSEncryptionPart part = 
                        new WSEncryptionPart(id, encryptionModifier);
                    part.setElement(el);
                    part.setXpath(expression);
                    
                    result.add(part);
                }
            }
        }
    }
    
    return result;
}
 
Example 15
Source File: DOMUtil.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public static Attr getAttr(Element elem, String name) {
    return elem.getAttributeNode(name);
}
 
Example 16
Source File: DOMUtil.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
final static String getAttribute(Element e,String attName) {
    if(e.getAttributeNode(attName)==null)   return null;
    return e.getAttribute(attName);
}
 
Example 17
Source File: XmlUtil.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static String getAttributeOrNull(Element e, String name) {
    Attr a = e.getAttributeNode(name);
    if (a == null)
        return null;
    return a.getValue();
}
 
Example 18
Source File: ClusteringCacheManagerServiceConfigurationParser.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
private ClusteringCacheManagerServiceConfigurationParser.ServerSideConfig processServerSideConfig(Element serverSideConfigElement) {
  ClusteringCacheManagerServiceConfigurationParser.ServerSideConfig serverSideConfig = new ClusteringCacheManagerServiceConfigurationParser.ServerSideConfig();

  String autoCreateAttr = serverSideConfigElement.getAttribute(AUTO_CREATE_ATTRIBUTE_NAME);
  String clientModeAttr = serverSideConfigElement.getAttribute(CLIENT_MODE_ATTRIBUTE_NAME);
  if (clientModeAttr.isEmpty()) {
    if (!autoCreateAttr.isEmpty()) {
      serverSideConfig.clientMode = Boolean.parseBoolean(autoCreateAttr) ? ClientMode.AUTO_CREATE : ClientMode.EXPECTING;
    }
  } else if (autoCreateAttr.isEmpty()) {
    serverSideConfig.clientMode = ClientMode.valueOf(clientModeAttr.toUpperCase(Locale.ROOT).replace('-', '_'));
  } else {
    throw new XmlConfigurationException("Cannot define both '" + AUTO_CREATE_ATTRIBUTE_NAME + "' and '" + CLIENT_MODE_ATTRIBUTE_NAME + "' attributes");
  }

  final NodeList serverSideNodes = serverSideConfigElement.getChildNodes();
  for (int i = 0; i < serverSideNodes.getLength(); i++) {
    final Node item = serverSideNodes.item(i);
    if (Node.ELEMENT_NODE == item.getNodeType()) {
      String nodeLocalName = item.getLocalName();
      if ("default-resource".equals(nodeLocalName)) {
        serverSideConfig.defaultServerResource = ((Element)item).getAttribute("from");

      } else if ("shared-pool".equals(nodeLocalName)) {
        Element sharedPoolElement = (Element)item;
        String poolName = sharedPoolElement.getAttribute("name");     // required
        Attr fromAttr = sharedPoolElement.getAttributeNode("from");   // optional
        String fromResource = (fromAttr == null ? null : fromAttr.getValue());
        Attr unitAttr = sharedPoolElement.getAttributeNode("unit");   // optional - default 'B'
        String unit = (unitAttr == null ? "B" : unitAttr.getValue());
        MemoryUnit memoryUnit = MemoryUnit.valueOf(unit.toUpperCase(Locale.ENGLISH));

        String quantityValue = sharedPoolElement.getFirstChild().getNodeValue();
        long quantity;
        try {
          quantity = Long.parseLong(quantityValue);
        } catch (NumberFormatException e) {
          throw new XmlConfigurationException("Magnitude of value specified for <shared-pool name=\""
                                              + poolName + "\"> is too large");
        }

        ServerSideConfiguration.Pool poolDefinition;
        if (fromResource == null) {
          poolDefinition = new ServerSideConfiguration.Pool(memoryUnit.toBytes(quantity));
        } else {
          poolDefinition = new ServerSideConfiguration.Pool(memoryUnit.toBytes(quantity), fromResource);
        }

        if (serverSideConfig.pools.put(poolName, poolDefinition) != null) {
          throw new XmlConfigurationException("Duplicate definition for <shared-pool name=\"" + poolName + "\">");
        }
      }
    }
  }
  return serverSideConfig;
}
 
Example 19
Source File: DOMUtil.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static Attr getAttr(Element elem, String name) {
    return elem.getAttributeNode(name);
}
 
Example 20
Source File: DOMUtil.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
final static String getAttribute(Element e,String attName) {
    if(e.getAttributeNode(attName)==null)   return null;
    return e.getAttribute(attName);
}