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

The following examples show how to use org.w3c.dom.Element#getFirstChild() . 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: TimerHandler.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public Object end(final String uri,
                  final String localName,
                  final ExtensibleXmlParser parser) throws SAXException {
    Element element = parser.endElementBuilder();
    StateBasedNode parent = (StateBasedNode) parser.getParent();
    String id = element.getAttribute("id");
    emptyAttributeCheck( localName, "id", id, parser );
    String delay = element.getAttribute("delay");
    String period = element.getAttribute("period");
    Timer timer = new Timer();
    timer.setId(new Long(id));
    if (delay != null && delay.length() != 0 ) {
        timer.setDelay(delay);
    }
    if (period != null && period.length() != 0 ) {
        timer.setPeriod(period);
    }
    org.w3c.dom.Node xmlNode = element.getFirstChild();
    DroolsAction action = null;
    if (xmlNode instanceof Element) {
		Element actionXml = (Element) xmlNode;
		action = AbstractNodeHandler.extractAction(actionXml);
    }
    parent.addTimer(timer, action);
    return null;
}
 
Example 2
Source File: STSServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signRequest(Element requestElement, PrivateKey privateKey, Object keyInfoValue) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, KeyException {
   DOMSignContext domSignContext = new DOMSignContext(privateKey, requestElement, requestElement.getFirstChild());
   String requestId = requestElement.getAttribute("RequestID");
   requestElement.setIdAttribute("RequestID", true);
   List<Transform> transforms = new LinkedList();
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature", (TransformParameterSpec)null));
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null));
   Reference reference = xmlSignatureFactory.newReference("#" + requestId, xmlSignatureFactory.newDigestMethod("http://www.w3.org/2000/09/xmldsig#sha1", (DigestMethodParameterSpec)null), transforms, (String)null, (String)null);
   CanonicalizationMethod canonicalizationMethod = xmlSignatureFactory.newCanonicalizationMethod("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null);
   SignatureMethod signatureMethod = xmlSignatureFactory.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#rsa-sha1", (SignatureMethodParameterSpec)null);
   SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference));
   KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
   KeyInfo keyInfo = null;
   if (keyInfoValue instanceof PublicKey) {
      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newKeyValue((PublicKey)keyInfoValue)));
   } else {
      if (!(keyInfoValue instanceof X509Certificate)) {
         throw new IllegalArgumentException("Unsupported keyinfo type [" + keyInfoValue.getClass() + "]");
      }

      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newX509Data(Collections.singletonList(keyInfoValue))));
   }

   XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);
   xmlSignature.sign(domSignContext);
}
 
Example 3
Source File: StramWebServicesTest.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
public static String getXmlString(Element element, String name)
{
  NodeList id = element.getElementsByTagName(name);
  Element line = (Element)id.item(0);
  if (line == null) {
    return null;
  }
  Node first = line.getFirstChild();
  // handle empty <key></key>
  if (first == null) {
    return "";
  }
  String val = first.getNodeValue();
  if (val == null) {
    return "";
  }
  return val;
}
 
Example 4
Source File: Base64.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method decode
 *
 * Takes the <CODE>Text</CODE> children of the Element and interprets
 * them as input for the <CODE>Base64.decode()</CODE> function.
 *
 * @param element
 * @return the byte obtained of the decoding the element
 * $todo$ not tested yet
 * @throws Base64DecodingException
 */
public static final byte[] decode(Element element) throws Base64DecodingException {

    Node sibling = element.getFirstChild();
    StringBuffer sb = new StringBuffer();

    while (sibling != null) {
        if (sibling.getNodeType() == Node.TEXT_NODE) {
            Text t = (Text) sibling;

            sb.append(t.getData());
        }
        sibling = sibling.getNextSibling();
    }

    return decode(sb.toString());
}
 
Example 5
Source File: Messages.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
private static Map<String, Message> toMap(Document dom) {
    Map<String, Message> map = new HashMap<>();
    Element element = dom.getDocumentElement();
    Element warnings = Xml.getChild(element, "WarningList");
    if(warnings != null) {
        Node node = warnings.getFirstChild();
        while(node != null) {
            if(node instanceof Element && ((Element)node).getTagName().equals("Warning")) {
                Element warning = (Element) node;
                String type = warning.getAttribute("Type");
                String title = Xml.getText(warning, "Title");
                String description = Xml.getText(warning, "Description");
                String longDescription = Xml.getText(warning, "LongDescription");
                if(map.containsKey(type)) {
                    throw new IllegalStateException("Warning type "+type+" is declared twice");
                }
                map.put(type, new Message(title, description, longDescription));
            }
            node = node.getNextSibling();
        }
    }
    return map;
}
 
Example 6
Source File: DOMKeyValue.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
PublicKey unmarshalKeyValue(Element kvtElem)
    throws MarshalException
{
    if (rsakf == null) {
        try {
            rsakf = KeyFactory.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException
                ("unable to create RSA KeyFactory: " + e.getMessage());
        }
    }
    Element modulusElem = DOMUtils.getFirstChildElement(kvtElem,
                                                        "Modulus");
    modulus = new DOMCryptoBinary(modulusElem.getFirstChild());
    Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem,
                                                          "Exponent");
    exponent = new DOMCryptoBinary(exponentElem.getFirstChild());
    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus.getBigNum(),
                                                 exponent.getBigNum());
    return generatePublicKey(rsakf, spec);
}
 
Example 7
Source File: Base64.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method decode
 *
 * Takes the <CODE>Text</CODE> children of the Element and interprets
 * them as input for the <CODE>Base64.decode()</CODE> function.
 *
 * @param element
 * @return the byte obtained of the decoding the element
 * $todo$ not tested yet
 * @throws Base64DecodingException
 */
public static final byte[] decode(Element element) throws Base64DecodingException {

    Node sibling = element.getFirstChild();
    StringBuffer sb = new StringBuffer();

    while (sibling != null) {
        if (sibling.getNodeType() == Node.TEXT_NODE) {
            Text t = (Text) sibling;

            sb.append(t.getData());
        }
        sibling = sibling.getNextSibling();
    }

    return decode(sb.toString());
}
 
Example 8
Source File: AnnotationImplTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAppInfo() throws IOException {
       String xpath = "/schema/element[1]/annotation";
       Annotation ann = FindSchemaComponentFromDOM.find(Annotation.class, schema, xpath);
       AppInfo info = ann.getAppInfos().iterator().next();
       assertEquals("appinfo source", "http://www.aloan.com/loanApp", info.getURI());
       Element infoE = info.getAppInfoElement();
       Element handlingE = (Element)infoE.getChildNodes().item(1);
       Text textnode = (Text)handlingE.getFirstChild();
       assertEquals("appinfo element child", "checkForPrimes", textnode.getText());

       ann.getModel().startTransaction();
       ann.removeAppInfo(info);
       AppInfo info2 = ann.getModel().getFactory().createAppInfo();
       textnode.setText("checkIfUpdated");
ann.getModel().endTransaction();
   }
 
Example 9
Source File: DOMKeyValue.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
PublicKey unmarshalKeyValue(Element kvtElem)
    throws MarshalException
{
    if (rsakf == null) {
        try {
            rsakf = KeyFactory.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException
                ("unable to create RSA KeyFactory: " + e.getMessage());
        }
    }
    Element modulusElem = DOMUtils.getFirstChildElement(kvtElem,
                                                        "Modulus");
    modulus = new DOMCryptoBinary(modulusElem.getFirstChild());
    Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem,
                                                          "Exponent");
    exponent = new DOMCryptoBinary(exponentElem.getFirstChild());
    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus.getBigNum(),
                                                 exponent.getBigNum());
    return generatePublicKey(rsakf, spec);
}
 
Example 10
Source File: CDAUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public List<Element> getChildren(Element element, String name) {
List<Element> l = new ArrayList<Element>();
if (element != null) {
	Node n = element.getFirstChild();
	while (n != null) {
		if (n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals(name)) {
			l.add((Element) n);
		}
		n = n.getNextSibling();
	}
}
return l;
}
 
Example 11
Source File: DomAnnotationParserFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public Object getResult(Object existing) {
    Document dom = (Document)result.getNode();
    Element e = dom.getDocumentElement();
    if(existing instanceof Element) {
        // merge all the children
        Element prev = (Element) existing;
        Node anchor = e.getFirstChild();
        while(prev.getFirstChild()!=null) {
            Node move = prev.getFirstChild();
            e.insertBefore(e.getOwnerDocument().adoptNode(move), anchor );
        }
    }
    return e;
}
 
Example 12
Source File: OtherData.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
private static String getCharacterDataFromElement(Element e) {
	try {
		Node child = e.getFirstChild();
		if (child instanceof org.w3c.dom.CharacterData) {
			org.w3c.dom.CharacterData cd = (org.w3c.dom.CharacterData) child;
			return cd.getData();
		}
	} catch (Exception ex) {
	}
	return "";
}
 
Example 13
Source File: XmlHelper.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static Element findChildElementWithAttribute(Element parent, String name, String attribute, String value) {
    if (parent == null) {
        return null;
    }
    org.w3c.dom.Node ret = parent.getFirstChild();
    while (ret != null && (!(ret instanceof Element) || !ret.getNodeName().equals(name) || ((Element)ret).getAttribute(attribute)==null || !((Element)ret).getAttribute(attribute).equals(value))) {
        ret = ret.getNextSibling();
    }
    return (Element) ret;
}
 
Example 14
Source File: MessageFlow.java    From cxf with Apache License 2.0 5 votes vote down vote up
private boolean getLastMessage(Element element) throws Exception {
    for (Node nd = element.getFirstChild(); nd != null; nd = nd.getNextSibling()) {
        if (Node.ELEMENT_NODE == nd.getNodeType() && "LastMessage".equals(nd.getLocalName())) {
            return true;
        }
    }
    return false;
}
 
Example 15
Source File: XMLUtil.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static String htmlToXmlEscapedPlainText(Element r) {
  StringBuilder s = new StringBuilder();
  Node n = r.getFirstChild();
  boolean ws = false;
  while (n != null) {
    if (n.getNodeType() == Node.TEXT_NODE) {
      String t = n.getTextContent().trim();
      if (Utilities.noString(t))
        ws = true;
      else {
        if (ws)
          s.append(" ");
        ws = false;
        s.append(t);
      }
    }
    if (n.getNodeType() == Node.ELEMENT_NODE) {
      if (ws)
        s.append(" ");
      ws = false;
      s.append(htmlToXmlEscapedPlainText((Element) n));
      if (r.getNodeName().equals("br") || r.getNodeName().equals("p"))
        s.append("\r\n");
    }
    n = n.getNextSibling();      
  }
  return s.toString();
}
 
Example 16
Source File: DOMConfigurationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Equivalence class partitioning with state and input values orientation
 * for public void setParameter(String name, Object value) throws
 * DOMException, <br>
 * <b>pre-conditions</b>: the root element has two Comment nodes, <br>
 * <b>name</b>: comments <br>
 * <b>value</b>: false. <br>
 * <b>Expected results</b>: the root element has no children
 */
@Test
public void testComments002() {
    DOMImplementation domImpl = null;
    try {
        domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException pce) {
        Assert.fail(pce.toString());
    } catch (FactoryConfigurationError fce) {
        Assert.fail(fce.toString());
    }

    Document doc = domImpl.createDocument("namespaceURI", "ns:root", null);

    Comment comment1 = doc.createComment("comment1");
    Comment comment2 = doc.createComment("comment2");

    DOMConfiguration config = doc.getDomConfig();
    config.setParameter("comments", Boolean.FALSE);

    Element root = doc.getDocumentElement();
    root.appendChild(comment1);
    root.appendChild(comment2);

    doc.normalizeDocument();

    if (root.getFirstChild() != null) {
        Assert.fail("root has a child " + root.getFirstChild() + ", but expected to has none");
    }

    return; // Status.passed("OK");

}
 
Example 17
Source File: XMLUtils.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Method getFullTextChildrenFromElement
 *
 * @param element
 * @return the string of children
 */
public static String getFullTextChildrenFromElement(Element element) {
    StringBuilder sb = new StringBuilder();

    Node child = element.getFirstChild();
    while (child != null) {
        if (child.getNodeType() == Node.TEXT_NODE) {
            sb.append(((Text)child).getData());
        }
        child = child.getNextSibling();
    }

    return sb.toString();
}
 
Example 18
Source File: BoundaryEventHandler.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
protected void handleErrorNode(final Node node, final Element element, final String uri,
           final String localName, final ExtensibleXmlParser parser, final String attachedTo,
           final boolean cancelActivity) throws SAXException {
       super.handleNode(node, element, uri, localName, parser);
       BoundaryEventNode eventNode = (BoundaryEventNode) node;
       eventNode.setMetaData("AttachedTo", attachedTo);
       eventNode.setAttachedToNodeId(attachedTo);
       org.w3c.dom.Node xmlNode = element.getFirstChild();
       while (xmlNode != null) {
           String nodeName = xmlNode.getNodeName();
           if ("dataOutput".equals(nodeName)) {
               String id = ((Element) xmlNode).getAttribute("id");
               String outputName = ((Element) xmlNode).getAttribute("name");
               dataOutputs.put(id, outputName);
           } else if ("dataOutputAssociation".equals(nodeName)) {
               readDataOutputAssociation(xmlNode, eventNode, parser);
           } else if ("errorEventDefinition".equals(nodeName)) {
               String errorRef = ((Element) xmlNode).getAttribute("errorRef");
               if (errorRef != null && errorRef.trim().length() > 0) {
               	List<Error> errors = (List<Error>) ((ProcessBuildData) parser.getData()).getMetaData("Errors");
	            if (errors == null) {
	                throw new IllegalArgumentException("No errors found");
	            }
	            Error error = null;
	            for( Error listError : errors ) {
	                if( errorRef.equals(listError.getId()) ) {
	                    error = listError;
	                }
	            }
	            if (error == null) {
	                throw new IllegalArgumentException("Could not find error " + errorRef);
	            }
	            String type = error.getErrorCode();
	            boolean hasErrorCode = true;
	            if (type == null) {
	            	type = error.getId();
	            	hasErrorCode = false;
	            }
	            String structureRef = error.getStructureRef();
	            if (structureRef != null) {
	            	Map<String, ItemDefinition> itemDefs = (Map<String, ItemDefinition>)((ProcessBuildData)
	            			parser.getData()).getMetaData("ItemDefinitions");

	            	if (itemDefs.containsKey(structureRef)) {
	            		structureRef = itemDefs.get(structureRef).getStructureRef();
	            	}
	            }

                   List<EventFilter> eventFilters = new ArrayList<EventFilter>();
                   EventTypeFilter eventFilter = new EventTypeFilter();
                   eventFilter.setType("Error-" + attachedTo + "-" + type);
                   eventFilters.add(eventFilter);
                   eventNode.setEventFilters(eventFilters);
                   eventNode.setMetaData("ErrorEvent", type);
                   eventNode.setMetaData("HasErrorEvent", hasErrorCode);
                   eventNode.setMetaData("ErrorStructureRef", structureRef);
               }
           }
           xmlNode = xmlNode.getNextSibling();
       }
   }
 
Example 19
Source File: Soap12FaultOutInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void handleMessage(SoapMessage message) throws Fault {
    LOG.info(getClass() + (String) message.get(Message.CONTENT_TYPE));

    XMLStreamWriter writer = message.getContent(XMLStreamWriter.class);
    Fault f = (Fault)message.getContent(Exception.class);
    message.put(org.apache.cxf.message.Message.RESPONSE_CODE, f.getStatusCode());

    SoapFault fault = SoapFault.createFault(f, message.getVersion());

    try {
        Map<String, String> namespaces = fault.getNamespaces();
        for (Map.Entry<String, String> e : namespaces.entrySet()) {
            writer.writeNamespace(e.getKey(), e.getValue());
        }

        String ns = message.getVersion().getNamespace();
        String defaultPrefix = writer.getPrefix(ns);
        if (defaultPrefix == null) {
            defaultPrefix = StaxUtils.getUniquePrefix(writer, ns, false);
            writer.writeStartElement(defaultPrefix, "Fault", ns);
            writer.writeNamespace(defaultPrefix, ns);
        } else {
            writer.writeStartElement(defaultPrefix, "Fault", ns);
        }

        writer.writeStartElement(defaultPrefix, "Code", ns);
        writer.writeStartElement(defaultPrefix, "Value", ns);

        writer.writeCharacters(fault.getCodeString(getFaultCodePrefix(writer, fault.getFaultCode()),
                                                   defaultPrefix));
        writer.writeEndElement();

        if (fault.getSubCodes() != null) {
            int fscCount = 0;
            for (QName fsc : fault.getSubCodes()) {
                writer.writeStartElement(defaultPrefix, "Subcode", ns);
                writer.writeStartElement(defaultPrefix, "Value", ns);
                writer.writeCharacters(getCodeString(getFaultCodePrefix(writer, fsc),
                                                     defaultPrefix, fsc));
                writer.writeEndElement();
                fscCount++;
            }
            while (fscCount-- > 0) {
                writer.writeEndElement();
            }
        }
        writer.writeEndElement();

        writer.writeStartElement(defaultPrefix, "Reason", ns);
        writer.writeStartElement(defaultPrefix, "Text", ns);
        String lang = f.getLang();
        if (StringUtils.isEmpty(lang)) {
            lang = getLangCode();
        }
        writer.writeAttribute("xml", "http://www.w3.org/XML/1998/namespace", "lang", lang);
        writer.writeCharacters(getFaultMessage(message, fault));
        writer.writeEndElement();
        writer.writeEndElement();

        if (fault.getRole() != null) {
            writer.writeStartElement(defaultPrefix, "Role", ns);
            writer.writeCharacters(fault.getRole());
            writer.writeEndElement();
        }

        prepareStackTrace(message, fault);

        if (fault.hasDetails()) {
            Element detail = fault.getDetail();
            writer.writeStartElement(defaultPrefix, "Detail", ns);

            Node node = detail.getFirstChild();
            while (node != null) {
                StaxUtils.writeNode(node, writer, true);
                node = node.getNextSibling();
            }

            // Details
            writer.writeEndElement();
        }

        // Fault
        writer.writeEndElement();
    } catch (Exception xe) {
        LOG.log(Level.WARNING, "XML_WRITE_EXC", xe);
        throw f;
    }
}
 
Example 20
Source File: ADMRemoteStore.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Creates multiple XML documents encapsulated in a single one. 
 * 
 * @param res       WebScriptResponse
 * @param store       String
 * @param in       XML document containing multiple document contents to write
 */
@Override
protected void createDocuments(WebScriptResponse res, String store, InputStream in)
{
    try
    {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
        Document document;
        document = documentBuilder.parse(in);
        Element docEl = document.getDocumentElement();
        Transformer transformer = ADMRemoteStore.this.transformer.get();
        for (Node n = docEl.getFirstChild(); n != null; n = n.getNextSibling())
        {
            if (!(n instanceof Element))
            {
                continue;
            }
            final String path = ((Element) n).getAttribute("path");
            
            // Turn the first element child into a document
            Document doc = documentBuilder.newDocument();
            Node child;
            for (child = n.getFirstChild(); child != null ; child=child.getNextSibling())
            {
               if (child instanceof Element)
               {
                   doc.appendChild(doc.importNode(child, true));
                   break;
               }
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream(512);
            transformer.transform(new DOMSource(doc), new StreamResult(out));
            out.close();
            
            writeDocument(path, new ByteArrayInputStream(out.toByteArray()));
        }
    }
    catch (AccessDeniedException ae)
    {
        res.setStatus(Status.STATUS_UNAUTHORIZED);
        throw ae;
    }
    catch (FileExistsException feeErr)
    {
        res.setStatus(Status.STATUS_CONFLICT);
        throw feeErr;
    }
    catch (Exception e)
    {
        // various annoying checked SAX/IO exceptions related to XML processing can be thrown
        // none of them should occur if the XML document is well formed
        logger.error(e);
        res.setStatus(Status.STATUS_INTERNAL_SERVER_ERROR);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    }
}