Java Code Examples for org.w3c.dom.NodeList#item()

The following examples show how to use org.w3c.dom.NodeList#item() . These examples are extracted from open source projects. 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
/**
 * Copy NodeList members into this nodelist, adding in
 * document order.  If a node is null, don't add it.
 *
 * @param nodelist List of nodes to be added
 * @param support The XPath runtime context.
 * @throws RuntimeException thrown if this NodeSet is not of
 * a mutable type.
 */
public void addNodesInDocOrder(NodeList nodelist, XPathContext support)
{

  if (!m_mutable)
    throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESET_NOT_MUTABLE, null)); //"This NodeSet is not mutable!");

  int nChildren = nodelist.getLength();

  for (int i = 0; i < nChildren; i++)
  {
    Node node = nodelist.item(i);

    if (null != node)
    {
      addNodeInDocOrder(node, support);
    }
  }
}
 
Example 2
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 3
private int getTotalNumberIssues(){
String tempQuery = "?jqlQuery=project+%3D+{0}+ORDER+BY+key+DESC&tempMax=1";
tempQuery = tempQuery.replace("{0}", projectName);
try {
	url = new URL(jiraURL + tempQuery);
	connection = url.openConnection();
	d = parseXML(connection.getInputStream());
	NodeList descNodes = d.getElementsByTagName("item");
	Node node = descNodes.item(0);
	for (int p = 0; p < node.getChildNodes().getLength(); p++) {
	if (node.getChildNodes().item(p).getNodeName().equals("key")){
		String key = (node.getChildNodes().item(p).getTextContent());
		key = key.replaceFirst(".*?(\\d+).*", "$1");
		return Integer.parseInt(key);
	}}
} catch (Exception e) {
	pw.println(e.getMessage());
} 
return 0;
}
 
Example 4
/**
 * The math:max function returns the maximum value of the nodes passed as the argument.
 * The maximum value is defined as follows. The node set passed as an argument is sorted
 * in descending order as it would be by xsl:sort with a data type of number. The maximum
 * is the result of converting the string value of the first node in this sorted list to
 * a number using the number function.
 * <p>
 * If the node set is empty, or if the result of converting the string values of any of the
 * nodes to a number is NaN, then NaN is returned.
 *
 * @param nl The NodeList for the node-set to be evaluated.
 *
 * @return the maximum value found, NaN if any node cannot be converted to a number.
 *
 * @see <a href="http://www.exslt.org/">EXSLT</a>
 */
public static double max (NodeList nl)
{
  if (nl == null || nl.getLength() == 0)
    return Double.NaN;

  double m = - Double.MAX_VALUE;
  for (int i = 0; i < nl.getLength(); i++)
  {
    Node n = nl.item(i);
    double d = toNumber(n);
    if (Double.isNaN(d))
      return Double.NaN;
    else if (d > m)
      m = d;
  }

  return m;
}
 
Example 5
public Clazz(final Node classNode, final Framework parent) {
    super(classNode, parent);
    this.classMethods = new ArrayList<Method>();
    this.instanceMethods = new ArrayList<Method>();

    final NodeList methodNodes = classNode.getChildNodes();
    for (int i = 0; i < methodNodes.getLength(); i++) {
        final Node node = methodNodes.item(i);
        if (!"method".equals(node.getLocalName())) continue;

        final String selName = Element.getAttr(node, "selector");
        if(selName == null || !SEL.validName(selName)){
            System.err.format("Warning: Discarding method %1$s:%2$s:%3$s"
                    + " -- Invalid selector name. Verify.\n",
                    parent.name, name, selName);
            continue;
        }

        final Method method = new Method(node, parent);
        if (method.isClassMethod) {
            classMethods.add(method);
        } else {
            instanceMethods.add(method);
        }
    }
}
 
Example 6
@Override
public void loadValueFromXML(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 p : this.value.getParameters()) {
      if (p.getName().equals(paramName)) {
        try {
          p.loadValueFromXML(nextElement);
        } catch (Exception e) {
          logger.log(Level.WARNING, "Error while loading parameter values for " + p.getName(), e);
        }
      }
    }
  }
}
 
Example 7
@Test
public void testParseXmlXxeError2() {
    System.out.println("***************************" + 2 + "***************************");
    String xmlFile = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
            "<!DOCTYPE a [\n" +
            "    <!ENTITY % name SYSTEM \"file:///etc/passwd\">\n" +
            "    %name;\n" +
            "]>";
    Document doc = null;
    try {
        doc = XmlUtils.getInstance().newDocument(xmlFile, "utf-8");
        Node notifyNode = doc.getFirstChild();
        NodeList list = notifyNode.getChildNodes();
        for (int i = 0, length = list.getLength(); i < length; i++) {
            Node n = list.item(i);
            String nodeName = n.getNodeName();
            String nodeContent = n.getTextContent();
            System.out.println(nodeName.toString() + "    " + nodeContent.toString());
        }
        assertTrue(false);
    } catch (Exception e) {
        assertTrue(true);
    }
}
 
Example 8
private List<EventDefinition> buildEvents(NodeList nodes) {
   List<EventDefinition> events = new ArrayList<EventDefinition>(nodes.getLength() + 1);
   logger.trace("Reading {} event nodes", nodes.getLength());
   for (int i = 0; i < nodes.getLength(); i++) {
      Element element = (Element)nodes.item(i);
      EventDefinition event = 
            Definitions
               .eventBuilder()
               .withName(element.getAttribute("name"))
               .withDescription(element.getAttribute("description"))
               .withParameters(
                     buildParameters(element.getElementsByTagNameNS(schemaURI, "parameter"))
               )
               .build();
      events.add(event);
      logger.trace("Added event [{}]", event.getName());
   }
   return events;
}
 
Example 9
/**
 * <code>publicId</code> returns the public identifier of the node passed as
 * argument. If a node set is passed as argument, the public identifier of
 * the first node in the set is returned.
 *
 * Xalan does not currently record this value, and will return null.
 *
 * @param nodeList a <code>NodeList</code> value
 * @return a <code>String</code> value
 */
public static String publicId(NodeList nodeList)
{
  if (nodeList == null || nodeList.getLength() == 0)
    return null;

  Node node = nodeList.item(0);
  int nodeHandler = ((DTMNodeProxy)node).getDTMNodeNumber();
  SourceLocator locator = ((DTMNodeProxy)node).getDTM()
    .getSourceLocatorFor(nodeHandler);

  if (locator != null)
    return locator.getPublicId();
  else
    return null;
}
 
Example 10
Source Project: jdk1.8-source-analysis   File: NodeInfo.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <code>systemId</code> returns the system id of the node passed as
 * argument. If a node set is passed as argument, the system id of
 * the first node in the set is returned.
 *
 * @param nodeList a <code>NodeList</code> value
 * @return a <code>String</code> value
 */
public static String systemId(NodeList nodeList)
{
  if (nodeList == null || nodeList.getLength() == 0)
    return null;

  Node node = nodeList.item(0);
  int nodeHandler = ((DTMNodeProxy)node).getDTMNodeNumber();
  SourceLocator locator = ((DTMNodeProxy)node).getDTM()
    .getSourceLocatorFor(nodeHandler);

  if (locator != null)
    return locator.getSystemId();
  else
    return null;
}
 
Example 11
@Override
public void loadValueFromXML(Element xmlElement) {
  NodeList items = xmlElement.getElementsByTagName("module");

  for (int i = 0; i < items.getLength(); i++) {
    Element moduleElement = (Element) items.item(i);
    String name = moduleElement.getAttribute("name");
    for (int j = 0; j < modulesWithParams.length; j++) {
      if (modulesWithParams[j].getModule().getName().equals(name)) {
        ParameterSet moduleParameters = modulesWithParams[j].getParameterSet();
        if (moduleParameters == null)
          continue;
        moduleParameters.loadValuesFromXML((Element) items.item(i));
      }
    }
  }
  String selectedAttr = xmlElement.getAttribute("selected");
  for (int j = 0; j < modulesWithParams.length; j++) {
    if (modulesWithParams[j].getModule().getName().equals(selectedAttr)) {
      value = modulesWithParams[j];
    }
  }
}
 
Example 12
Source Project: hop   File: OdfSheet.java    License: Apache License 2.0 6 votes vote down vote up
protected int findNrColumns( OdfTableRow row ) {
  int result = roughNrOfCols;
  if ( row != null ) {
    NodeList cells = row.getOdfElement().getChildNodes();
    if ( cells != null && cells.getLength() > 0 ) {
      int cellLen = cells.getLength();
      for ( int i = cellLen - 1; i >= 0; i-- ) {
        Node cell = cells.item( i );
        if ( cell instanceof TableTableCellElement ) {
          if ( !cell.hasChildNodes() ) {
            // last cell is empty - remove it from counter
            result -= ( (TableTableCellElement) cell ).getTableNumberColumnsRepeatedAttribute();
          } else {
            // get first non-empty cell from the end, break
            break;
          }
        }
      }
    }
  }
  return result;
}
 
Example 13
Source Project: constellation   File: XmlUtilities.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reads an XML document into an array of maps. The XML document is
 * recursively read and each time a tag with a specified name is
 * encountered, the children of that element are used to create a series of
 * key/value pairs that are placed into a new map in the array. The name of
 * each child tag becomes a new key while the text content of that element
 * becomes the value.
 *
 * @param document the XML document.
 * @param rowTag the tags that represent a row in the resulting tabular
 * structure.
 * @return a tabular representation of the given XML document.
 */
public List<Map<String, String>> map(final Document document, final String rowTag) {
    final List<Map<String, String>> table = new LinkedList<>();
    final NodeList rowList = document.getElementsByTagName(rowTag);
    for (int r = 0; r < rowList.getLength(); r++) {
        final Node rowNode = rowList.item(r);
        if (rowNode instanceof Element) {
            final Element rowElement = (Element) rowNode;

            final Map<String, String> row = new HashMap<>();
            table.add(row);

            final NodeList cellList = rowElement.getChildNodes();
            for (int c = 0; c < cellList.getLength(); c++) {
                final Node cellNode = cellList.item(c);
                if (cellNode instanceof Element) {
                    final Element cellElement = (Element) cellNode;
                    row.put(cellElement.getTagName(), cellElement.getTextContent());
                }
            }
        }
    }
    return table;
}
 
Example 14
Source Project: milkman   File: XmlContentType.java    License: MIT License 5 votes vote down vote up
public static String toPrettyString(String xml, int indent) {
    try {
        // Turn xml string into a document
        Document document = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

        // Remove whitespaces outside tags
        document.normalize();
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']",
                                                      document,
                                                      XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        // Setup pretty print options
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // Return pretty print xml string
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (Exception e) {
        log.warn("Failed to format xml", e);
    }
    return xml;
}
 
Example 15
private void validateIdAttributes(Document doc) throws Exception {
  String idAttribute = new String(idIdentifier.getText());
  XPathFactory xPathfactory = XPathFactory.newInstance();
  XPath xpath = xPathfactory.newXPath();
  XPathExpression expr = xpath.compile("descendant-or-self::*/@" + idAttribute);
  NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
  if(nodeList != null && nodeList.getLength() > 0) {
    for(int j = 0; j < nodeList.getLength(); j++) {
        Attr attr = (Attr)nodeList.item(j);
        ((Element)attr.getOwnerElement()).setIdAttributeNode(attr,true);
    }
  }
}
 
Example 16
public static void writeXmlFormatted(Document pom, File destination, Log log) throws Exception {
    XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("//text()[normalize-space(.) = '']");
    NodeList emptyNodes = (NodeList) xpath.evaluate(pom, XPathConstants.NODESET);

    // Remove empty text nodes
    for (int i = 0; i < emptyNodes.getLength(); i++) {
        Node emptyNode = emptyNodes.item(i);
        emptyNode.getParentNode().removeChild(emptyNode);
    }

    pom.setXmlStandalone(true);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    DOMSource source = new DOMSource(pom);

    String content;
    try (StringWriter out = new StringWriter()) {
        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
        content = out.toString();
    }

    // Fix header formatting problem
    content = content.replaceFirst("-->", "-->\n").replaceFirst("\\?><!--", "\\?>\n<!--");

    writeFileIfChanged(content, destination, log);
}
 
Example 17
Source Project: hop   File: SwitchCaseTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Load local xml data for case-value mapping, transform info.
 *
 * @return
 * @throws URISyntaxException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
private static Node loadTransformXmlMetadata( String fileName ) throws URISyntaxException, ParserConfigurationException, SAXException, IOException {
  String PKG = SwitchCaseTest.class.getPackage().getName().replace( ".", "/" );
  PKG = PKG + "/";
  URL url = SwitchCaseTest.class.getClassLoader().getResource( PKG + fileName );
  File file = new File( url.toURI() );
  DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  Document doc = dBuilder.parse( file );
  NodeList nList = doc.getElementsByTagName( "transform" );
  return nList.item( 0 );
}
 
Example 18
/**
 * Creates a <code>DOMKeyInfo</code> from XML.
 *
 * @param kiElem KeyInfo element
 */
public DOMKeyInfo(Element kiElem, XMLCryptoContext context,
                  Provider provider)
    throws MarshalException
{
    // get Id attribute, if specified
    Attr attr = kiElem.getAttributeNodeNS(null, "Id");
    if (attr != null) {
        id = attr.getValue();
        kiElem.setIdAttributeNode(attr, true);
    } else {
        id = null;
    }

    // get all children nodes
    NodeList nl = kiElem.getChildNodes();
    int length = nl.getLength();
    if (length < 1) {
        throw new MarshalException
            ("KeyInfo must contain at least one type");
    }
    List<XMLStructure> content = new ArrayList<XMLStructure>(length);
    for (int i = 0; i < length; i++) {
        Node child = nl.item(i);
        // ignore all non-Element nodes
        if (child.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }
        Element childElem = (Element)child;
        String localName = childElem.getLocalName();
        if (localName.equals("X509Data")) {
            content.add(new DOMX509Data(childElem));
        } else if (localName.equals("KeyName")) {
            content.add(new DOMKeyName(childElem));
        } else if (localName.equals("KeyValue")) {
            content.add(DOMKeyValue.unmarshal(childElem));
        } else if (localName.equals("RetrievalMethod")) {
            content.add(new DOMRetrievalMethod(childElem,
                                               context, provider));
        } else if (localName.equals("PGPData")) {
            content.add(new DOMPGPData(childElem));
        } else { //may be MgmtData, SPKIData or element from other namespace
            content.add(new javax.xml.crypto.dom.DOMStructure((childElem)));
        }
    }
    keyInfoTypes = Collections.unmodifiableList(content);
}
 
Example 19
/**
 * Merge the given DHT node into the marker sequence.  If there already
 * exist DHT marker segments in the sequence, then each table in the
 * node replaces the first table, in any DHT segment, with the same
 * table class and table id.  If none of the existing DHT segments contain
 * a table with the same class and id, then the table is added to the last
 * existing DHT segment.
 * If there are no DHT segments, then a new one is created and added
 * as follows:
 * If there are DQT segments, the new DHT segment is inserted immediately
 * following the last DQT segment.
 * If there are no DQT segments, the new DHT segment is inserted before
 * an SOF segment, if there is one.
 * If there is no SOF segment, the new DHT segment is inserted before
 * the first SOS segment, if there is one.
 * If there is no SOS segment, the new DHT segment is added to the end
 * of the sequence.
 */
private void mergeDHTNode(Node node) throws IIOInvalidTreeException {
    // First collect any existing DQT nodes into a local list
    ArrayList oldDHTs = new ArrayList();
    Iterator iter = markerSequence.iterator();
    while (iter.hasNext()) {
        MarkerSegment seg = (MarkerSegment) iter.next();
        if (seg instanceof DHTMarkerSegment) {
            oldDHTs.add(seg);
        }
    }
    if (!oldDHTs.isEmpty()) {
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            NamedNodeMap attrs = child.getAttributes();
            int childID = MarkerSegment.getAttributeValue(child,
                                                          attrs,
                                                          "htableId",
                                                          0, 3,
                                                          true);
            int childClass = MarkerSegment.getAttributeValue(child,
                                                             attrs,
                                                             "class",
                                                             0, 1,
                                                             true);
            DHTMarkerSegment dht = null;
            int tableIndex = -1;
            for (int j = 0; j < oldDHTs.size(); j++) {
                DHTMarkerSegment testDHT = (DHTMarkerSegment) oldDHTs.get(j);
                for (int k = 0; k < testDHT.tables.size(); k++) {
                    DHTMarkerSegment.Htable testTable =
                        (DHTMarkerSegment.Htable) testDHT.tables.get(k);
                    if ((childID == testTable.tableID) &&
                        (childClass == testTable.tableClass)) {
                        dht = testDHT;
                        tableIndex = k;
                        break;
                    }
                }
                if (dht != null) break;
            }
            if (dht != null) {
                dht.tables.set(tableIndex, dht.getHtableFromNode(child));
            } else {
                dht = (DHTMarkerSegment) oldDHTs.get(oldDHTs.size()-1);
                dht.tables.add(dht.getHtableFromNode(child));
            }
        }
    } else {
        DHTMarkerSegment newGuy = new DHTMarkerSegment(node);
        int lastDQT = findMarkerSegmentPosition(DQTMarkerSegment.class, false);
        int firstSOF = findMarkerSegmentPosition(SOFMarkerSegment.class, true);
        int firstSOS = findMarkerSegmentPosition(SOSMarkerSegment.class, true);
        if (lastDQT != -1) {
            markerSequence.add(lastDQT+1, newGuy);
        } else if (firstSOF != -1) {
            markerSequence.add(firstSOF, newGuy);
        } else if (firstSOS != -1) {
            markerSequence.add(firstSOS, newGuy);
        } else {
            markerSequence.add(newGuy);
        }
    }
}
 
Example 20
private void parseAspect(Element aspectElement, ParserContext parserContext) {
	String aspectId = aspectElement.getAttribute(ID);
	String aspectName = aspectElement.getAttribute(REF);

	try {
		this.parseState.push(new AspectEntry(aspectId, aspectName));
		List<BeanDefinition> beanDefinitions = new ArrayList<>();
		List<BeanReference> beanReferences = new ArrayList<>();

		List<Element> declareParents = DomUtils.getChildElementsByTagName(aspectElement, DECLARE_PARENTS);
		for (int i = METHOD_INDEX; i < declareParents.size(); i++) {
			Element declareParentsElement = declareParents.get(i);
			beanDefinitions.add(parseDeclareParents(declareParentsElement, parserContext));
		}

		// We have to parse "advice" and all the advice kinds in one loop, to get the
		// ordering semantics right.
		NodeList nodeList = aspectElement.getChildNodes();
		boolean adviceFoundAlready = false;
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i);
			if (isAdviceNode(node, parserContext)) {
				if (!adviceFoundAlready) {
					adviceFoundAlready = true;
					if (!StringUtils.hasText(aspectName)) {
						parserContext.getReaderContext().error(
								"<aspect> tag needs aspect bean reference via 'ref' attribute when declaring advices.",
								aspectElement, this.parseState.snapshot());
						return;
					}
					beanReferences.add(new RuntimeBeanReference(aspectName));
				}
				AbstractBeanDefinition advisorDefinition = parseAdvice(
						aspectName, i, aspectElement, (Element) node, parserContext, beanDefinitions, beanReferences);
				beanDefinitions.add(advisorDefinition);
			}
		}

		AspectComponentDefinition aspectComponentDefinition = createAspectComponentDefinition(
				aspectElement, aspectId, beanDefinitions, beanReferences, parserContext);
		parserContext.pushContainingComponent(aspectComponentDefinition);

		List<Element> pointcuts = DomUtils.getChildElementsByTagName(aspectElement, POINTCUT);
		for (Element pointcutElement : pointcuts) {
			parsePointcut(pointcutElement, parserContext);
		}

		parserContext.popAndRegisterContainingComponent();
	}
	finally {
		this.parseState.pop();
	}
}