Java Code Examples for org.w3c.dom.Document#getFirstChild()

The following examples show how to use org.w3c.dom.Document#getFirstChild() . 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
Source Project: iaf   File: BisUtils.java    License: Apache License 2.0 6 votes vote down vote up
public Message prepareReply(Message rawReply, String messageHeader, String result, boolean resultInPayload) throws DomBuilderException, IOException, TransformerException {
	ArrayList messages = new ArrayList();
	if (messageHeader != null) {
		messages.add(messageHeader);
	}
	messages.add(rawReply.asString());

	String payload = null;
	if (result == null) {
		payload = Misc.listToString(messages);
	} else {
		if (resultInPayload) {
			String message = Misc.listToString(messages);
			Document messageDoc = XmlUtils.buildDomDocument(message);
			Node messageRootNode = messageDoc.getFirstChild();
			Node resultNode = messageDoc.importNode(XmlUtils.buildNode(result), true);
			messageRootNode.appendChild(resultNode);
			payload = XmlUtils.nodeToString(messageDoc);
		} else {
			messages.add(result);
			payload = Misc.listToString(messages);
		}
	}
	return new Message(payload);
}
 
Example 2
Source Project: hop   File: XmlHandlerUnitTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetLastSubNode() throws Exception {
  String testXML =
    "<?xml version=\"1.0\"?>\n"
      + "<root>\n"
      + "<xpto>A</xpto>\n"
      + "<xpto>B</xpto>\n"
      + "<xpto>C</xpto>\n"
      + "<xpto>D</xpto>\n"
      + "</root>\n";

  DocumentBuilder builder = XmlHandler.createDocumentBuilder( false, false );

  Document parse = builder.parse( new ByteArrayInputStream( testXML.getBytes() ) );
  Node rootNode = parse.getFirstChild();
  Node lastSubNode = XmlHandler.getLastSubNode( rootNode, "xpto" );
  assertNotNull( lastSubNode );
  assertEquals( "D", lastSubNode.getTextContent() );
}
 
Example 3
Source Project: elastic-db-tools-for-java   File: SqlResults.java    License: MIT License 6 votes vote down vote up
/**
 * Constructs an instance of StoreLogEntry using parts of a row from ResultSet. Used for creating the store operation for Undo.
 *
 * @param reader
 *            ResultSet whose row has operation information.
 * @param offset
 *            Reader offset for column that begins operation information.
 */
public static StoreLogEntry readLogEntry(ResultSet reader,
        int offset) throws SQLException {
    try {
        UUID shardIdRemoves = StringUtilsLocal.isNullOrEmpty(reader.getString(offset + 4)) ? null : UUID.fromString(reader.getString(offset + 4));
        UUID shardIdAdds = StringUtilsLocal.isNullOrEmpty(reader.getString(offset + 5)) ? null : UUID.fromString(reader.getString(offset + 5));
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(reader.getSQLXML(offset + 2).getBinaryStream());

        return new StoreLogEntry(UUID.fromString(reader.getString(offset)), StoreOperationCode.forValue(reader.getInt(offset + 1)),
                (Element) doc.getFirstChild(), StoreOperationState.forValue(reader.getInt(offset + 3)), shardIdRemoves, shardIdAdds);
    }
    catch (SAXException | IOException | ParserConfigurationException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 4
Source Project: cxf   File: Client.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
    if (args != null && args.length > 0 && !"".equals(args[0])) {
        factory.setAddress(args[0]);
    } else {
        factory.setAddress("http://localhost:9000/Hello");
    }
    factory.getServiceFactory().setDataBinding(new AegisDatabinding());
    HelloWorld client = factory.create(HelloWorld.class);
    System.out.println("Invoke sayHi()....");
    System.out.println(client.sayHi(System.getProperty("user.name")));
    Document doc = client.getADocument();
    Element e = (Element) doc.getFirstChild();
    System.out.println(e.getTagName());
    Text t = (Text) e.getFirstChild();
    System.out.println(t);
}
 
Example 5
Source Project: Azzet   File: TestXml.java    License: Open Software License 3.0 6 votes vote down vote up
@Test
public void testClass()
{
	Document doc = Assets.load("plugin.xml");

	assertNotNull( doc );
	
	Node n0 = doc.getFirstChild();
	
	assertNotNull( n0 );
	assertEquals( "plugin", n0.getNodeName() );
	assertEquals( "test", n0.getAttributes().getNamedItem("name").getNodeValue() );
	
	Node n1 = n0.getChildNodes().item(1);

	assertNotNull( n1 );
	assertEquals( "version", n1.getNodeName() );
	assertEquals( "2.3.0", n1.getFirstChild().getNodeValue() );
}
 
Example 6
Source Project: binnavi   File: MemoryModuleParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parses the thread id from the data contents of the CModuleReply message.
 *
 * @param data The raw data of the CModuleReply message.
 *
 * @return The parsed thread id.
 *
 * @throws MessageParserException Thrown if parsing of the message failed.
 */
public static TargetProcessThread parseThreadId(final byte[] data) throws MessageParserException {
  Preconditions.checkNotNull(data, "IE00057: Data argument can not be null");

  final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

  try {
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document document = builder.parse(new ByteArrayInputStream(data, 0, data.length));

    final Node node = document.getFirstChild();

    final long threadId = Long.valueOf(getAttribute(node, "threadid"));

    return new TargetProcessThread(threadId, ThreadState.SUSPENDED);
  } catch (final Exception exception) {
    throw new MessageParserException(exception.getLocalizedMessage());
  }
}
 
Example 7
Source Project: axmlprinter   File: TestAXMLResource.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testToXml() throws IOException, ParserConfigurationException {
    InputStream testStream = this.getClass().getClassLoader().getResourceAsStream(largeFromMalware);

    underTest = new AXMLResource(testStream);
    String xml = underTest.toXML();

    try {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));
        Node manifestNode = document.getFirstChild();
        NamedNodeMap manifestNodeAttributes = manifestNode.getAttributes();
        assertEquals("http://schemas.android.com/apk/res/android", manifestNodeAttributes.getNamedItem("xmlns:android").getNodeValue());
        assertEquals("3133", manifestNodeAttributes.getNamedItem("android:versionCode").getNodeValue());
        assertEquals("1.9.3", manifestNodeAttributes.getNamedItem("android:versionName").getNodeValue());
        assertEquals("com.faithcomesbyhearing.android.pt.bibleis", manifestNodeAttributes.getNamedItem("package").getNodeValue());
    } catch (SAXException e) {
        // Is not xml
        assertTrue(false);
    }
}
 
Example 8
@Override
public void parseDocument(Document doc, File f) {
    NamedNodeMap attrs;
    Node attr;
    ClassId classId;
    String className;
    ClassId parentClassId;
    for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
        if ("list".equals(n.getNodeName())) {
            for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                attrs = d.getAttributes();
                if ("class".equals(d.getNodeName())) {
                    attr = attrs.getNamedItem("classId");
                    classId = ClassId.getClassId(parseInteger(attr));
                    attr = attrs.getNamedItem("name");
                    className = attr.getNodeValue();
                    attr = attrs.getNamedItem("parentClassId");
                    parentClassId = (attr != null) ? ClassId.getClassId(parseInteger(attr)) : null;
                    _classData.put(classId, new ClassInfo(classId, className, parentClassId));
                }
            }
        }
    }
}
 
Example 9
Source Project: container   File: Fragments.java    License: Apache License 2.0 5 votes vote down vote up
public Node generateBPEL4RESTLightServiceInstancePOSTAsNode(final String instanceDataAPIUrlVariableName,
                                                            final String csarId, final QName serviceTemplateId,
                                                            final String responseVariableName) throws IOException,
    SAXException {
    final String templateString =
        generateBPEL4RESTLightServiceInstancePOST(instanceDataAPIUrlVariableName, csarId, serviceTemplateId,
            responseVariableName);
    final InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(templateString));
    final Document doc = this.docBuilder.parse(is);
    return doc.getFirstChild();
}
 
Example 10
Source Project: container   File: Fragments.java    License: Apache License 2.0 5 votes vote down vote up
public Node generateCopyFromStringVarToAnyTypeVarAsNode(final String propertyVarName,
                                                        final String nodeInstancePropertyRequestVarName,
                                                        final String nodeInstancePropertyLocalName,
                                                        final String nodeInstancePropertyNamespace) throws IOException,
    SAXException {
    final String templateString =
        generateCopyFromStringVarToAnyTypeVar(propertyVarName, nodeInstancePropertyRequestVarName,
            nodeInstancePropertyLocalName, nodeInstancePropertyNamespace);
    final InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(templateString));
    final Document doc = this.docBuilder.parse(is);
    return doc.getFirstChild();
}
 
Example 11
@Override
public void parseDocument(Document doc, File f) {
    for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
        if ("list".equalsIgnoreCase(n.getNodeName())) {
            for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                if ("equipment".equalsIgnoreCase(d.getNodeName())) {
                    parseEquipment(d);
                }
            }
        }
    }
}
 
Example 12
Source Project: L2jOrg   File: Config.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void parseDocument(Document doc, File f) {
    NamedNodeMap attrs;
    for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
        if ("gameserver".equalsIgnoreCase(n.getNodeName())) {
            for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                if ("define".equalsIgnoreCase(d.getNodeName())) {
                    attrs = d.getAttributes();
                    _subnets.add(attrs.getNamedItem("subnet").getNodeValue());
                    _hosts.add(attrs.getNamedItem("address").getNodeValue());

                    if (_hosts.size() != _subnets.size()) {
                        LOGGER.warn("Failed to Load " + IPCONFIG_FILE + " File - subnets does not match server addresses.");
                    }
                }
            }

            final Node att = n.getAttributes().getNamedItem("address");
            if (att == null) {
                LOGGER.warn("Failed to load " + IPCONFIG_FILE + " file - default server address is missing.");
                _hosts.add("127.0.0.1");
            } else {
                _hosts.add(att.getNodeValue());
            }
            _subnets.add("0.0.0.0/0");
        }
    }
}
 
Example 13
Source Project: container   File: ModelUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Transforms the given string to a DOM node
 *
 * @param xmlString the xml to transform as String
 * @return a DOM Node representing the given string
 */
public static Node string2dom(final String xmlString) throws ParserConfigurationException, SAXException,
    IOException {

    final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(true);
    final DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

    final InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlString));
    final Document doc = docBuilder.parse(is);
    return doc.getFirstChild();
}
 
Example 14
/**
 * Loads a BPEL Assign fragment which queries the csarEntrypath from the input message into String variable.
 *
 * @param assignName          the name of the BPEL assign
 * @param csarEntryXpathQuery the csarEntryPoint XPath query
 * @param stringVarName       the variable to load the queries results into
 * @return a DOM Node representing a BPEL assign element
 * @throws IOException  is thrown when loading internal bpel fragments fails
 * @throws SAXException is thrown when parsing internal format into DOM fails
 */
public Node loadAssignXpathQueryToStringVarFragmentAsNode(final String assignName, final String xpath2Query,
                                                          final String stringVarName) throws IOException,
    SAXException {
    final String templateString =
        loadAssignXpathQueryToStringVarFragmentAsString(assignName, xpath2Query, stringVarName);
    final InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(templateString));
    final Document doc = this.docBuilder.parse(is);
    return doc.getFirstChild();
}
 
Example 15
private final void load()
{
	if (Config.DEBUG)
   		System.out.print("Parsing ...");
       try
       {
           DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
           factory.setValidating(false);
           factory.setIgnoringComments(true);

           File file = new File(Config.DATAPACK_ROOT+"/data/xml/cursedWeapons.xml");
           if (!file.exists())
           {
       		if (Config.DEBUG)
           		System.out.println("NO FILE");
           	return;
           }

           Document doc = factory.newDocumentBuilder().parse(file);

           for (Node n=doc.getFirstChild(); n != null; n = n.getNextSibling())
           {
               if ("list".equalsIgnoreCase(n.getNodeName()))
               {
                   for (Node d=n.getFirstChild(); d != null; d = d.getNextSibling())
                   {
                       if ("item".equalsIgnoreCase(d.getNodeName()))
                       {
                   		NamedNodeMap attrs = d.getAttributes();
                       	int id = Integer.parseInt(attrs.getNamedItem("id").getNodeValue());
                       	int skillId = Integer.parseInt(attrs.getNamedItem("skillId").getNodeValue());
                       	String name = attrs.getNamedItem("name").getNodeValue();

                       	CursedWeapon cw = new CursedWeapon(id, skillId, name);

                       	int val;
                           for (Node cd=d.getFirstChild(); cd != null; cd = cd.getNextSibling())
                           {
                               if ("dropRate".equalsIgnoreCase(cd.getNodeName()))
                               {
                           		attrs = cd.getAttributes();
                           		val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                           		cw.setDropRate(val);
                               }
                               else if ("duration".equalsIgnoreCase(cd.getNodeName()))
                               {
                           		attrs = cd.getAttributes();
                           		val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                           		cw.setDuration(val);
                               }
                               else if ("durationLost".equalsIgnoreCase(cd.getNodeName()))
                               {
                           		attrs = cd.getAttributes();
                           		val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                           		cw.setDurationLost(val);
                               }
                               else if ("disapearChance".equalsIgnoreCase(cd.getNodeName()))
                               {
                           		attrs = cd.getAttributes();
                           		val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                           		cw.setDisapearChance(val);
                               }
                               else if ("stageKills".equalsIgnoreCase(cd.getNodeName()))
                               {
                           		attrs = cd.getAttributes();
                           		val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                           		cw.setStageKills(val);
                               }
                           }
                           _cursedWeapons.put(id, cw);
                       }
                   }
               }
           }

       	if (Config.DEBUG)
       		System.out.println("OK");
       }
       catch (Exception e)
       {
           _log.log(Level.SEVERE, "Error parsing cursed weapons file.", e);

           if (Config.DEBUG)
       		System.out.println("ERROR");
           return ;
       }
}
 
Example 16
Source Project: container   File: BPELProcessFragments.java    License: Apache License 2.0 4 votes vote down vote up
public Node transformStringToNode(String xmlString) throws SAXException, IOException {
    final InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlString));
    final Document doc = this.docBuilder.parse(is);
    return doc.getFirstChild();
}
 
Example 17
Source Project: j-road   File: DhlXTeeServiceImpl.java    License: Apache License 2.0 4 votes vote down vote up
private String addCorrectNamespaces(String xml) {
    Node root;
    try {
        DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = docBuilder.parse(new InputSource(new StringReader(xml)));

        Document targetDoc = docBuilder.newDocument();
        root = targetDoc.appendChild(targetDoc.createElementNS("", "xml-fragment"));

        Node keha = doc.getFirstChild();
        NodeList items = keha.getChildNodes();
        for (int i = 0; i < items.getLength(); i++) {
            Node item = items.item(i);
            final String name1 = item.getNodeName();
            log.debug("name=" + name1);
            if ("item".equalsIgnoreCase(name1)) {
                log.debug("parsing item");
                Node itemTarget = root.appendChild(targetDoc.createElementNS("", "item"));

                NodeList sublist = item.getChildNodes();
                for (int j = 0; j < sublist.getLength(); j++) {
                    Node subItem = sublist.item(j);
                    final String localName = subItem.getNodeName();
                    if ("dhl_id".equalsIgnoreCase(localName)) {
                        final String NS_DHL_META_AUTOMATIC = "http://www.riik.ee/schemas/dhl-meta-automatic";
                        addNameSpace(NS_DHL_META_AUTOMATIC, subItem, itemTarget);
                    } else if ("edastus".equalsIgnoreCase(localName)) {
                        final String NS_SCHEMAS_DHL = "http://www.riik.ee/schemas/dhl";
                        addNameSpace(NS_SCHEMAS_DHL, subItem, itemTarget);
                    } else if ("olek".equalsIgnoreCase(localName)) {
                        addNameSpace("", subItem, itemTarget);
                        // } else {
                        // log.error("Unexpected localName: '"+localName+"', text:\n'"+subItem.getTextContent()+"'");
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("failed to add correct namespaces to given xml: " + xml, e);
    }
    String resultXml = xmlNodeToString(root);
    if (log.isDebugEnabled()) {
        log.debug("Added namespaces for the xml.\n START: xml source:\n" + xml + "\n\nEND: xml source\nSTART: xml result\n" + resultXml
                + "\n\nEND: xml result");
    }
    return resultXml;
}
 
Example 18
Source Project: maven-replacer-plugin   File: XPathReplacer.java    License: MIT License 4 votes vote down vote up
private Node convertXmlToNode(String xml) throws Exception {
	InputSource docSource = new InputSource(new StringReader(xml));
	Document doc = docBuilder.parse(docSource);
	return doc.getFirstChild();
}
 
Example 19
Source Project: JDKSourceCode1.8   File: OutputFormat.java    License: MIT License 4 votes vote down vote up
/**
 * Determine the output method for the specified document.
 * If the document is an instance of {@link org.w3c.dom.html.HTMLDocument}
 * then the method is said to be <tt>html</tt>. If the root
 * element is 'html' and all text nodes preceding the root
 * element are all whitespace, then the method is said to be
 * <tt>html</tt>. Otherwise the method is <tt>xml</tt>.
 *
 * @param doc The document to check
 * @return The suitable method
 */
public static String whichMethod( Document doc )
{
    Node    node;
    String  value;
    int     i;

    // If document is derived from HTMLDocument then the default
    // method is html.
    if ( doc instanceof HTMLDocument )
        return Method.HTML;

    // Lookup the root element and the text nodes preceding it.
    // If root element is html and all text nodes contain whitespace
    // only, the method is html.

    // FIXME (SM) should we care about namespaces here?

    node = doc.getFirstChild();
    while (node != null) {
        // If the root element is html, the method is html.
        if ( node.getNodeType() == Node.ELEMENT_NODE ) {
            if ( node.getNodeName().equalsIgnoreCase( "html" ) ) {
                return Method.HTML;
            } else if ( node.getNodeName().equalsIgnoreCase( "root" ) ) {
                return Method.FOP;
            } else {
                return Method.XML;
            }
        } else if ( node.getNodeType() == Node.TEXT_NODE ) {
            // If a text node preceding the root element contains
            // only whitespace, this might be html, otherwise it's
            // definitely xml.
            value = node.getNodeValue();
            for ( i = 0 ; i < value.length() ; ++i )
                if ( value.charAt( i ) != 0x20 && value.charAt( i ) != 0x0A &&
                     value.charAt( i ) != 0x09 && value.charAt( i ) != 0x0D )
                    return Method.XML;
        }
        node = node.getNextSibling();
    }
    // Anything else, the method is xml.
    return Method.XML;
}
 
Example 20
Source Project: container   File: ResourceHandler.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Generates a BPEL Copy which sets a dummy WS-Addressing ReplyTo Header on the given request
 * variable
 *
 * @param requestVariableName the name of a BPEL Variable as String
 * @return a DOM Node containing a complete BPEL Copy element
 * @throws IOException is thrown when reading internal files fails
 * @throws SAXException is thrown when parsing internal data to DOM fails
 */
public Node generateAddressingInitAsNode(final String requestVariableName) throws IOException, SAXException {
    final String addressingCopyString = generateAddressingInit(requestVariableName);
    final InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(addressingCopyString));
    final Document doc = this.docBuilder.parse(is);
    return doc.getFirstChild();
}