List of usage examples for org.dom4j Element getNamespace
Namespace getNamespace();
Namespace
of this element if one exists otherwise Namespace.NO_NAMESPACE
is returned. From source file:org.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller.java
License:Apache License
/** * Check the element for the following OPC compliance rules: * //w w w.j a v a 2s. c o m * Rule M4.2: A format consumer shall consider the use of the Markup * Compatibility namespace to be an error. * * Rule M4.3: Producers shall not create a document element that contains * refinements to the Dublin Core elements, except for the two specified in * the schema: <dcterms:created> and <dcterms:modified> Consumers shall * consider a document element that violates this constraint to be an error. * * Rule M4.4: Producers shall not create a document element that contains * the xml:lang attribute. Consumers shall consider a document element that * violates this constraint to be an error. * * Rule M4.5: Producers shall not create a document element that contains * the xsi:type attribute, except for a <dcterms:created> or * <dcterms:modified> element where the xsi:type attribute shall be present * and shall hold the value dcterms:W3CDTF, where dcterms is the namespace * prefix of the Dublin Core namespace. Consumers shall consider a document * element that violates this constraint to be an error. */ public void checkElementForOPCCompliance(Element el) throws InvalidFormatException { // Check the current element List declaredNamespaces = el.declaredNamespaces(); Iterator itNS = declaredNamespaces.iterator(); while (itNS.hasNext()) { Namespace ns = (Namespace) itNS.next(); // Rule M4.2 if (ns.getURI().equals(PackageNamespaces.MARKUP_COMPATIBILITY)) throw new InvalidFormatException( "OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error."); } // Rule M4.3 if (el.getNamespace().getURI().equals(PackageProperties.NAMESPACE_DCTERMS) && !(el.getName().equals(KEYWORD_CREATED) || el.getName().equals(KEYWORD_MODIFIED))) throw new InvalidFormatException( "OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: <dcterms:created> and <dcterms:modified> Consumers shall consider a document element that violates this constraint to be an error."); // Rule M4.4 if (el.attribute(new QName("lang", namespaceXML)) != null) throw new InvalidFormatException( "OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error."); // Rule M4.5 if (el.getNamespace().getURI().equals(PackageProperties.NAMESPACE_DCTERMS)) { // DCTerms namespace only use with 'created' and 'modified' elements String elName = el.getName(); if (!(elName.equals(KEYWORD_CREATED) || elName.equals(KEYWORD_MODIFIED))) throw new InvalidFormatException("Namespace error : " + elName + " shouldn't have the following naemspace -> " + PackageProperties.NAMESPACE_DCTERMS); // Check for the 'xsi:type' attribute Attribute typeAtt = el.attribute(new QName("type", namespaceXSI)); if (typeAtt == null) throw new InvalidFormatException("The element '" + elName + "' must have the '" + namespaceXSI.getPrefix() + ":type' attribute present !"); // Check for the attribute value => 'dcterms:W3CDTF' if (!typeAtt.getValue().equals("dcterms:W3CDTF")) throw new InvalidFormatException("The element '" + elName + "' must have the '" + namespaceXSI.getPrefix() + ":type' attribute with the value 'dcterms:W3CDTF' !"); } // Check its children Iterator itChildren = el.elementIterator(); while (itChildren.hasNext()) checkElementForOPCCompliance((Element) itChildren.next()); }
From source file:org.openxml4j.opc.signature.RelationshipTransform.java
License:Apache License
@SuppressWarnings("unchecked") public static void RemoveAllNameSpacesExceptRelationship(Element elem) { // if the default namespace is not correct or if it has a prefix // fix it by setting to correct value without prefix if (elem.getNamespace().getStringValue() != PackageNamespaces.RELATIONSHIPS || elem.getNamespace().getPrefix() != "") { elem.setQName(new QName(elem.getName(), DocumentFactory.getInstance().createNamespace("", PackageNamespaces.RELATIONSHIPS))); }/*w w w .j a v a 2 s .c o m*/ // remove all additional namespace declarations List<Namespace> additionalNameSpaces = elem.additionalNamespaces(); for (Namespace nms : additionalNameSpaces) { elem.remove(nms); } }
From source file:org.orbeon.oxf.processor.tamino.dom4j.TDOM4JXMLOutputter.java
License:Open Source License
/** * <p>// ww w .j a va2 s . co m * This will handle printing out an <code>{@link Element}</code>, * its <code>{@link Attribute}</code>s, and its value. * </p> * * @param element <code>Element</code> to output. * @param out <code>Writer</code> to write to. * @param indent <code>int</code> level of indention. * @param namespaces <code>List</code> stack of Namespaces in scope. */ protected void printElement(Element element, Writer out, int indentLevel, TDOM4JNamespaceStack namespaces) throws IOException { List mixedContent = element.elements(); boolean empty = mixedContent.size() == 0; boolean stringOnly = !empty && mixedContent.size() == 1 && mixedContent.get(0) instanceof String; // Print beginning element tag /* maybe the doctype, xml declaration, and processing instructions should only break before and not after; then this check is unnecessary, or maybe the println should only come after and never before. Then the output always ends with a newline */ indent(out, indentLevel); // Print the beginning of the tag plus attributes and any // necessary namespace declarations out.write("<"); out.write(element.getQualifiedName()); int previouslyDeclaredNamespaces = namespaces.size(); Namespace ns = element.getNamespace(); // Add namespace decl only if it's not the XML namespace and it's // not the NO_NAMESPACE with the prefix "" not yet mapped // (we do output xmlns="" if the "" prefix was already used and we // need to reclaim it for the NO_NAMESPACE) if (ns != Namespace.XML_NAMESPACE && !(ns == Namespace.NO_NAMESPACE && namespaces.getURI("") == null)) { String prefix = ns.getPrefix(); String uri = namespaces.getURI(prefix); if (!ns.getURI().equals(uri)) { // output a new namespace decl namespaces.push(ns); printNamespace(ns, out); } } // Print out additional namespace declarations List additionalNamespaces = element.additionalNamespaces(); if (additionalNamespaces != null) { for (int i = 0; i < additionalNamespaces.size(); i++) { Namespace additional = (Namespace) additionalNamespaces.get(i); String prefix = additional.getPrefix(); String uri = namespaces.getURI(prefix); if (!additional.getURI().equals(uri)) { namespaces.push(additional); printNamespace(additional, out); } } } printAttributes(element.attributes(), element, out, namespaces); // handle "" string same as empty if (stringOnly) { String elementText = trimText ? element.getTextTrim() : element.getText(); if (elementText == null || elementText.equals("")) { empty = true; } } if (empty) { // Simply close up if (!expandEmptyElements) { out.write(" />"); } else { out.write("></"); out.write(element.getQualifiedName()); out.write(">"); } maybePrintln(out); } else { // we know it's not null or empty from above out.write(">"); if (stringOnly) { // if string only, print content on same line as tags printElementContent(element, out, indentLevel, namespaces, mixedContent); } else { maybePrintln(out); printElementContent(element, out, indentLevel, namespaces, mixedContent); indent(out, indentLevel); } out.write("</"); out.write(element.getQualifiedName()); out.write(">"); maybePrintln(out); } // remove declared namespaces from stack while (namespaces.size() > previouslyDeclaredNamespaces) { namespaces.pop(); } }
From source file:org.orbeon.oxf.processor.tamino.dom4j.TDOM4JXMLOutputter.java
License:Open Source License
/** ** Gets all the declared namespaces starting at the given element and accumulates the detected namespaces ** within the given namespace stack. The given namespace stack is also returned as the result. ** Please note, that this method has been added for the purpose that not always all given namespaces ** are serialized if they are already given for an ancestor. **///w ww. ja v a 2 s .c om private TDOM4JNamespaceStack getParentNamespaces(Element element, TDOM4JNamespaceStack namespaces) { if (element == null) return namespaces; if (element.getParent() != null) namespaces = getParentNamespaces(element.getParent(), namespaces); Namespace ns = element.getNamespace(); // Add namespace decl only if it's not the XML namespace and it's // not the NO_NAMESPACE with the prefix "" not yet mapped // (we do output xmlns="" if the "" prefix was already used and we // need to reclaim it for the NO_NAMESPACE) if (ns != Namespace.XML_NAMESPACE && !(ns == Namespace.NO_NAMESPACE && namespaces.getURI("") == null)) { String prefix = ns.getPrefix(); String uri = namespaces.getURI(prefix); // Put a new namespace declaratation into the namespace stack if (!ns.getURI().equals(uri)) { namespaces.push(ns); } } // Add additional namespace declarations if not given yet List additionalNamespaces = element.additionalNamespaces(); if (additionalNamespaces != null) { for (int i = 0; i < additionalNamespaces.size(); i++) { Namespace additional = (Namespace) additionalNamespaces.get(i); String prefix = additional.getPrefix(); String uri = namespaces.getURI(prefix); if (!additional.getURI().equals(uri)) namespaces.push(additional); } } return namespaces; }
From source file:org.sapia.util.xml.confix.Dom4jProcessor.java
License:Open Source License
private Object process(Object aParent, Element anElement, String setterName) throws ProcessingException { String aName = anElement.getName(); if (setterName == null) { setterName = aName;/* w ww. java 2 s . c o m*/ } CreationStatus status = null; try { status = getObjectFactory().newObjectFor(anElement.getNamespace().getPrefix(), anElement.getNamespace().getURI(), aName, aParent); } catch (ObjectCreationException oce) { if (aParent == null) { String aMessage = "Unable to create an object for the element " + anElement; throw new ProcessingException(aMessage, oce); } List children; if ((aParent != null) && (containsMethod("set", aParent, aName) || containsMethod("add", aParent, aName)) && ((children = anElement.elements()).size() == 1)) { Element child = (Element) children.get(0); process(aParent, child, setterName); return aParent; } try { String aValue = anElement.getTextTrim(); invokeSetter(aParent.getClass().getName(), aParent, aName, aValue); return aParent; } catch (ConfigurationException ce) { String aMessage = "Unable to create an object nor to call a setter for the element " + anElement; oce.printStackTrace(); throw new ProcessingException(aMessage, ce); } } String text = anElement.getTextTrim(); if (text.length() > 0) { try { invokeSetter(aName, status.getCreated(), "Text", text); } catch (ConfigurationException ce) { String aMessage = "The object '" + aName + "' does not accept free text"; throw new ProcessingException(aMessage, ce); } } try { // Process the attributes of the DOM element for (Iterator it = anElement.attributeIterator(); it.hasNext();) { Attribute attr = (Attribute) it.next(); invokeSetter(aName, status.getCreated(), attr.getName(), attr.getValue()); } // Process the child elements for (Iterator it = anElement.elementIterator(); it.hasNext();) { Element child = (Element) it.next(); if (status.getCreated() instanceof Dom4jHandlerIF) { ((Dom4jHandlerIF) status.getCreated()).handleElement(child); } else if (status.getCreated() instanceof XMLConsumer) { XMLConsumer cons = (XMLConsumer) status.getCreated(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); XMLWriter writer; try { writer = new XMLWriter(bos, OutputFormat.createPrettyPrint()); } catch (UnsupportedEncodingException e) { throw new ProcessingException("Could not instantiate XMLWriter", e); } try { Element copy = child.createCopy(); copy.setDocument(null); writer.write(DocumentHelper.createDocument(copy)); ByteArrayInputStream in = new ByteArrayInputStream(bos.toByteArray()); InputSource is = new InputSource(in); cons.consume(is); } catch (Exception e) { throw new ProcessingException("Could not pipe content of element: " + child.getQualifiedName() + " to XMLConsumer", e); } } else { process(status.getCreated(), child); } } // before assigning to parent, check if object // implements ObjectCreationCallback. if (status.getCreated() instanceof ObjectCreationCallback) { status._created = ((ObjectCreationCallback) status.getCreated()).onCreate(); } // assign obj to parent through setXXX or addXXX if ((aParent != null) && !status.wasAssigned() && !(status.getCreated() instanceof NullObject)) { assignToParent(aParent, status.getCreated(), setterName); } if (status.getCreated() instanceof NullObject) { return null; } return status.getCreated(); } catch (ConfigurationException ce) { String aMessage = "Unable to process the content of the element " + aName; throw new ProcessingException(aMessage, ce); } }
From source file:org.talend.camel.designer.ui.wizards.export.RouteJavaScriptOSGIForESBManager.java
License:Open Source License
private void handleSpringXml(String targetFilePath, ProcessItem processItem, InputStream springInput, ExportFileResource osgiResource, boolean convertToBP, boolean convertImports) { File targetFile = new File(getTmpFolder() + PATH_SEPARATOR + targetFilePath); try {/*from w w w . j a v a 2 s . co m*/ SAXReader saxReader = new SAXReader(); saxReader.setStripWhitespaceText(false); Document document = saxReader.read(springInput); Element root = document.getRootElement(); if (convertToBP) { if ("blueprint".equals(root.getName())) { formatSchemaLocation(root, false, false); InputStream inputStream = new ByteArrayInputStream(root.asXML().getBytes()); FilesUtils.copyFile(inputStream, targetFile); osgiResource.addResource(FileConstants.BLUEPRINT_FOLDER_NAME, targetFile.toURI().toURL()); return; } String bpPrefix = "bp"; int cnt = 0; while (root.getNamespaceForPrefix(bpPrefix) != null) { bpPrefix = "bp" + (++cnt); } root.setQName(QName.get("blueprint", bpPrefix, BLUEPRINT_NSURI)); } Namespace springCamelNsp = Namespace.get("camel", CAMEL_SPRING_NSURI); boolean addCamel = springCamelNsp.equals(root.getNamespaceForPrefix("camel")); formatSchemaLocation(root, convertToBP, addCamel); for (Iterator<?> i = root.elementIterator("import"); i.hasNext();) { Element ip = (Element) i.next(); Attribute resource = ip.attribute("resource"); URL path = dummyURL(resource.getValue()); for (ResourceDependencyModel resourceModel : RouteResourceUtil .getResourceDependencies(processItem)) { if (matches(path, resourceModel)) { IFile resourceFile = RouteResourceUtil.getSourceFile(resourceModel.getItem()); String cpUrl = adaptedClassPathUrl(resourceModel, convertImports); handleSpringXml(cpUrl, processItem, resourceFile.getContents(), osgiResource, convertImports, convertImports); resource.setValue(IMPORT_RESOURCE_PREFIX + cpUrl); } } if (convertImports) { i.remove(); } } if (CONVERT_CAMEL_CONTEXT) { if (CONVERT_CAMEL_CONTEXT_ALL) { moveNamespace(root, CAMEL_SPRING_NSURI, CAMEL_BLUEPRINT_NSURI); } else { Namespace blueprintCamelNsp = Namespace.get("camel", CAMEL_BLUEPRINT_NSURI); moveNamespace(root, springCamelNsp, blueprintCamelNsp); if (springCamelNsp.equals(root.getNamespaceForPrefix("camel"))) { root.remove(springCamelNsp); root.add(blueprintCamelNsp); } Namespace springCamelDefNsp = Namespace.get(CAMEL_SPRING_NSURI); Namespace blueprintCamelDefNsp = Namespace.get(CAMEL_BLUEPRINT_NSURI); for (Iterator<?> i = root.elementIterator("camelContext"); i.hasNext();) { Element cc = (Element) i.next(); if (springCamelDefNsp.equals(cc.getNamespace())) { moveNamespace(cc, springCamelDefNsp, blueprintCamelDefNsp); } } } } InputStream inputStream = new ByteArrayInputStream(root.asXML().getBytes()); FilesUtils.copyFile(inputStream, targetFile); osgiResource.addResource(adaptedResourceFolderName(targetFilePath, convertToBP), targetFile.toURI().toURL()); } catch (Exception e) { Logger.getAnonymousLogger().log(Level.WARNING, "Custom Spring to OSGi conversion failed. ", e); } finally { try { springInput.close(); } catch (IOException e) { Logger.getAnonymousLogger().log(Level.WARNING, "Unexpected File closing failure. ", e); } } }
From source file:org.talend.camel.designer.ui.wizards.export.RouteJavaScriptOSGIForESBManager.java
License:Open Source License
private static void moveNamespace(Element treeRoot, Namespace oldNsp, Namespace newNsp) { if (treeRoot.getNamespace().equals(oldNsp)) { treeRoot.setQName(QName.get(treeRoot.getName(), newNsp)); treeRoot.remove(oldNsp);/*from w w w . jav a 2s. com*/ } moveNamespaceInChildren(treeRoot, oldNsp, newNsp); }
From source file:org.talend.camel.designer.ui.wizards.export.RouteJavaScriptOSGIForESBManager.java
License:Open Source License
private static void moveNamespaceInChildren(Element treeRoot, Namespace oldNsp, Namespace newNsp) { for (Iterator<?> i = treeRoot.elementIterator(); i.hasNext();) { Element e = (Element) i.next(); if (e.getNamespace().equals(oldNsp)) { e.setQName(QName.get(e.getName(), newNsp)); e.remove(oldNsp);/*from w ww . j a v a 2s . co m*/ } moveNamespaceInChildren(e, oldNsp, newNsp); } }
From source file:org.talend.camel.designer.ui.wizards.export.RouteJavaScriptOSGIForESBManager.java
License:Open Source License
private static void moveNamespace(Element treeRoot, String oldNspURI, String newNspURI) { Namespace oldNsp = treeRoot.getNamespace(); if (oldNspURI.equals(oldNsp.getURI())) { Namespace newNsp = Namespace.get(oldNsp.getPrefix(), newNspURI); treeRoot.setQName(QName.get(treeRoot.getName(), newNsp)); treeRoot.remove(oldNsp);//from ww w. ja v a 2 s . co m } moveNamespaceInChildren(treeRoot, oldNspURI, newNspURI); }
From source file:org.talend.camel.designer.ui.wizards.export.RouteJavaScriptOSGIForESBManager.java
License:Open Source License
private static void moveNamespaceInChildren(Element treeRoot, String oldNspURI, String newNspURI) { for (Iterator<?> i = treeRoot.elementIterator(); i.hasNext();) { Element e = (Element) i.next(); Namespace oldNsp = e.getNamespace(); if (oldNspURI.equals(oldNsp.getURI())) { Namespace newNsp = Namespace.get(oldNsp.getPrefix(), newNspURI); e.setQName(QName.get(e.getName(), newNsp)); e.remove(oldNsp);/*from ww w.j ava2 s .co m*/ } moveNamespaceInChildren(e, oldNspURI, newNspURI); } }