List of usage examples for org.w3c.dom Document createDocumentFragment
public DocumentFragment createDocumentFragment();
DocumentFragment
object. From source file:org.eclipse.ecr.common.xmap.DOMHelper.java
/** * Parses a string containing XML and returns a DocumentFragment containing * the nodes of the parsed XML./*from ww w . j a va 2 s. c o m*/ */ public static void loadFragment(Element el, String fragment) { // Wrap the fragment in an arbitrary element fragment = "<fragment>" + fragment + "</fragment>"; try { // Create a DOM builder and parse the fragment DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document d = factory.newDocumentBuilder().parse(new InputSource(new StringReader(fragment))); Document doc = el.getOwnerDocument(); // Import the nodes of the new document into doc so that they // will be compatible with doc Node node = doc.importNode(d.getDocumentElement(), true); // Create the document fragment node to hold the new nodes DocumentFragment docfrag = doc.createDocumentFragment(); // Move the nodes into the fragment while (node.hasChildNodes()) { el.appendChild(node.removeChild(node.getFirstChild())); } } catch (Exception e) { log.error(e, e); } }
From source file:org.eclipse.swordfish.internal.core.integration.nmr.SwordfishExchangeListener.java
private void processOutgoingRequestHeaders(Exchange exchange) { EndpointMetadata<?> metadata = (EndpointMetadata<?>) exchange .getProperty(EndpointMetadata.ENDPOINT_METADATA); if (metadata == null) { return;/* w ww. j a v a2 s .c o m*/ } DocumentFragment policy = metadata.toXml(); // create wsa:ReplyTo SOAP header containing traded policy Document doc = XmlUtil.getDocumentBuilder().newDocument(); Element replyTo = doc.createElementNS(JbiConstants.WSA_NS, JbiConstants.WSA_REPLY_TO_NAME); replyTo.setPrefix(JbiConstants.WSA_PREFIX); Element addr = doc.createElementNS(JbiConstants.WSA_NS, JbiConstants.WSA_ADDRESS_NAME); addr.setPrefix(JbiConstants.WSA_PREFIX); addr.appendChild(doc.createTextNode(JbiConstants.WSA_ANONYMOUS)); replyTo.appendChild(addr); Element refParams = doc.createElementNS(JbiConstants.WSA_NS, JbiConstants.WSA_REFERENCE_PARAMS_NAME); refParams.setPrefix(JbiConstants.WSA_PREFIX); Node policyNode = doc.importNode(policy, true); refParams.appendChild(policyNode); replyTo.appendChild(refParams); DocumentFragment replyToHeader = doc.createDocumentFragment(); replyToHeader.appendChild(replyTo); Map<QName, DocumentFragment> headers = new HashMap<QName, DocumentFragment>(); QName policyKey = new QName(policy.getFirstChild().getNamespaceURI(), policy.getFirstChild().getLocalName()); headers.put(policyKey, policy); headers.put(JbiConstants.WSA_REPLY_TO_QNAME, replyToHeader); exchange.getIn(false).setHeader(JbiConstants.SOAP_HEADERS, headers); }
From source file:org.eclipse.swordfish.internal.core.util.smx.ServiceMixSupport.java
public static DocumentFragment getEndpointReference(EndpointDescription description) { try {/* w ww . j av a 2 s. c o m*/ Assert.notNull(description); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); Document doc = factory.newDocumentBuilder().newDocument(); Element endpRef = doc.createElementNS(JbiConstants.WSA_NS, "EndpointReference"); endpRef.setPrefix(JbiConstants.WSA_PREFIX); Element address = doc.createElementNS(JbiConstants.WSA_NS, "Address"); address.setPrefix(JbiConstants.WSA_PREFIX); address.appendChild(doc.createTextNode(description.getAddress())); endpRef.appendChild(address); QName serviceName = description.getServiceName(); Element metadata = doc.createElementNS(JbiConstants.WSA_NS, "Metadata"); metadata.setPrefix(JbiConstants.WSA_PREFIX); Element service = doc.createElementNS(JbiConstants.WSA_NS, "ServiceName"); service.setAttribute("EndpointName", description.getName()); service.setPrefix(JbiConstants.WSAW_PREFIX); service.appendChild( doc.createTextNode(serviceName.getNamespaceURI() + "/" + serviceName.getLocalPart())); metadata.appendChild(service); endpRef.appendChild(metadata); doc.appendChild(endpRef); DocumentFragment frag = doc.createDocumentFragment(); frag.appendChild(doc.getDocumentElement()); return frag; } catch (Exception e) { throw new RuntimeException("Unexpected failure of enpoint reference creation", e); } }
From source file:org.jasig.resourceserver.utils.aggr.ResourcesElementsProviderImpl.java
/** * Build XML {@link DocumentFragment} of link and script tags for the specified skin file *//*from ww w. j ava 2 s. c om*/ protected DocumentFragment getResourcesXml(HttpServletRequest request, String skinXml) { final Included includedType = this.getIncludedType(request); DocumentFragment headFragment; if (Included.AGGREGATED == includedType) { headFragment = this.xmlResourcesCache.get(skinXml); if (headFragment != null) { return headFragment; } } final Resources skinResources = this.getResources(request, skinXml); if (skinResources == null) { logger.warn("Could not find skin file " + skinXml); return null; } final Document doc = this.documentBuilder.newDocument(); headFragment = doc.createDocumentFragment(); final String relativeRoot = request.getContextPath() + "/" + FilenameUtils.getPath(skinXml); for (final Css css : skinResources.getCss()) { appendCssNode(request, doc, headFragment, css, relativeRoot); } for (final Js js : skinResources.getJs()) { appendJsNode(request, doc, headFragment, js, relativeRoot); } if (Included.AGGREGATED == includedType) { this.xmlResourcesCache.put(skinXml, headFragment); } return headFragment; }
From source file:org.nuxeo.common.xmap.DOMHelper.java
/** * Parses a string containing XML and returns a DocumentFragment containing * the nodes of the parsed XML./*w w w. j a v a 2 s . com*/ */ public static void loadFragment(Element el, String fragment) { // Wrap the fragment in an arbitrary element fragment = "<fragment>" + fragment + "</fragment>"; try { // Create a DOM builder and parse the fragment DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document d = factory.newDocumentBuilder().parse(new InputSource(new StringReader(fragment))); Document doc = el.getOwnerDocument(); // Import the nodes of the new document into doc so that they // will be compatible with doc Node node = doc.importNode(d.getDocumentElement(), true); // Create the document fragment node to hold the new nodes DocumentFragment docfrag = doc.createDocumentFragment(); // Move the nodes into the fragment while (node.hasChildNodes()) { el.appendChild(node.removeChild(node.getFirstChild())); } } catch (ParserConfigurationException e) { log.error(e, e); } catch (SAXException e) { log.error(e, e); } catch (IOException e) { log.error(e, e); } }
From source file:org.voyanttools.trombone.input.expand.XmlExpander.java
public List<StoredDocumentSource> getExpandedStoredDocumentSources(StoredDocumentSource storedDocumentSource) throws IOException { List<StoredDocumentSource> childStoredDocumentSources = new ArrayList<StoredDocumentSource>(); String xmlDocumentsXpath = parameters.getParameterValue("xmlDocumentsXpath", ""); // no format specified, so let's have a peek at the contents to see if we can determine a sub-format DocumentFormat guessedFormat = DocumentFormat.UNKNOWN; if (parameters.getParameterValue("inputFormat", "").isEmpty()) { InputStream is = null;//from w w w . j a v a 2s . c om try { is = storedDocumentSourceStorage.getStoredDocumentSourceInputStream(storedDocumentSource.getId()); XmlRootExtractor xmlRootExtractor = new XmlRootExtractor(); QName qname = xmlRootExtractor.extractRootElement(is); String name = qname.getLocalPart(); if (name.equals("feed") && qname.getNamespaceURI().toLowerCase().contains("atom")) guessedFormat = DocumentFormat.ATOM; else if (name.equals("TEI")) guessedFormat = DocumentFormat.TEI; else if (name.equals("teiCorpus")) guessedFormat = DocumentFormat.TEICORPUS; else if (name.equals("rss")) guessedFormat = DocumentFormat.RSS; else if (name.equals("EEBO")) guessedFormat = DocumentFormat.EEBODREAM; } finally { if (is != null) is.close(); } } // check to see if we need to set xmlDocumentsXpath using defaults for format if (xmlDocumentsXpath.isEmpty() && (parameters.getParameterValue("inputFormat", "").isEmpty() == false || guessedFormat != DocumentFormat.UNKNOWN)) { if (guessedFormat == DocumentFormat.UNKNOWN) { guessedFormat = DocumentFormat .valueOf(parameters.getParameterValue("inputFormat", "").toUpperCase()); } Properties properties = new Properties(); String resourcePath = "/org/voyanttools/trombone/input-formats/" + guessedFormat.name().toLowerCase() + ".xml"; URL url = this.getClass().getResource(resourcePath); if (url != null) { File file = new File(url.getPath()); if (file.exists()) { FileInputStream in = null; try { in = new FileInputStream(file); properties.loadFromXML(in); } finally { if (in != null) { in.close(); } } } if (properties.containsKey("xmlDocumentsXpath")) { xmlDocumentsXpath = properties.getProperty("xmlDocumentsXpath"); } } } String xmlGroupByXpath = parameters.getParameterValue("xmlGroupByXpath", ""); if (xmlDocumentsXpath.isEmpty()) { childStoredDocumentSources.add(storedDocumentSource); return childStoredDocumentSources; } DocumentMetadata parentMetadata = storedDocumentSource.getMetadata(); String parentId = storedDocumentSource.getId(); String multipleExpandedStoredDocumentSourcesPrefix = DigestUtils .md5Hex(xmlDocumentsXpath + xmlGroupByXpath); childStoredDocumentSources = storedDocumentSourceStorage.getMultipleExpandedStoredDocumentSources(parentId, multipleExpandedStoredDocumentSourcesPrefix); if (childStoredDocumentSources != null && childStoredDocumentSources.isEmpty() == false) { return childStoredDocumentSources; } // for some reason XPathAPI doesn't work properly with the default // XPathFactory, so we'll use Saxon System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_SAXON, "net.sf.saxon.xpath.XPathFactoryImpl"); InputStream inputStream = null; Document doc; try { inputStream = storedDocumentSourceStorage .getStoredDocumentSourceInputStream(storedDocumentSource.getId()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/validation", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setIgnoringComments(true); DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(inputStream); } catch (ParserConfigurationException e) { throw new IOException("Error with XML parser configuration for " + storedDocumentSource, e); } catch (SAXException e) { throw new IOException("Error with XML parsing for " + storedDocumentSource, e); } finally { if (inputStream != null) inputStream.close(); } List<NodeInputSource> nodeInputSources = getChildStoredDocumentSources(doc, xmlDocumentsXpath, parentId, parentMetadata); if (nodeInputSources.isEmpty() == false) { if (xmlGroupByXpath.isEmpty() == false) { Map<String, List<NodeInputSource>> groupedNodeInputSources = new HashMap<String, List<NodeInputSource>>(); for (NodeInputSource nodeInputSource : nodeInputSources) { List<String> keys; try { Node fragment = doc.createDocumentFragment(); fragment.appendChild(nodeInputSource.node); keys = XPathAPI.selectNodeListAsStrings(fragment, xmlGroupByXpath); } catch (XPathException e) { throw new IllegalArgumentException("Unable to use this XPath: " + xmlGroupByXpath, e); } if (keys.isEmpty() == false) { String key = StringUtils.join(keys, " "); if (groupedNodeInputSources.containsKey(key) == false) { groupedNodeInputSources.put(key, new ArrayList<NodeInputSource>()); } groupedNodeInputSources.get(key).add(nodeInputSource); } } for (Map.Entry<String, List<NodeInputSource>> mappedNodeInputSources : groupedNodeInputSources .entrySet()) { List<NodeInputSource> mappedNodeInputSourcesList = mappedNodeInputSources.getValue(); // if (mappedNodeInputSourcesList.size()==1) { // just one, so use it // childStoredDocumentSources.add(getStoredDocumentSource(mappedNodeInputSourcesList.get(0))); // } // else { // multiple, we need to wrap with root node String key = mappedNodeInputSources.getKey(); Node newParentNode = doc.getDocumentElement().cloneNode(false); for (NodeInputSource nodeInputSource : mappedNodeInputSourcesList) { newParentNode.appendChild(nodeInputSource.node); } NodeInputSource newNodeInputSource = getChildStoredDocumentSource(newParentNode, parentId, parentMetadata, parentId + ";group:" + key); newNodeInputSource.documentMetadata.setTitle(key); childStoredDocumentSources.add(getStoredDocumentSource(newNodeInputSource)); // } } } else { for (NodeInputSource nodeInputSource : nodeInputSources) { childStoredDocumentSources.add(getStoredDocumentSource(nodeInputSource)); } } } // each node is a separate document // if (xmlDocumentsXpaths.length == 1) { // childStoredDocumentSources.addAll(getChildStoredDocumentSources( // doc, xmlDocumentsXpaths[0], parentId, parentMetadata)); // } // // // each xpath is a separate document // else { // childStoredDocumentSources.addAll(getChildStoredDocumentSources( // doc, xmlDocumentsXpaths, parentId, parentMetadata)); // } storedDocumentSourceStorage.setMultipleExpandedStoredDocumentSources(parentId, childStoredDocumentSources, multipleExpandedStoredDocumentSourcesPrefix); return childStoredDocumentSources; }
From source file:sf.net.experimaestro.utils.JSUtils.java
public static Object toDOM(Scriptable scope, Object object, OptionalDocument document) { // Unwrap if needed (if this is not a JSBaseObject) if (object instanceof Wrapper && !(object instanceof JSBaseObject)) object = ((Wrapper) object).unwrap(); // It is already a DOM node if (object instanceof Node) return object; if (object instanceof XMLObject) { final XMLObject xmlObject = (XMLObject) object; String className = xmlObject.getClassName(); if (className.equals("XMLList")) { LOGGER.debug("Transforming from XMLList [%s]", object); final Object[] ids = xmlObject.getIds(); if (ids.length == 1) return toDOM(scope, xmlObject.get((Integer) ids[0], xmlObject), document); Document doc = XMLUtils.newDocument(); DocumentFragment fragment = doc.createDocumentFragment(); for (int i = 0; i < ids.length; i++) { Node node = (Node) toDOM(scope, xmlObject.get((Integer) ids[i], xmlObject), document); if (node instanceof Document) node = ((Document) node).getDocumentElement(); fragment.appendChild(doc.adoptNode(node)); }//from w ww . jav a 2s . c o m return fragment; } // XML node if (className.equals("XML")) { // FIXME: this strips all whitespaces! Node node = XMLLibImpl.toDomNode(object); LOGGER.debug("Got node from JavaScript [%s / %s] from [%s]", node.getClass(), XMLUtils.toStringObject(node), object.toString()); if (node instanceof Document) node = ((Document) node).getDocumentElement(); node = document.get().adoptNode(node.cloneNode(true)); return node; } throw new RuntimeException(format("Not implemented: convert %s to XML", className)); } if (object instanceof NativeArray) { NativeArray array = (NativeArray) object; ArrayNodeList list = new ArrayNodeList(); for (Object x : array) { Object o = toDOM(scope, x, document); if (o instanceof Node) list.add(document.cloneAndAdopt((Node) o)); else { for (Node node : XMLUtils.iterable((NodeList) o)) { list.add(document.cloneAndAdopt(node)); } } } return list; } if (object instanceof NativeObject) { // JSON case: each key of the JS object is an XML element NativeObject json = (NativeObject) object; ArrayNodeList list = new ArrayNodeList(); for (Object _id : json.getIds()) { String jsQName = JSUtils.toString(_id); if (jsQName.length() == 0) { final Object seq = toDOM(scope, json.get(jsQName, json), document); for (Node node : XMLUtils.iterable(seq)) { if (node instanceof Document) node = ((Document) node).getDocumentElement(); list.add(document.cloneAndAdopt(node)); } } else if (jsQName.charAt(0) == '@') { final QName qname = QName.parse(jsQName.substring(1), null, new JSNamespaceBinder(scope)); Attr attribute = document.get().createAttributeNS(qname.getNamespaceURI(), qname.getLocalPart()); StringBuilder sb = new StringBuilder(); for (Node node : XMLUtils.iterable(toDOM(scope, json.get(jsQName, json), document))) { sb.append(node.getTextContent()); } attribute.setTextContent(sb.toString()); list.add(attribute); } else { final QName qname = QName.parse(jsQName, null, new JSNamespaceBinder(scope)); Element element = qname.hasNamespace() ? document.get().createElementNS(qname.getNamespaceURI(), qname.getLocalPart()) : document.get().createElement(qname.getLocalPart()); list.add(element); final Object seq = toDOM(scope, json.get(jsQName, json), document); for (Node node : XMLUtils.iterable(seq)) { if (node instanceof Document) node = ((Document) node).getDocumentElement(); node = document.get().adoptNode(node.cloneNode(true)); if (node.getNodeType() == Node.ATTRIBUTE_NODE) element.setAttributeNodeNS((Attr) node); else element.appendChild(node); } } } return list; } if (object instanceof Double) { // Wrap a double final Double x = (Double) object; if (x.longValue() == x.doubleValue()) return document.get().createTextNode(Long.toString(x.longValue())); return document.get().createTextNode(Double.toString(x)); } if (object instanceof Integer) { return document.get().createTextNode(Integer.toString((Integer) object)); } if (object instanceof CharSequence) { return document.get().createTextNode(object.toString()); } if (object instanceof UniqueTag) throw new XPMRuntimeException("Undefined cannot be converted to XML", object.getClass()); if (object instanceof JSNode) { Node node = ((JSNode) object).getNode(); if (document.has()) { if (node instanceof Document) node = ((Document) node).getDocumentElement(); return document.get().adoptNode(node); } return node; } if (object instanceof JSNodeList) { return ((JSNodeList) object).getList(); } if (object instanceof Scriptable) { ((Scriptable) object).getDefaultValue(String.class); } // By default, convert to string return document.get().createTextNode(object.toString()); }