List of usage examples for org.w3c.dom DocumentFragment appendChild
public Node appendChild(Node newChild) throws DOMException;
newChild
to the end of the list of children of this node. From source file:org.ambraproject.service.article.FetchArticleServiceImpl.java
/** * Get references for a given article/*from ww w .j ava 2 s. c om*/ * * @param doc article xml * @return references */ public ArrayList<CitationReference> getReferences(Document doc) { ArrayList<CitationReference> list = new ArrayList<CitationReference>(); if (doc == null) { return list; } try { NodeList refList = getReferenceNodes(doc); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression typeExpr = xpath.compile("//citation | //nlm-citation | //element-citation"); XPathExpression titleExpr = xpath.compile("//article-title"); XPathExpression authorsExpr = xpath.compile("//person-group[@person-group-type='author']/name"); XPathExpression journalExpr = xpath.compile("//source"); XPathExpression volumeExpr = xpath.compile("//volume"); XPathExpression numberExpr = xpath.compile("//label"); XPathExpression fPageExpr = xpath.compile("//fpage"); XPathExpression lPageExpr = xpath.compile("//lpage"); XPathExpression yearExpr = xpath.compile("//year"); XPathExpression publisherExpr = xpath.compile("//publisher-name"); for (int i = 0; i < refList.getLength(); i++) { Node refNode = refList.item(i); CitationReference citation = new CitationReference(); DocumentFragment df = doc.createDocumentFragment(); df.appendChild(refNode); // citation type Object resultObj = typeExpr.evaluate(df, XPathConstants.NODE); Node resultNode = (Node) resultObj; if (resultNode != null) { String citationType = getCitationType(resultNode); if (citationType != null) { citation.setCitationType(citationType); } } // title resultObj = titleExpr.evaluate(df, XPathConstants.NODE); resultNode = (Node) resultObj; if (resultNode != null) { citation.setTitle(resultNode.getTextContent()); } // authors resultObj = authorsExpr.evaluate(df, XPathConstants.NODESET); NodeList resultNodeList = (NodeList) resultObj; ArrayList<String> authors = new ArrayList<String>(); for (int j = 0; j < resultNodeList.getLength(); j++) { Node nameNode = resultNodeList.item(j); NodeList namePartList = nameNode.getChildNodes(); String surName = ""; String givenName = ""; for (int k = 0; k < namePartList.getLength(); k++) { Node namePartNode = namePartList.item(k); if (namePartNode.getNodeName().equals("surname")) { surName = namePartNode.getTextContent(); } else if (namePartNode.getNodeName().equals("given-names")) { givenName = namePartNode.getTextContent(); } } authors.add(givenName + " " + surName); } citation.setAuthors(authors); // journal title resultObj = journalExpr.evaluate(df, XPathConstants.NODE); resultNode = (Node) resultObj; if (resultNode != null) { citation.setJournalTitle(resultNode.getTextContent()); } // volume resultObj = volumeExpr.evaluate(df, XPathConstants.NODE); resultNode = (Node) resultObj; if (resultNode != null) { citation.setVolume(resultNode.getTextContent()); } // citation number resultObj = numberExpr.evaluate(df, XPathConstants.NODE); resultNode = (Node) resultObj; if (resultNode != null) { citation.setNumber(resultNode.getTextContent()); } // citation pages String firstPage = null; String lastPage = null; resultObj = fPageExpr.evaluate(df, XPathConstants.NODE); resultNode = (Node) resultObj; if (resultNode != null) { firstPage = resultNode.getTextContent(); } resultObj = lPageExpr.evaluate(df, XPathConstants.NODE); resultNode = (Node) resultObj; if (resultNode != null) { lastPage = resultNode.getTextContent(); } if (firstPage != null) { if (lastPage != null) { citation.setPages(firstPage + "-" + lastPage); } else { citation.setPages(firstPage); } } // citation year resultObj = yearExpr.evaluate(df, XPathConstants.NODE); resultNode = (Node) resultObj; if (resultNode != null) { citation.setYear(resultNode.getTextContent()); } // citation publisher resultObj = publisherExpr.evaluate(df, XPathConstants.NODE); resultNode = (Node) resultObj; if (resultNode != null) { citation.setPublisher(resultNode.getTextContent()); } list.add(citation); } } catch (Exception e) { log.error("Error occurred while gathering the citation references.", e); } return list; }
From source file:org.apache.cocoon.webapps.session.context.RequestSessionContext.java
/** * Get the XML from the request object//from w w w. j av a 2s . c o m */ public DocumentFragment getXML(String path) throws ProcessingException { if (path == null || path.charAt(0) != '/') { throw new ProcessingException("Not a valid XPath: " + path); } path = this.createPath(path); DocumentFragment result = null; NodeList list; try { list = DOMUtil.selectNodeList(this.contextData, path, this.xpathProcessor); } catch (javax.xml.transform.TransformerException localException) { throw new ProcessingException("Exception: " + localException, localException); } if (list != null && list.getLength() > 0) { result = DOMUtil.getOwnerDocument(contextData).createDocumentFragment(); for (int i = 0; i < list.getLength(); i++) { // the found node is either an attribute or an element if (list.item(i).getNodeType() == Node.ATTRIBUTE_NODE) { // if it is an attribute simple create a new text node with the value of the attribute result.appendChild( DOMUtil.getOwnerDocument(contextData).createTextNode(list.item(i).getNodeValue())); } else { // now we have an element // copy all children of this element in the resulting tree NodeList childs = list.item(i).getChildNodes(); if (childs != null) { for (int m = 0; m < childs.getLength(); m++) { result.appendChild( DOMUtil.getOwnerDocument(contextData).importNode(childs.item(m), true)); } } } } } return result; }
From source file:org.apache.cocoon.xml.dom.DOMUtil.java
/** * Get a document fragment from a <code>Reader</code>. * The reader must provide valid XML, but it is allowed that the XML * has more than one root node. This xml is parsed by the * specified parser instance and a DOM DocumentFragment is created. *//*ww w.j ava2 s. com*/ public static DocumentFragment getDocumentFragment(SAXParser parser, Reader stream) throws ProcessingException { DocumentFragment frag = null; Writer writer; Reader reader; boolean removeRoot = true; try { // create a writer, // write the root element, then the input from the // reader writer = new StringWriter(); writer.write(XML_ROOT_DEFINITION); char[] cbuf = new char[16384]; int len; do { len = stream.read(cbuf, 0, 16384); if (len != -1) { writer.write(cbuf, 0, len); } } while (len != -1); writer.write("</root>"); // now test if xml input start with <?xml String xml = writer.toString(); String searchString = XML_ROOT_DEFINITION + "<?xml "; if (xml.startsWith(searchString) == true) { // now remove the surrounding root element xml = xml.substring(XML_ROOT_DEFINITION.length(), xml.length() - 7); removeRoot = false; } reader = new StringReader(xml); InputSource input = new InputSource(reader); DOMBuilder builder = new DOMBuilder(); builder.startDocument(); builder.startElement("", "root", "root", XMLUtils.EMPTY_ATTRIBUTES); IncludeXMLConsumer filter = new IncludeXMLConsumer(builder, builder); parser.parse(input, filter); builder.endElement("", "root", "root"); builder.endDocument(); // Create Document Fragment, remove <root> final Document doc = builder.getDocument(); frag = doc.createDocumentFragment(); final Node root = doc.getDocumentElement().getFirstChild(); root.normalize(); if (removeRoot == false) { root.getParentNode().removeChild(root); frag.appendChild(root); } else { Node child; while (root.hasChildNodes() == true) { child = root.getFirstChild(); root.removeChild(child); frag.appendChild(child); } } } catch (SAXException sax) { throw new ProcessingException("SAXException: " + sax, sax); } catch (IOException ioe) { throw new ProcessingException("IOException: " + ioe, ioe); } return frag; }
From source file:org.apache.nutch.parse.html.HtmlParser.java
private DocumentFragment parseNeko(InputSource input) throws Exception { DOMFragmentParser parser = new DOMFragmentParser(); try {// w ww .j a va 2s . c o m parser.setFeature("http://cyberneko.org/html/features/augmentations", true); parser.setProperty("http://cyberneko.org/html/properties/default-encoding", defaultCharEncoding); parser.setFeature("http://cyberneko.org/html/features/scanner/ignore-specified-charset", true); parser.setFeature("http://cyberneko.org/html/features/balance-tags/ignore-outside-content", false); parser.setFeature("http://cyberneko.org/html/features/balance-tags/document-fragment", true); parser.setFeature("http://cyberneko.org/html/features/report-errors", LOG.isTraceEnabled()); } catch (SAXException e) { } // convert Document to DocumentFragment HTMLDocumentImpl doc = new HTMLDocumentImpl(); doc.setErrorChecking(false); DocumentFragment res = doc.createDocumentFragment(); DocumentFragment frag = doc.createDocumentFragment(); parser.parse(input, frag); res.appendChild(frag); try { while (true) { frag = doc.createDocumentFragment(); parser.parse(input, frag); if (!frag.hasChildNodes()) break; if (LOG.isInfoEnabled()) { LOG.info(" - new frag, " + frag.getChildNodes().getLength() + " nodes."); } res.appendChild(frag); } } catch (Exception x) { x.printStackTrace(LogUtil.getWarnStream(LOG)); } ; return res; }
From source file:org.apache.nutch.store.readable.StoreReadable.java
private DocumentFragment parseNeko(InputSource input) throws Exception { System.out.println("[STORE-READABLE]----------------------------------------------------parseNeko"); DOMFragmentParser parser = new DOMFragmentParser(); try {/*from w w w . ja v a 2s. c om*/ parser.setFeature("http://cyberneko.org/html/features/scanner/allow-selfclosing-iframe", true); parser.setFeature("http://cyberneko.org/html/features/augmentations", true); parser.setProperty("http://cyberneko.org/html/properties/default-encoding", defaultCharEncoding); parser.setFeature("http://cyberneko.org/html/features/scanner/ignore-specified-charset", true); parser.setFeature("http://cyberneko.org/html/features/balance-tags/ignore-outside-content", false); parser.setFeature("http://cyberneko.org/html/features/balance-tags/document-fragment", true); parser.setFeature("http://cyberneko.org/html/features/report-errors", LOG.isTraceEnabled()); } catch (SAXException e) { } // convert Document to DocumentFragment HTMLDocumentImpl doc = new HTMLDocumentImpl(); doc.setErrorChecking(false); DocumentFragment res = doc.createDocumentFragment(); DocumentFragment frag = doc.createDocumentFragment(); parser.parse(input, frag); res.appendChild(frag); try { while (true) { frag = doc.createDocumentFragment(); parser.parse(input, frag); if (!frag.hasChildNodes()) break; if (LOG.isInfoEnabled()) { LOG.info(" - new frag, " + frag.getChildNodes().getLength() + " nodes."); } res.appendChild(frag); } } catch (Exception x) { LOG.error("Failed with the following Exception: ", x); } ; return res; }
From source file:org.apache.ode.jbi.EndpointReferenceContextImpl.java
public EndpointReference resolveEndpointReference(Element epr) { QName elname = new QName(epr.getNamespaceURI(), epr.getLocalName()); if (__log.isDebugEnabled()) { __log.debug("resolveEndpointReference:\n" + prettyPrint(epr)); }// w w w.j a va 2 s .com if (!elname.equals(EndpointReference.SERVICE_REF_QNAME)) throw new IllegalArgumentException( "EPR root element " + elname + " should be " + EndpointReference.SERVICE_REF_QNAME); Document doc = DOMUtils.newDocument(); DocumentFragment fragment = doc.createDocumentFragment(); NodeList children = epr.getChildNodes(); for (int i = 0; i < children.getLength(); ++i) if (children.item(i) instanceof Element) fragment.appendChild(doc.importNode(children.item(i), true)); ServiceEndpoint se = _ode.getContext().resolveEndpointReference(fragment); if (se == null) return null; return new JbiEndpointReference(se); }
From source file:org.apache.ode.jbi.EndpointReferenceContextImpl.java
public EndpointReference convertEndpoint(QName eprType, Element epr) { Document doc = DOMUtils.newDocument(); DocumentFragment fragment = doc.createDocumentFragment(); NodeList children = epr.getChildNodes(); for (int i = 0; i < children.getLength(); ++i) fragment.appendChild(doc.importNode(children.item(i), true)); ServiceEndpoint se = _ode.getContext().resolveEndpointReference(fragment); if (se == null) return null; return new JbiEndpointReference(se, eprType); }
From source file:org.apache.servicemix.jbi.deployer.descriptor.DescriptorFactory.java
/** * Build a jbi descriptor from the specified binary data. * The descriptor is validated against the schema, but no * semantic validation is performed./*from w w w . j a v a 2 s . c o m*/ * * @param bytes hold the content of the JBI descriptor xml document * @return the Descriptor object */ public static Descriptor buildDescriptor(final byte[] bytes) { try { // Validate descriptor SchemaFactory schemaFactory = SchemaFactory.newInstance(XSD_SCHEMA_LANGUAGE); Schema schema = schemaFactory.newSchema(DescriptorFactory.class.getResource(JBI_DESCRIPTOR_XSD)); Validator validator = schema.newValidator(); validator.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { //log.debug("Validation warning on " + url + ": " + exception); } public void error(SAXParseException exception) throws SAXException { //log.info("Validation error on " + url + ": " + exception); } public void fatalError(SAXParseException exception) throws SAXException { throw exception; } }); validator.validate(new StreamSource(new ByteArrayInputStream(bytes))); // Parse descriptor DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.parse(new ByteArrayInputStream(bytes)); Element jbi = doc.getDocumentElement(); Descriptor desc = new Descriptor(); desc.setVersion(Double.parseDouble(getAttribute(jbi, VERSION))); Element child = getFirstChildElement(jbi); if (COMPONENT.equals(child.getLocalName())) { ComponentDesc component = new ComponentDesc(); component.setType(child.getAttribute(TYPE)); component.setComponentClassLoaderDelegation(getAttribute(child, COMPONENT_CLASS_LOADER_DELEGATION)); component.setBootstrapClassLoaderDelegation(getAttribute(child, BOOTSTRAP_CLASS_LOADER_DELEGATION)); List<SharedLibraryList> sls = new ArrayList<SharedLibraryList>(); DocumentFragment ext = null; for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) { if (IDENTIFICATION.equals(e.getLocalName())) { component.setIdentification(readIdentification(e)); } else if (COMPONENT_CLASS_NAME.equals(e.getLocalName())) { component.setComponentClassName(getText(e)); component.setDescription(getAttribute(e, DESCRIPTION)); } else if (COMPONENT_CLASS_PATH.equals(e.getLocalName())) { ClassPath componentClassPath = new ClassPath(); ArrayList<String> l = new ArrayList<String>(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (PATH_ELEMENT.equals(e2.getLocalName())) { l.add(getText(e2)); } } componentClassPath.setPathList(l); component.setComponentClassPath(componentClassPath); } else if (BOOTSTRAP_CLASS_NAME.equals(e.getLocalName())) { component.setBootstrapClassName(getText(e)); } else if (BOOTSTRAP_CLASS_PATH.equals(e.getLocalName())) { ClassPath bootstrapClassPath = new ClassPath(); ArrayList<String> l = new ArrayList<String>(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (PATH_ELEMENT.equals(e2.getLocalName())) { l.add(getText(e2)); } } bootstrapClassPath.setPathList(l); component.setBootstrapClassPath(bootstrapClassPath); } else if (SHARED_LIBRARY.equals(e.getLocalName())) { SharedLibraryList sl = new SharedLibraryList(); sl.setName(getText(e)); sl.setVersion(getAttribute(e, VERSION)); sls.add(sl); } else { if (ext == null) { ext = doc.createDocumentFragment(); } ext.appendChild(e); } } component.setSharedLibraries(sls.toArray(new SharedLibraryList[sls.size()])); if (ext != null) { InstallationDescriptorExtension descriptorExtension = new InstallationDescriptorExtension(); descriptorExtension.setDescriptorExtension(ext); component.setDescriptorExtension(descriptorExtension); } desc.setComponent(component); } else if (SHARED_LIBRARY.equals(child.getLocalName())) { SharedLibraryDesc sharedLibrary = new SharedLibraryDesc(); sharedLibrary.setClassLoaderDelegation(getAttribute(child, CLASS_LOADER_DELEGATION)); sharedLibrary.setVersion(getAttribute(child, VERSION)); for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) { if (IDENTIFICATION.equals(e.getLocalName())) { sharedLibrary.setIdentification(readIdentification(e)); } else if (SHARED_LIBRARY_CLASS_PATH.equals(e.getLocalName())) { ClassPath sharedLibraryClassPath = new ClassPath(); ArrayList<String> l = new ArrayList<String>(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (PATH_ELEMENT.equals(e2.getLocalName())) { l.add(getText(e2)); } } sharedLibraryClassPath.setPathList(l); sharedLibrary.setSharedLibraryClassPath(sharedLibraryClassPath); } } desc.setSharedLibrary(sharedLibrary); } else if (SERVICE_ASSEMBLY.equals(child.getLocalName())) { ServiceAssemblyDesc serviceAssembly = new ServiceAssemblyDesc(); ArrayList<ServiceUnitDesc> sus = new ArrayList<ServiceUnitDesc>(); for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) { if (IDENTIFICATION.equals(e.getLocalName())) { serviceAssembly.setIdentification(readIdentification(e)); } else if (SERVICE_UNIT.equals(e.getLocalName())) { ServiceUnitDesc su = new ServiceUnitDesc(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (IDENTIFICATION.equals(e2.getLocalName())) { su.setIdentification(readIdentification(e2)); } else if (TARGET.equals(e2.getLocalName())) { Target target = new Target(); for (Element e3 = getFirstChildElement(e2); e3 != null; e3 = getNextSiblingElement( e3)) { if (ARTIFACTS_ZIP.equals(e3.getLocalName())) { target.setArtifactsZip(getText(e3)); } else if (COMPONENT_NAME.equals(e3.getLocalName())) { target.setComponentName(getText(e3)); } } su.setTarget(target); } } sus.add(su); } else if (CONNECTIONS.equals(e.getLocalName())) { Connections connections = new Connections(); ArrayList<Connection> cns = new ArrayList<Connection>(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (CONNECTION.equals(e2.getLocalName())) { Connection cn = new Connection(); for (Element e3 = getFirstChildElement(e2); e3 != null; e3 = getNextSiblingElement( e3)) { if (CONSUMER.equals(e3.getLocalName())) { Consumer consumer = new Consumer(); consumer.setInterfaceName(readAttributeQName(e3, INTERFACE_NAME)); consumer.setServiceName(readAttributeQName(e3, SERVICE_NAME)); consumer.setEndpointName(getAttribute(e3, ENDPOINT_NAME)); cn.setConsumer(consumer); } else if (PROVIDER.equals(e3.getLocalName())) { Provider provider = new Provider(); provider.setServiceName(readAttributeQName(e3, SERVICE_NAME)); provider.setEndpointName(getAttribute(e3, ENDPOINT_NAME)); cn.setProvider(provider); } } cns.add(cn); } } connections.setConnections(cns.toArray(new Connection[cns.size()])); serviceAssembly.setConnections(connections); } } serviceAssembly.setServiceUnits(sus.toArray(new ServiceUnitDesc[sus.size()])); desc.setServiceAssembly(serviceAssembly); } else if (SERVICES.equals(child.getLocalName())) { Services services = new Services(); services.setBindingComponent( Boolean.valueOf(getAttribute(child, BINDING_COMPONENT)).booleanValue()); ArrayList<Provides> provides = new ArrayList<Provides>(); ArrayList<Consumes> consumes = new ArrayList<Consumes>(); for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) { if (PROVIDES.equals(e.getLocalName())) { Provides p = new Provides(); p.setInterfaceName(readAttributeQName(e, INTERFACE_NAME)); p.setServiceName(readAttributeQName(e, SERVICE_NAME)); p.setEndpointName(getAttribute(e, ENDPOINT_NAME)); provides.add(p); } else if (CONSUMES.equals(e.getLocalName())) { Consumes c = new Consumes(); c.setInterfaceName(readAttributeQName(e, INTERFACE_NAME)); c.setServiceName(readAttributeQName(e, SERVICE_NAME)); c.setEndpointName(getAttribute(e, ENDPOINT_NAME)); c.setLinkType(getAttribute(e, LINK_TYPE)); consumes.add(c); } } services.setProvides(provides.toArray(new Provides[provides.size()])); services.setConsumes(consumes.toArray(new Consumes[consumes.size()])); desc.setServices(services); } checkDescriptor(desc); return desc; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.servicemix.jbi.runtime.impl.ServiceEndpointImpl.java
public DocumentFragment getAsReference(QName operationName) { try {/*from ww w. ja v a 2 s.c o m*/ Document doc = DOMUtil.newDocument(); DocumentFragment fragment = doc.createDocumentFragment(); Element epr = doc.createElementNS(JBI_NAMESPACE, JBI_PREFIX + JBI_ENDPOINT_REFERENCE); epr.setAttributeNS(XMLNS_NAMESPACE, "xmlns:sns", getServiceName().getNamespaceURI()); epr.setAttributeNS(JBI_NAMESPACE, JBI_PREFIX + JBI_SERVICE_NAME, "sns:" + getServiceName().getLocalPart()); epr.setAttributeNS(JBI_NAMESPACE, JBI_PREFIX + JBI_ENDPOINT_NAME, getEndpointName()); fragment.appendChild(epr); return fragment; } catch (Exception e) { LOG.warn("Unable to create reference for ServiceEndpoint " + this, e); return null; } }
From source file:org.apache.ws.security.saml.ext.OpenSAMLUtil.java
/** * Convert a SAML Assertion from a XMLObject to a DOM Element * * @param xmlObject of type XMLObject//from w ww . jav a 2 s . c o m * @param doc of type Document * @param signObject whether to sign the XMLObject during marshalling * @return Element * @throws MarshallingException * @throws SignatureException */ public static Element toDom(XMLObject xmlObject, Document doc, boolean signObject) throws WSSecurityException { Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject); Element element = null; DocumentFragment frag = doc == null ? null : doc.createDocumentFragment(); try { if (frag != null) { while (doc.getFirstChild() != null) { frag.appendChild(doc.removeChild(doc.getFirstChild())); } } try { if (doc == null) { element = marshaller.marshall(xmlObject); } else { element = marshaller.marshall(xmlObject, doc); } } catch (MarshallingException ex) { throw new WSSecurityException("Error marshalling a SAML assertion", ex); } if (signObject) { signXMLObject(xmlObject); } } finally { if (frag != null) { while (doc.getFirstChild() != null) { doc.removeChild(doc.getFirstChild()); } doc.appendChild(frag); } } return element; }