Java Code Examples for org.w3c.dom.NamedNodeMap#getNamedItem()

The following examples show how to use org.w3c.dom.NamedNodeMap#getNamedItem() . 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: ResXmlPatcher.java    From ratel with Apache License 2.0 6 votes vote down vote up
/**
 * Replaces package value with passed packageOriginal string
 *
 * @param file File for AndroidManifest.xml
 * @param packageOriginal Package name to replace
 * @throws AndrolibException
 */
public static void renameManifestPackage(File file, String packageOriginal) throws AndrolibException {
    try {
        Document doc = loadDocument(file);

        // Get the manifest line
        Node manifest = doc.getFirstChild();

        // update package attribute
        NamedNodeMap attr = manifest.getAttributes();
        Node nodeAttr = attr.getNamedItem("package");
        nodeAttr.setNodeValue(packageOriginal);
        saveDocument(file, doc);

    } catch (SAXException | ParserConfigurationException | IOException | TransformerException ignored) {
    }
}
 
Example 2
Source File: TestingUtilitiesX.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private static String compareAttributes(String path, NamedNodeMap src, NamedNodeMap tgt) {
  for (int i = 0; i < src.getLength(); i++) {
  
    Node sa = src.item(i);
    String sn = sa.getNodeName();
    if (! (sn.equals("xmlns") || sn.startsWith("xmlns:"))) {
      Node ta = tgt.getNamedItem(sn);
      if (ta == null) 
        return "Attributes differ at "+path+": missing attribute "+sn;
      if (!normalise(sa.getTextContent()).equals(normalise(ta.getTextContent()))) {
        byte[] b1 = unBase64(sa.getTextContent());
        byte[] b2 = unBase64(ta.getTextContent());
        if (!sameBytes(b1, b2))
          return "Attributes differ at "+path+": value "+normalise(sa.getTextContent()) +"/"+ normalise(ta.getTextContent());
      }
    }
  }
  return null;
}
 
Example 3
Source File: RecentFileStorage.java    From FancyBing with GNU General Public License v3.0 6 votes vote down vote up
public static ArrayList<String> getAllMimeType(String mimeType)
{
    updateFromFile();
    ArrayList<String> result = new ArrayList<String>();
    NodeList nodeList = s_document.getElementsByTagName("RecentItem");
    for (int i = 0; i < nodeList.getLength(); ++i)
    {
        Node element = nodeList.item(i);
        NamedNodeMap attributes = element.getAttributes();
        Node nodeMimeType = attributes.getNamedItem("Mime-Type");
        if (nodeMimeType == null)
            continue;
        String value = nodeMimeType.getNodeValue();
        if (! value.equals(mimeType))
            continue;
        result.add(value);
    }
    return result;
}
 
Example 4
Source File: JPEGMetadata.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private void mergeStandardTextNode(Node node)
    throws IIOInvalidTreeException {
    // Convert to comments.  For the moment ignore the encoding issue.
    // Ignore keywords, language, and encoding (for the moment).
    // If compression tag is present, use only entries with "none".
    NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        NamedNodeMap attrs = child.getAttributes();
        Node comp = attrs.getNamedItem("compression");
        boolean copyIt = true;
        if (comp != null) {
            String compString = comp.getNodeValue();
            if (!compString.equals("none")) {
                copyIt = false;
            }
        }
        if (copyIt) {
            String value = attrs.getNamedItem("value").getNodeValue();
            COMMarkerSegment com = new COMMarkerSegment(value);
            insertCOMMarkerSegment(com);
        }
    }
}
 
Example 5
Source File: DDProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * @return version of deployment descriptor. 
 */
private void extractVersion () {
    // This is the default version
    version = Application.VERSION_7;
    
    // first check the doc type to see if there is one
    DocumentType dt = document.getDoctype();

    if(dt == null) {
        //check application node version attribute
        NodeList nl = document.getElementsByTagName("application");//NOI18N
        if(nl != null && nl.getLength() > 0) {
            Node appNode = nl.item(0);
            NamedNodeMap attrs = appNode.getAttributes();
            Node vNode = attrs.getNamedItem("version");//NOI18N
            if(vNode != null) {
                String versionValue = vNode.getNodeValue();
                if (Application.VERSION_1_4.equals(versionValue)) {
                    version = Application.VERSION_1_4;
                } else if (Application.VERSION_5.equals(versionValue)) {
                    version = Application.VERSION_5;
                } else if (Application.VERSION_6.equals(versionValue)) {
                    version = Application.VERSION_6;
                } else {
                    version = Application.VERSION_7; //default
                }
            }
        }
    }
}
 
Example 6
Source File: EntityReferenceImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the absolute base URI of this node or null if the implementation
 * wasn't able to obtain an absolute URI. Note: If the URI is malformed, a
 * null is returned.
 *
 * @return The absolute base URI of this node or null.
 * @since DOM Level 3
 */
public String getBaseURI() {
    if (needsSyncData()) {
        synchronizeData();
    }
    if (baseURI == null) {
        DocumentType doctype;
        NamedNodeMap entities;
        EntityImpl entDef;
        if (null != (doctype = getOwnerDocument().getDoctype()) &&
            null != (entities = doctype.getEntities())) {

            entDef = (EntityImpl)entities.getNamedItem(getNodeName());
            if (entDef !=null) {
                return entDef.getBaseURI();
            }
        }
    } else if (baseURI != null && baseURI.length() != 0 ) {// attribute value is always empty string
        try {
            return new URI(baseURI).toString();
        }
        catch (com.sun.org.apache.xerces.internal.util.URI.MalformedURIException e){
            // REVISIT: what should happen in this case?
            return null;
        }
    }
    return baseURI;
}
 
Example 7
Source File: XMLUtil.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static Map<String, String> mapAttributeNodes(NodeList nodes, String nodeName, String nodeKeyName, String nodeValueName) throws OpenAS2Exception {
    Map<String, String> attributes = new HashMap<String, String>();
    int nodeCount = nodes.getLength();
    Node attrNode;
    NamedNodeMap nodeAttributes;
    Node tmpNode;
    String attrName;
    String attrValue;

    for (int i = 0; i < nodeCount; i++) {
        attrNode = nodes.item(i);

        if (attrNode.getNodeName().equals(nodeName)) {
            nodeAttributes = attrNode.getAttributes();
            tmpNode = nodeAttributes.getNamedItem(nodeKeyName);

            if (tmpNode == null) {
                throw new OpenAS2Exception(attrNode.toString() + " does not have key attribute: " + nodeKeyName);
            }

            attrName = tmpNode.getNodeValue();
            tmpNode = nodeAttributes.getNamedItem(nodeValueName);

            if (tmpNode == null) {
                throw new OpenAS2Exception(attrNode.toString() + " does not have value attribute: " + nodeValueName);
            }

            attrValue = tmpNode.getNodeValue();
            attributes.put(attrName, attrValue);
        }
    }

    return attributes;
}
 
Example 8
Source File: XmlAuthorization.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/** Get the attribute value for a given attribute name of a node. */
private static String getAttributeValue(Node node, String attrName) {

  NamedNodeMap attrMap = node.getAttributes();
  Node attrNode;
  if (attrMap != null && (attrNode = attrMap.getNamedItem(attrName)) != null) {
    return ((Attr)attrNode).getValue();
  }
  return EMPTY_VALUE;
}
 
Example 9
Source File: PXDOMStyleAdapter.java    From pixate-freestyle-android with Apache License 2.0 5 votes vote down vote up
@Override
public String getAttributeValue(Object styleable, String attribute) {
    Node node = (Node) styleable;
    NamedNodeMap attributes = node.getAttributes();
    String result = null;
    if (attributes != null) {
        Node idAttr = attributes.getNamedItem(attribute);
        if (idAttr != null) {
            result = idAttr.getNodeValue();
        }
    }
    return result;
}
 
Example 10
Source File: EntityReferenceImpl.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * Returns the absolute base URI of this node or null if the implementation
 * wasn't able to obtain an absolute URI. Note: If the URI is malformed, a
 * null is returned.
 *
 * @return The absolute base URI of this node or null.
 * @since DOM Level 3
 */
public String getBaseURI() {
    if (needsSyncData()) {
        synchronizeData();
    }
    if (baseURI == null) {
        DocumentType doctype;
        NamedNodeMap entities;
        EntityImpl entDef;
        if (null != (doctype = getOwnerDocument().getDoctype()) &&
            null != (entities = doctype.getEntities())) {

            entDef = (EntityImpl)entities.getNamedItem(getNodeName());
            if (entDef !=null) {
                return entDef.getBaseURI();
            }
        }
    } else if (baseURI != null && baseURI.length() != 0 ) {// attribute value is always empty string
        try {
            return new URI(baseURI).toString();
        }
        catch (com.sun.org.apache.xerces.internal.util.URI.MalformedURIException e){
            // REVISIT: what should happen in this case?
            return null;
        }
    }
    return baseURI;
}
 
Example 11
Source File: DOM4Parser.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected String pull(Node n, String name) {
  NamedNodeMap map = n.getAttributes();
  Node attr = map.getNamedItem(name);
  if (attr == null)
    return null;
  return attr.getNodeValue();
}
 
Example 12
Source File: ActivitiWorkflowEngine.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String getProcessKey(InputStream workflowDefinition) throws Exception
{
    try 
    {
        InputSource inputSource = new InputSource(workflowDefinition);
        DOMParser parser = new DOMParser();
        parser.parse(inputSource);
        Document document = parser.getDocument();
        NodeList elemnts = document.getElementsByTagName("process");
        if (elemnts.getLength() < 1)
        {
            throw new IllegalArgumentException("The input stream does not contain a process definition!");
        }
        NamedNodeMap attributes = elemnts.item(0).getAttributes();
        Node idAttrib = attributes.getNamedItem("id");
        if (idAttrib == null)
        {
            throw new IllegalAccessError("The process definition does not have an id!");
        }
        
        if(activitiUtil.isMultiTenantWorkflowDeploymentEnabled())
        {
            // Workflow-definition is deployed tenant-aware, key should be altered
            return factory.getDomainProcessKey(idAttrib.getNodeValue());
        }
        else
        {
            return idAttrib.getNodeValue();
        }
    }
    finally
    {
        workflowDefinition.close();
    }
}
 
Example 13
Source File: Wallet.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
private VersionNumber getVersionNumber(Document doc, boolean legacy) {
	VersionNumber secretXmlVersion = null;
	try {
		NodeList rootNode = doc.getElementsByTagName(legacy ? CACHE_FILE_NAME_LEGACY : CACHE_FILE_NAME_CREDENTIALS);
		NamedNodeMap attributes = rootNode.item(0).getAttributes();
		Node versionValue = attributes.getNamedItem(VERSION_ATTRIBUTE);
		secretXmlVersion = new VersionNumber(versionValue.getNodeValue());
	} catch (Exception e) {
		// attribute missing
	}
	return secretXmlVersion;
}
 
Example 14
Source File: Tag.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public Attr getAttributeNode(String name) {
    NamedNodeMap map = getAttributes();
    Node node = map.getNamedItem(name);
    return (Attr) node;
}
 
Example 15
Source File: JunitXmlReportWriter.java    From ossindex-gradle-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void modifyElementAttribute(Document doc, String tagName, Integer index, String attrName, String value) {
  Node target = doc.getElementsByTagName(tagName).item(index);
  NamedNodeMap attr = target.getAttributes();
  Node nodeAttr = attr.getNamedItem(attrName);
  nodeAttr.setTextContent(value);
}
 
Example 16
Source File: DomainEditor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private boolean createSampleDatasource(Document domainDoc){
    NodeList resourcesNodeList = domainDoc.getElementsByTagName("resources");
    NodeList serverNodeList = domainDoc.getElementsByTagName("server");
    if (resourcesNodeList == null || resourcesNodeList.getLength() == 0 ||
            serverNodeList == null || serverNodeList.getLength() == 0) {
        return true;
    }
    Node resourcesNode = resourcesNodeList.item(0);

    Map<String,Node> cpMap = getConnPoolsNodeMap(domainDoc);
    if(! cpMap.containsKey(SAMPLE_CONNPOOL)){
        if (cpMap.isEmpty()) {
            LOGGER.log(Level.INFO,
                    "Cannot create sample datasource {0}",
                    SAMPLE_DATASOURCE);
            return false;
        }
        Node oldNode = cpMap.values().iterator().next();
        Node cpNode = oldNode.cloneNode(false);
        NamedNodeMap cpAttrMap = cpNode.getAttributes();
        if(cpAttrMap.getNamedItem(CONST_NAME) != null) {
            cpAttrMap.getNamedItem(CONST_NAME).setNodeValue(SAMPLE_CONNPOOL);
        }
        if(cpAttrMap.getNamedItem(CONST_DS_CLASS) != null) {
            cpAttrMap.getNamedItem(CONST_DS_CLASS).setNodeValue("org.apache.derby.jdbc.ClientDataSource"); //N0I18N
        }
        if(cpAttrMap.getNamedItem(CONST_RES_TYPE) != null) {
            cpAttrMap.getNamedItem(CONST_RES_TYPE).setNodeValue("javax.sql.DataSource"); //N0I18N
        }
        HashMap<String, String> poolProps = new HashMap<String, String>();
        poolProps.put(CONST_SERVER_NAME, "localhost"); //N0I18N
        poolProps.put(CONST_PASSWORD, "app"); //N0I18N
        poolProps.put(CONST_USER, "app"); //N0I18N
        poolProps.put(CONST_DATABASE_NAME, "sample"); //N0I18N
        poolProps.put(CONST_PORT_NUMBER, "1527"); //N0I18N
        poolProps.put(CONST_URL, "jdbc:derby://localhost:1527/sample"); //N0I18N

        Object[] propNames = poolProps.keySet().toArray();
        for(int i=0; i<propNames.length; i++){
            String keyName = (String)propNames[i];
            Element propElement = domainDoc.createElement(CONST_PROP); //N0I18N
            propElement.setAttribute(CONST_NAME, keyName);
            propElement.setAttribute(CONST_VALUE, poolProps.get(keyName)); //N0I18N
            cpNode.appendChild(propElement);
        }
        resourcesNode.appendChild(cpNode);
    }

    Element dsElement = domainDoc.createElement(CONST_JDBC); //N0I18N
    dsElement.setAttribute(CONST_JNDINAME, SAMPLE_DATASOURCE); //N0I18N
    dsElement.setAttribute(CONST_POOLNAME, SAMPLE_CONNPOOL); //N0I18N
    dsElement.setAttribute(CONST_OBJTYPE, "user"); //N0I18N
    dsElement.setAttribute(CONST_ENABLED, "true"); //N0I18N

    // Insert the ds __Sample as a first child of "resources" element
    if (resourcesNode.getFirstChild() != null)
        resourcesNode.insertBefore(dsElement, resourcesNode.getFirstChild());
    else
        resourcesNode.appendChild(dsElement);

    //<resource-ref enabled="true" ref="jdbc/__default"/>
    Element dsResRefElement = domainDoc.createElement("resource-ref"); //N0I18N
    dsResRefElement.setAttribute("ref", SAMPLE_DATASOURCE); //N0I18N
    dsResRefElement.setAttribute(CONST_ENABLED, "true"); //N0I18N
    // Insert the ds reference __Sample as last child of "server" element
    Node serverNode = serverNodeList.item(0);
    if (serverNode.getLastChild() != null)
        serverNode.insertBefore(dsResRefElement, serverNode.getLastChild());
    else
        serverNode.appendChild(dsResRefElement);

    return saveDomainScriptFile(domainDoc, getDomainLocation());
}
 
Example 17
Source File: Result.java    From balana with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new instance of a <code>Result</code> based on the given
 * DOM root node. A <code>ParsingException</code> is thrown if the DOM
 * root doesn't represent a valid ResultType.
 *
 * @param root the DOM root of a ResultType
 *
 * @return a new <code>Result</code>
 *
 * @throws ParsingException if the node is invalid
 */
public static AbstractResult getInstance(Node root) throws ParsingException {
    
    int decision = -1;
    Status status = null;
    String resource = null;
    List<ObligationResult> obligations = null;

    NamedNodeMap attrs = root.getAttributes();
    Node resourceAttr = attrs.getNamedItem("ResourceId");
    if (resourceAttr != null){
        resource = resourceAttr.getNodeValue();
    }
    NodeList nodes = root.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        String name = DOMHelper.getLocalName(node);

        if (name.equals("Decision")) {
            String type = node.getFirstChild().getNodeValue();
            for (int j = 0; j < DECISIONS.length; j++) {
                if (DECISIONS[j].equals(type)) {
                    decision = j;
                    break;
                }
            }

            if (decision == -1)
                throw new ParsingException("Unknown Decision: " + type);
        } else if (name.equals("Status")) {
            if(status == null){
                status = Status.getInstance(node);
            } else {
                throw new ParsingException("More than one StatusType defined");      
            }
        } else if (name.equals("Obligations")) {
            if(obligations == null){
                obligations = parseObligations(node);
            } else {
                throw new ParsingException("More than one ObligationsType defined");    
            }
        }
    }

    return new Result(decision, status, obligations, resource);
}
 
Example 18
Source File: AdductsParameter.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void loadValueFromXML(final Element xmlElement) {

  // Get the XML tag.
  final NodeList items = xmlElement.getElementsByTagName(ADDUCTS_TAG);
  final int length = items.getLength();

  // Start with current choices and empty selections.
  final ArrayList<AdductType> newChoices = new ArrayList<AdductType>(Arrays.asList(getChoices()));
  final ArrayList<AdductType> selections = new ArrayList<AdductType>(length);

  // Process each adduct.
  for (int i = 0; i < length; i++) {

    final Node item = items.item(i);

    // Get attributes.
    final NamedNodeMap attributes = item.getAttributes();
    final Node nameNode = attributes.getNamedItem(NAME_ATTRIBUTE);
    final Node massNode = attributes.getNamedItem(MASS_ATTRIBUTE);
    final Node selectedNode = attributes.getNamedItem(SELECTED_ATTRIBUTE);

    // Valid attributes?
    if (nameNode != null && massNode != null) {

      try {
        // Create new adduct.
        final AdductType adduct =
            new AdductType(nameNode.getNodeValue(), Double.parseDouble(massNode.getNodeValue()));

        // A new choice?
        if (!newChoices.contains(adduct)) {

          newChoices.add(adduct);
        }

        // Selected?
        if (!selections.contains(adduct) && selectedNode != null
            && Boolean.parseBoolean(selectedNode.getNodeValue())) {

          selections.add(adduct);
        }
      } catch (NumberFormatException ex) {

        // Ignore.
        LOG.warning("Illegal mass difference attribute in " + item.getNodeValue());
      }
    }
  }

  // Set choices and selections (value).
  setChoices(newChoices.toArray(new AdductType[newChoices.size()]));
  setValue(selections.toArray(new AdductType[selections.size()]));
}
 
Example 19
Source File: DOM2DTM.java    From jdk1.8-source-analysis with Apache License 2.0 4 votes vote down vote up
/**
 * The getUnparsedEntityURI function returns the URI of the unparsed
 * entity with the specified name in the same document as the context
 * node (see [3.3 Unparsed Entities]). It returns the empty string if
 * there is no such entity.
 * <p>
 * XML processors may choose to use the System Identifier (if one
 * is provided) to resolve the entity, rather than the URI in the
 * Public Identifier. The details are dependent on the processor, and
 * we would have to support some form of plug-in resolver to handle
 * this properly. Currently, we simply return the System Identifier if
 * present, and hope that it a usable URI or that our caller can
 * map it to one.
 * TODO: Resolve Public Identifiers... or consider changing function name.
 * <p>
 * If we find a relative URI
 * reference, XML expects it to be resolved in terms of the base URI
 * of the document. The DOM doesn't do that for us, and it isn't
 * entirely clear whether that should be done here; currently that's
 * pushed up to a higher level of our application. (Note that DOM Level
 * 1 didn't store the document's base URI.)
 * TODO: Consider resolving Relative URIs.
 * <p>
 * (The DOM's statement that "An XML processor may choose to
 * completely expand entities before the structure model is passed
 * to the DOM" refers only to parsed entities, not unparsed, and hence
 * doesn't affect this function.)
 *
 * @param name A string containing the Entity Name of the unparsed
 * entity.
 *
 * @return String containing the URI of the Unparsed Entity, or an
 * empty string if no such entity exists.
 */
public String getUnparsedEntityURI(String name)
{

  String url = "";
  Document doc = (m_root.getNodeType() == Node.DOCUMENT_NODE)
      ? (Document) m_root : m_root.getOwnerDocument();

  if (null != doc)
  {
    DocumentType doctype = doc.getDoctype();

    if (null != doctype)
    {
      NamedNodeMap entities = doctype.getEntities();
      if(null == entities)
        return url;
      Entity entity = (Entity) entities.getNamedItem(name);
      if(null == entity)
        return url;

      String notationName = entity.getNotationName();

      if (null != notationName)  // then it's unparsed
      {
        // The draft says: "The XSLT processor may use the public
        // identifier to generate a URI for the entity instead of the URI
        // specified in the system identifier. If the XSLT processor does
        // not use the public identifier to generate the URI, it must use
        // the system identifier; if the system identifier is a relative
        // URI, it must be resolved into an absolute URI using the URI of
        // the resource containing the entity declaration as the base
        // URI [RFC2396]."
        // So I'm falling a bit short here.
        url = entity.getSystemId();

        if (null == url)
        {
          url = entity.getPublicId();
        }
        else
        {
          // This should be resolved to an absolute URL, but that's hard
          // to do from here.
        }
      }
    }
  }

  return url;
}
 
Example 20
Source File: ConfigurationManager.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private final String getValue(final NamedNodeMap map, final String attr) {

      final Node n = map.getNamedItem(attr);
      return n.getNodeValue();
   }