List of usage examples for org.jdom2 Namespace getNamespace
public static Namespace getNamespace(final String uri)
Namespace
for the supplied URI, and make it usable as a default namespace, as no prefix is supplied. From source file:nl.nn.adapterframework.util.XmlBuilder.java
License:Apache License
public void addAttribute(String name, String value) { if (value != null) { if (name.equalsIgnoreCase("xmlns")) { element.setNamespace(Namespace.getNamespace(value)); } else if (StringUtils.startsWithIgnoreCase(name, "xmlns:")) { String prefix = name.substring(6); element.addNamespaceDeclaration(Namespace.getNamespace(prefix, value)); } else {//w w w . j av a 2s. co m element.setAttribute(new Attribute(name, value)); } } }
From source file:nz.ac.massey.cs.guery.adapters.jungalt.io.graphml.GraphMLReader.java
License:Apache License
@Override public synchronized DirectedGraph<V, E> readGraph() throws GraphIOException { Map<String, V> vertices = new HashMap<String, V>(); Map<String, E> edges = new HashMap<String, E>(); // parse/*from ww w .j a v a 2s. c o m*/ SAXBuilder builder = new SAXBuilder(); try { Namespace NS_GRAPHML = Namespace.getNamespace("http://graphml.graphdrawing.org/xmlns"); Document doc = builder.build(reader); Element root = doc.getRootElement(); assert "graphml".equals(root.getName()); Element eGraph = root.getChild("graph", NS_GRAPHML); for (Object o : eGraph.getChildren("node", NS_GRAPHML)) { if (o instanceof Element) { buildVertex(vertices, (Element) o); } } for (Object o : eGraph.getChildren("edge", NS_GRAPHML)) { if (o instanceof Element) { E e = buildEdge(vertices, (Element) o); if (edges.containsKey(e.getId())) { throw new GraphIOException( "There are two edges with the same id " + e.getId() + " in the graph"); } edges.put(e.getId(), e); } } // during parsing, composite edges can be created which replace simple edges, those simple edges must be removed from the buffer Collection<CompositeEdge<E>> composites = new HashSet<CompositeEdge<E>>(); for (E e : edges.values()) { if (e instanceof CompositeEdge) { composites.add((CompositeEdge) e); } } // now remove for (CompositeEdge<E> ce : composites) { Collection<E> parts = ce.getParts(); for (E part : parts) { edges.remove(part.getId()); } } // TODO: at this stage both the xml doc and the graph are in memory // we could gc the doc before we continue // build graph } catch (Exception e) { throw new GraphIOException(e); } DirectedGraph<V, E> graph = new DirectedSparseGraph<V, E>(); for (V v : vertices.values()) { graph.addVertex(v); } for (E e : edges.values()) { graph.addEdge(e, e.getStart(), e.getEnd()); } return graph; }
From source file:org.apache.roller.planet.util.rome.ContentModuleParser.java
License:Open Source License
public Namespace getContentNamespace() { return Namespace.getNamespace(ContentModule.URI); }
From source file:org.artifactory.version.converter.NamespaceConverter.java
License:Open Source License
@Override @SuppressWarnings({ "unchecked" }) public void convert(Document doc) { // change the xsd uri and schema location String currentXsdUri = ArtifactoryConfigVersion.getCurrent().getXsdUri(); String currentXsdLocation = ArtifactoryConfigVersion.getCurrent().getXsdLocation(); Namespace ns = Namespace.getNamespace(currentXsdUri); Element root = doc.getRootElement(); // Check that schema instance namespace is there before adding schema location... Namespace schemaInstanceNS = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); List<Namespace> namespaces = root.getAdditionalNamespaces(); boolean hasSchemaInstanceNS = false; for (Namespace namespace : namespaces) { // The equality is only on URI so hardcoded prefix does not impact if (namespace.equals(schemaInstanceNS)) { hasSchemaInstanceNS = true;// www .j a v a 2s . c om } } if (!hasSchemaInstanceNS) { root.addNamespaceDeclaration(schemaInstanceNS); } root.setAttribute("schemaLocation", currentXsdUri + " " + currentXsdLocation, schemaInstanceNS); changeNameSpace(root, ns); }
From source file:org.dvlyyon.net.netconf.marshalling.Filter.java
License:Open Source License
/** * Creates a NETCONF XML filter with the specified parameters. Actually constructs the complete XML tree, including all the attributes of * the desired object type and set the xmlFilter member variable. * * @param model The marshaling model. * @param xpathId XPath representing the ID of the object. * @param theClass Class representing the parent object. * @param childClass Class representing the object of interest. * @param delete true if a filter is required for a delete operation. *///from w w w.jav a 2 s . c o m private void createXmlFilter(DataModel model, final String xpathId, final ClassMapping theClass, final ClassMapping childClass, final boolean delete) { m_model = model; Element xml = null; Element current = null; String[] xpathTokens = new String[0]; if (xpathId != null) { xpathTokens = StringUtils.tokenizeToStringArrayQuotes(xpathId, "/"); } //final ArrayList<PathSegment> segments = xpath.getSegments(); final ArrayList<ClassMapping> mappings = getClassHierarchy(theClass); int index = 0; for (String token : xpathTokens) //for (PathSegment seg : segments) { ClassMapping clsMapping = mappings.get(index); Element elem = processToken(token, clsMapping); if (xml == null) { xml = elem; current = elem; } else { current.addContent(elem); current = elem; } index++; } if (childClass != null) { Namespace ns = Namespace.getNamespace(childClass.getXmlNamespace()); // Add the tag for the child class Element elem = new Element(childClass.getXmlTag(), ns); if (current != null) { current.addContent(elem); current = elem; } else { current = elem; xml = elem; } } if (delete) { current.setAttribute("operation", "delete"); } else { // It's not a delete; restrict the set of attributes to the ones we are interested in if (childClass != null) { addAttributeSet(childClass, current); } else { addAttributeSet(theClass, current); } } if (delete) { m_xmlFilter = xml; } else { m_xmlFilter = new Element("filter", s_rpcNs); m_xmlFilter.setAttribute("type", "subtree"); m_xmlFilter.addContent(xml); } if (s_logger.isDebugEnabled()) { s_logger.debug(XmlUtils.toXmlString(m_xmlFilter, true)); } }
From source file:org.dvlyyon.net.netconf.marshalling.Filter.java
License:Open Source License
/** * Given a string representing a path end-point, and the class that we are interested in, converts the attributes specified in the * end-point as XML entities used in a Filter. For example, if you have a path like 'myClass[key1="val1"][key2="val2"]', an XML * node is created for each key and added as a child to the root node called 'myClass'. * * @param pathToken Path end-point (this is a path-segment). * @param theClass Class mapping representing the class we are dealing with. * @return XML node containing Filter XML equivalent of the specified path end-point. *///from w ww . ja va2 s .c o m static Element processToken(final String pathToken, final ClassMapping theClass) //static Element processToken(final PathSegment pathSegment, final ClassMapping theClass) { // in the form elementTag [attribute1="value1"][attribute2="value2"] Element ret = null; //final String[] tokens = StringUtils.tokenizeToStringArray(pathSegment.getTag(), " []"); // ** mike ** final String[] tokens = StringUtils.tokenizeToStringArray(pathToken, " []"); final String[] tokens = StringUtils.tokenizeToStringArrayQuotes(pathToken, "[]"); int index = 0; for (String token : tokens) { Namespace ns = Namespace.getNamespace(theClass.getXmlNamespace()); //Namespace ns = Namespace.getNamespace(pathSegment.getNamespaceUri()); if (index == 0) { ret = new Element(token, ns); } else { // This one is name="value" String name = token.substring(0, token.indexOf('=')).trim(); // Actually we should look for the "" (and not assume lack of spaces) String value = token.substring(token.indexOf('\"') + 1, token.lastIndexOf('\"')); // TODO: Deal with the possibility that the KEY ATTRIBUTE has a different namespace - a bit paranoid here Element attrib = new Element(name, ns); attrib.setText(value); ret.addContent(attrib); } index++; } return ret; }
From source file:org.dvlyyon.net.netconf.marshalling.Filter.java
License:Open Source License
/** * /* w w w . j a va2 s . co m*/ * @param classMapping * @param root */ private void addAttributeSet(final ClassMapping classMapping, final Element root) { Namespace classNs = Namespace.getNamespace(classMapping.getXmlNamespace()); for (AttributeMapping am : classMapping.getAttributeMappings()) { Namespace ns = classNs; if (am.getXmlNamespace() != null) { ns = Namespace.getNamespace(am.getXmlNamespace()); } if (!am.isSynthetic() || (am.isSynthetic() && am.getType() == AttributeMapping.Type.Primitive_Boolean)) { Element attrib = new Element(am.getXmlTag(), ns); root.addContent(attrib); } else if (am.getType() == AttributeMapping.Type.Class) { // It's a synthetic choice or case or union - recurse down the tree until you hit anything non-synthetic and add it Path childPath = Path.fromString(classMapping.getXmlPath()); PathSegment ps = new PathSegment(classMapping.getXmlNamespace(), classMapping.getXmlTag()); childPath.addSegment(ps); ps = new PathSegment(am.getXmlNamespace(), am.getXmlTag()); childPath.addSegment(ps); ClassMapping childClass = m_model.getClassMappingByPath(childPath); if (childClass.getType() == ClassMapping.Type.Union) { // A union is treated as just an attribute Element attrib = new Element(am.getXmlTag(), ns); root.addContent(attrib); } else { addAttributeSet(childClass, root); } } } }
From source file:org.dvlyyon.net.netconf.marshalling.NetconfUtil.java
License:Open Source License
/** * Given a POJO, converts it to the corresponding (valid) NETCONF XML, which can then be sent over the wire. * * @param parentXpathOid XPATH representing the path to the parent object of the POJO. * @param oldObject the old POJO, in case the edit operation specified is an update. We need to pass this in, since * there may be a specific need to "unset" attributes that were previously set. * @param object the POJO that needs to be converted to NETOCNF XML. * @param editOperation The type of operation to be performed. * @return XML node representing the data to be sent via NETCONF. * @throws RuntimeException if an error occurred. *//*from ww w. j av a2 s . co m*/ public Element toXml(final Path parentXpathOid, final Object oldObject, final Object object, final EditOperation editOperation) throws RuntimeException { // Create an xpath based upon the parent's OID, my xmltag and my keys Element ret = null; ClassMapping classUnderConsideration = m_model.getClassMappingByName(object.getClass().getName()); if (classUnderConsideration == null) { throw new RuntimeException("Class metadata not found for: " + object.getClass().getName()); } Element current = null; ClassMapping cm = classUnderConsideration.getParentClass(); if (cm == null) { s_logger.debug("Parent class metadata not found for: " + object.getClass().getName()); } else { //Namespace ns = Namespace.getNamespace(cm.getXmlNamespace()); final ArrayList<PathSegment> segments = parentXpathOid.getSegments(); final ArrayList<ClassMapping> mappings = Filter.getClassHierarchy(cm); int index = 0; for (PathSegment segment : segments) { ClassMapping theClass = mappings.get(index); Element elem = Filter.processToken(segment.getTag(), theClass); if (ret == null) { ret = elem; current = elem; } else { current.addContent(elem); current = elem; } index++; } } // Now we have got all the XML up to our parent in the hierarchy, now for the class itself Element classElem = new Element(classUnderConsideration.getXmlTag(), Namespace.getNamespace(classUnderConsideration.getXmlNamespace())); // Here is where we set the operation to being create, update or delete if (editOperation == EditOperation.Delete) { classElem.setAttribute("operation", "delete"); } else if (editOperation == EditOperation.Create) { classElem.setAttribute("operation", "create"); } else if (editOperation == EditOperation.Replace) { classElem.setAttribute("operation", "replace"); } else if (editOperation == EditOperation.Merge) { classElem.setAttribute("operation", "merge"); } if (ret == null) { ret = classElem; } else { current.addContent(classElem); } dumpAttributesToXml(classElem, classUnderConsideration, oldObject, object, editOperation); return ret; }
From source file:org.dvlyyon.net.netconf.marshalling.NetconfUtil.java
License:Open Source License
/** * Given an attribute mapping for a class, convert it to NETCONF XML and add them to the root XML node. * * @param am Attribute mappings defining an attribute of the class. * @param classElem Root XML node representing the object. * @param cm ClassMapping representing the class being transformed. * @param oldObject the old POJO, in case the edit operation specified is an update. We need to pass this in, since * there may be a specific need to "unset" attributes that were previously set. * @param object the POJO that needs to be converted to NETOCNF XML. * @param editOperation The type of operation to be performed. * @throws RuntimeException if an error occurred. *//*from w w w . j a va 2 s. c om*/ @SuppressWarnings("unchecked") void dumpAttributeToXml(AttributeMapping am, final Element classElem, final ClassMapping cm, final Object oldObject, final Object object, final EditOperation editOperation) throws RuntimeException { Namespace namespace = Namespace.getNamespace(cm.getXmlNamespace()); Namespace ns = namespace; String attrNs = am.getXmlNamespace(); if (attrNs != null) { ns = Namespace.getNamespace(attrNs); } if (am.isReadOnly()) { // We do not stream read-only values out return; } if (am.getType() == AttributeMapping.Type.Class) { Path childPath = Path.fromString(cm.getXmlPath()); PathSegment ps = new PathSegment(cm.getXmlNamespace(), cm.getXmlTag()); childPath.addSegment(ps); ps = new PathSegment(am.getXmlNamespace(), am.getXmlTag()); childPath.addSegment(ps); ClassMapping childClass = m_model.getClassMappingByPath(childPath); if (childClass == null) { throw new RuntimeException("Class mapping not found for path: " + childPath); } if (childClass.getType() == ClassMapping.Type.Union) { Object childValue = BeanUtil.getDirectFieldValue(am.getJavaMemberName(), object); if (am.isList()) { if (editOperation == EditOperation.Merge && oldObject != null) { List<Object> oldUnions = (List<Object>) BeanUtil.getDirectListValue(am.getJavaMemberName(), oldObject); for (Object oldUnion : oldUnions) { Element unionAttrib = new Element(am.getXmlTag(), ns); unionAttrib.setAttribute("operation", "delete"); // TODO: Optimize later - only dump out the index attributes m_unionChoiceHelper.unionToXml(childClass, oldUnion, unionAttrib); classElem.addContent(unionAttrib); } } // Stick the new ones in List<Object> unionList = (List<Object>) childValue; for (Object unionObject : unionList) { Element attrib = new Element(am.getXmlTag(), ns); m_unionChoiceHelper.unionToXml(childClass, unionObject, attrib); classElem.addContent(attrib); } } else { Element attrib = new Element(am.getXmlTag(), ns); m_unionChoiceHelper.unionToXml(childClass, childValue, attrib); classElem.addContent(attrib); } } else if (childClass.getType() == ClassMapping.Type.Choice) { Object choiceValue = BeanUtil.getDirectFieldValue(am.getJavaMemberName(), object); m_unionChoiceHelper.choiceToXml(cm, childClass, choiceValue, classElem, editOperation); } else if (!am.isList()) { boolean add = false; Object value = BeanUtil.getDirectFieldValue(am.getJavaMemberName(), object); Element childClassElem = new Element(childClass.getXmlTag(), Namespace.getNamespace(childClass.getXmlNamespace())); if (value != null) { childClassElem.setAttribute("operation", "replace"); add = true; dumpAttributesToXml(childClassElem, childClass, null, value, EditOperation.NotApplicable); } else { // Remove the child if there used to be one there originally if (editOperation == EditOperation.Merge && oldObject != null) { Object oldValue = BeanUtil.getDirectFieldValue(am.getJavaMemberName(), oldObject); if (oldValue != null) { childClassElem.setAttribute("operation", "delete"); add = true; } } } if (add) { classElem.addContent(childClassElem); } } else { // Need to delete the old objects first (if there is an old object) if (oldObject != null) { List<Object> oldVos = (List<Object>) BeanUtil.getDirectListValue(am.getJavaMemberName(), oldObject); for (Object vo : oldVos) { Element childClassElem = new Element(childClass.getXmlTag(), Namespace.getNamespace(childClass.getXmlNamespace())); classElem.addContent(childClassElem); childClassElem.setAttribute("operation", "delete"); // TODO: Optimize later - only dump out the index attributes dumpAttributesToXml(childClassElem, childClass, null, vo, EditOperation.Create); } } // Then, add the current ones - aka "create" List<Object> vos = (List<Object>) BeanUtil.getDirectListValue(am.getJavaMemberName(), object); for (Object vo : vos) { Element childClassElem = new Element(childClass.getXmlTag(), Namespace.getNamespace(childClass.getXmlNamespace())); classElem.addContent(childClassElem); childClassElem.setAttribute("operation", "replace"); dumpAttributesToXml(childClassElem, childClass, null, vo, EditOperation.Create); } } } else { // Check for a list here, too (this corresponds to a leaf-list) if (am.isList()) { // Delete all the existing leaf-list attributes if the operation is an edit if (editOperation == EditOperation.Merge && oldObject != null) { List<Object> oldPrimitives = (List<Object>) BeanUtil.getDirectListValue(am.getJavaMemberName(), oldObject); for (Object prim : oldPrimitives) { Element attrib = new Element(am.getXmlTag(), ns); attrib.setAttribute("operation", "delete"); String strVal = am.convertValueToString(prim); if (strVal != null) { attrib.setText(strVal); } classElem.addContent(attrib); } } // Stick the new ones in List<Object> primitives = (List<Object>) BeanUtil.getDirectListValue(am.getJavaMemberName(), object); for (Object prim : primitives) { Element attrib = new Element(am.getXmlTag(), ns); String strVal = am.convertValueToString(prim); if (strVal != null) { attrib.setText(strVal); } classElem.addContent(attrib); } } else { Element targetNode = classElem; boolean add = false; Element attrib = null; ; if (am.isSynthetic() && am.getType() != AttributeMapping.Type.Primitive_Boolean) { // No extra XML node here - just set the content directly (unless it is "empty") attrib = classElem; targetNode = null; } else { attrib = new Element(am.getXmlTag(), ns); } Object value = BeanUtil.getDirectFieldValue(am.getJavaMemberName(), object); if (value != null) { String strVal = am.convertValueToString(value); if (strVal != null) { attrib.setText(strVal); add = true; } } else { // "Unset" the attribute by setting delete = true if (editOperation == EditOperation.Merge && oldObject != null) { Object oldValue = BeanUtil.getDirectFieldValue(am.getJavaMemberName(), oldObject); if (oldValue != null) { attrib.setAttribute("operation", "delete"); add = true; } } } if (add && targetNode != null) { targetNode.addContent(attrib); } } } }
From source file:org.dvlyyon.net.netconf.marshalling.NetconfUtil.java
License:Open Source License
/** * Give the XML node that represents a response from a NETCONF device, extracts and creates the list of POJOs that * correspond to the specified Java class. * * @param root Root node of NETCONF XML returned from a query. * @param cm Class mapping that represents the desired objects. * @param ignoreContainment true to ignore intermediate containers, false to take them into account. * @return List of objects of the desired type, that are contained within the specified node. * @throws RuntimeException if an error occurred. *//*from w w w . j a v a2 s . c o m*/ @SuppressWarnings("unchecked") private List<Object> fromXml(final Element root, ClassMapping cm, final boolean ignoreContainment) throws RuntimeException { List<Object> ret = new ArrayList<Object>(); final Path xmlpath = Path.fromString(cm.getXmlPath()); final String namespace = cm.getXmlNamespace(); if (xmlpath == null) { throw new RuntimeException("XML container not found for class: " + cm.getJavaClassName()); } Element elementToProcess = root; if (!ignoreContainment) { Element current = root; // We are searching from the ROOT node for this class // final String[] xpathTokens = StringUtils.tokenizeToStringArray(xmlpath, "/"); final ArrayList<PathSegment> xpathTokens = xmlpath.getSegments(); int index = 0; //for (String token : xpathTokens) for (PathSegment token : xpathTokens) { current = current.getChild(token.getTag(), Namespace.getNamespace(token.getNamespaceUri())); if (current == null) { // We have gotten only through part of the hierarchy (after which it has apparently ended). // We take this to mean there is no data for the required objects; so return the empty list //throw new RuntimeException("Unexpected XML tag - expected: " + token.getTag() + ", got: null"); s_logger.warn("Unexpected XML tag - expected: " + token.getTag() + ", got: null"); return ret; } index++; } elementToProcess = current; } // Now we are pointing to the PARENT node of the class we are interested in // Get the list of classes that we are looking for String tag = cm.getXmlTag(); List<Element> classes = (List<Element>) elementToProcess.getChildren(tag, Namespace.getNamespace(namespace)); for (Element theClass : classes) { //VersionedObject o = ModelUtil.getInstance().createObject(m_model.getModuleName()+"/"+cd.getName(), m_version); Object o = null; try { Class<?> cls = Class.forName(cm.getJavaClassName()); o = cls.newInstance(); } catch (final Exception ex) { throw new RuntimeException( "Error instantiating class: " + cm.getJavaClassName() + " -- " + ex.getMessage()); } setAttributesFromXml(o, theClass, cm); ret.add(o); } return ret; }