List of usage examples for org.jdom2 Element getNamespaceURI
public String getNamespaceURI()
From source file:es.upm.dit.xsdinferencer.extraction.extractorImpl.TypesExtractorImpl.java
License:Apache License
/** * Recursive method that traverses an element to extract all the possible information from it. * It is recursive because it calls itself for each child of the element (obviously, infinite recursion * is not possible as there are not, or there should not be, parent-child loops). * The index of the current document is necessary in order to add well some information to * the statistics./*from www.j a va 2 s .com*/ * @param documentIndex index of current document * @param element the element to traverse (as a JDOM2 {@link Element}) * @param enclosingComplexType the complex type which will contain the current element */ private void traverseElement(int documentIndex, Element element, String enclosingComplexType) { //Elements in the XSI namespace should be ignored if (element.getNamespaceURI().equalsIgnoreCase(XSI_NAMESPACE_URI)) return; List<String> realPathUnfiltered = getRealPathOfElementUnfiltered(element, configuration, false, solvedNamespaceToPrefixMapping); String realPathFiltered = filterAndJoinRealPath(realPathUnfiltered);//Path for the statistics List<String> typePathUnfiltered = getRealPathOfElementUnfiltered(element, configuration, false, solvedNamespaceToPrefixMapping); List<String> suitablePath = getSuitablePath(typePathUnfiltered);//Path for type name inferencing //First, we will register the information of width and depth //The root is in a level whose width is 1, if we did not do the following, that width would be never registered if (element.isRootElement()) { statistics.registerWidth(documentIndex, 1); } statistics.registerDepth(documentIndex, realPathUnfiltered.size()); int width = element.getChildren().size(); if (width > 0) { statistics.registerWidth(documentIndex, width); } TypeNameInferencer typeNameInferencer = configuration.getTypeNameInferencer(); String complexTypeName = typeNameInferencer.inferTypeName(suitablePath, configuration);//Complex type of this element // //Little workaround that ensures that the same complex type is used // //when the elements on its path are the same (same name and namespace) but some of them // //use different namespace prefixes // List<String> realPathUnfilteredKey=getRealPathOfElementUnfiltered(element, configuration, false, solvedNamespaceToPrefixMapping); // List<String> suitablePathKey=getSuitablePath(realPathUnfilteredKey);//Path for type name inferencing // String complexTypeNameKey = typeNameInferencer.inferTypeName(suitablePathKey, configuration);//Complex type of this element String complexTypeNameKey = complexTypeName; //The complex type object of this element. ComplexType complexType = complexTypes.get(complexTypeNameKey); if (complexType == null) { complexType = new ComplexType(complexTypeName, null, null, null); complexTypes.put(complexTypeNameKey, complexType); //New complex type } complexType.addSourceNodeNamespaceAndName(element.getNamespaceURI(), element.getName()); //Comment processing for (Comment comment : element.getDescendants(Filters.comment())) { if (comment.getParentElement().equals(element)) complexType.getComments().add(comment.getText()); } //Key to find the corresponding SchemaElement //This key is: if the SchemaElement has an enclosing complex type (i.e., it is not a valid root), its name will be: //enclosingComplexType+typeNamesSeparator+elementName //If the element is a suitable root, the key is the name of the element. String schemaElementKey = (!enclosingComplexType.equals("")) ? enclosingComplexType + configuration.getTypeNamesAncestorsSeparator() + element.getName() : element.getName(); if (configuration.getTypeNameInferencer() instanceof NameTypeNameInferencer) { schemaElementKey = element.getName(); //If we use a name-based type inferencer, the key is the name and we avoid problems. } SchemaElement schemaElement = elements.get(element.getNamespaceURI(), schemaElementKey); if (schemaElement == null) { schemaElement = new SchemaElement(element.getName(), element.getNamespaceURI(), complexType);//Complex type already not known. elements.put(element.getNamespaceURI(), schemaElementKey, schemaElement); } boolean wasAlreadyValidRoot = schemaElement.isValidRoot(); schemaElement.setValidRoot(wasAlreadyValidRoot || element.isRootElement()); ComplexTypeStatisticsEntry complexTypeStatisticsEntry = statistics.getComplexTypeInfo().get(complexType); if (complexTypeStatisticsEntry == null) { complexTypeStatisticsEntry = new ComplexTypeStatisticsEntry(xmlDocuments.size()); statistics.getComplexTypeInfo().put(complexType, complexTypeStatisticsEntry); } AttributeListInferencer attributeListInferencer = attributeListInferencers.get(complexTypeName); if (attributeListInferencer == null) { attributeListInferencer = inferencersFactory.getAttributeListInferencerInstance(complexTypeName, configuration, solvedNamespaceToPrefixMapping, statistics); attributeListInferencers.put(complexTypeName, attributeListInferencer); } attributeListInferencer.learnAttributeList(element.getAttributes(), documentIndex); SimpleTypeInferencer simpleTypeInferencer = simpleTypeInferencersOfComplexTypes.get(complexTypeName); if (simpleTypeInferencer == null) { simpleTypeInferencer = inferencersFactory.getSimpleTypeInferencerInstance(complexTypeName, configuration); simpleTypeInferencersOfComplexTypes.put(complexTypeName, simpleTypeInferencer); } simpleTypeInferencer.learnValue(element.getText(), element.getNamespaceURI(), element.getName()); // SchemaElement previousChildSchemaElement=null; //We need to store the previous child in order to add the edge between it and the current child. List<SchemaElement> schemaElementChildren = new ArrayList<>(element.getChildren().size()); for (int i = 0; i < element.getChildren().size(); i++) { Element child = element.getChildren().get(i); traverseElement(documentIndex, child, complexTypeName); String childSchemaElementKey = complexTypeName + configuration.getTypeNamesAncestorsSeparator() + child.getName(); if (configuration.getTypeNameInferencer() instanceof NameTypeNameInferencer) { childSchemaElementKey = child.getName(); // If we use the name-based type name inferencer, the name is the key } SchemaElement childSchemaElement = elements.get(child.getNamespaceURI(), childSchemaElementKey);//The SchemaElement object does exist because the method traverseElement is called before this. // if(i==0){ // automaton.addEdge(automaton.getInitialState(), childSchemaElement); // } // else { // automaton.addEdge(previousChildSchemaElement, childSchemaElement); // if(i==(element.getChildren().size()-1)){ // automaton.addEdge(childSchemaElement, automaton.getFinalState()); // } // } complexTypeStatisticsEntry.registerElementCount(childSchemaElement, documentIndex); schemaElementChildren.add(childSchemaElement); // previousChildSchemaElement=childSchemaElement; } ExtendedAutomaton automaton = automatons.get(complexTypeName); if (automaton == null) { automaton = new ExtendedAutomaton(); SchemaElement initialState = new SchemaElement("initial", DEFAULT_PSEUDOELEMENTS_NAMESPACE, null); automaton.setInitialState(initialState); SchemaElement finalState = new SchemaElement("final", DEFAULT_PSEUDOELEMENTS_NAMESPACE, null); automaton.setFinalState(finalState); automatons.put(complexTypeName, automaton); } List<SchemaElement> schemaElementChildrenWithInitialAndFinal = new ArrayList<>(schemaElementChildren); schemaElementChildrenWithInitialAndFinal.add(0, automaton.getInitialState()); schemaElementChildrenWithInitialAndFinal.add(automaton.getFinalState()); automaton.learn(schemaElementChildrenWithInitialAndFinal); complexTypeStatisticsEntry.registerSubpatternsFromList(schemaElementChildren); complexTypeStatisticsEntry.registerValueOfNodeCount(element.getText(), schemaElement, documentIndex); statistics.registerElementAtPathCount(realPathFiltered, documentIndex); statistics.registerValueAtPathCount(realPathFiltered, element.getText(), documentIndex); if (enclosingComplexType.equals("")) { statistics.registerRootElementOccurrence(schemaElement); } }
From source file:nl.b3p.imro.harvester.parser.ParserFactory.java
License:Open Source License
private static boolean isElementEqual(Element elem1, Element elem2) { return elem1.getName().equals(elem2.getName()) && elem1.getNamespaceURI().equals(elem2.getNamespaceURI()); }
From source file:nl.nn.adapterframework.util.XmlBuilder.java
License:Apache License
private void addNamespaceRecursive(Element element, Namespace namespace) { if (StringUtils.isEmpty(element.getNamespaceURI())) { element.setNamespace(namespace); List<Element> childList = element.getChildren(); if (!childList.isEmpty()) { for (Element child : childList) { addNamespaceRecursive(child, namespace); }/*w w w.j a va2s . c om*/ } } }
From source file:org.dvlyyon.net.netconf.marshalling.UnionChoiceHelper.java
License:Open Source License
Object xmlToUnion(ClassMapping cm, Element unionAttributeNode) { // Get to the union class Path childPath = Path.fromString(cm.getXmlPath()); PathSegment ps = new PathSegment(cm.getXmlNamespace(), cm.getXmlTag()); childPath.addSegment(ps);//w ww. ja va 2 s . c om ps = new PathSegment(unionAttributeNode.getNamespaceURI(), unionAttributeNode.getName()); childPath.addSegment(ps); ClassMapping unionClass = m_model.getClassMappingByPath(childPath); if (unionClass == null) { throw new RuntimeException("Class mapping not found for path: " + childPath); } // Instantiate the union class Object ret = createInstance(unionClass); // Check out every attribute in it one by one for (AttributeMapping am : unionClass.getAttributeMappings()) { Object attribValue = null; try { attribValue = am.convertStringToValue(unionAttributeNode.getText()); if (attribValue != null) { boolean valid = am.isValid(attribValue); if (!valid) { throw new RuntimeException("Invalid union assigment; constraint mismatch"); } } } catch (final Exception ex) { s_logger.warn(ex.getMessage()); attribValue = null; } if (attribValue != null) { // Yay - we found a match; set it BeanUtil.setDirectFieldValue(am.getJavaMemberName(), ret, attribValue); break; } } return ret; }
From source file:org.dvlyyon.net.netconf.marshalling.UnionChoiceHelper.java
License:Open Source License
@SuppressWarnings("unchecked") Object xmlToChoice(ClassMapping cm, String tag, Element choiceParentNode) throws RuntimeException { // Get to the choice class Path childPath = Path.fromString(cm.getXmlPath()); PathSegment ps = new PathSegment(cm.getXmlNamespace(), cm.getXmlTag()); childPath.addSegment(ps);// www. j ava2s .com ps = new PathSegment(choiceParentNode.getNamespaceURI(), tag); childPath.addSegment(ps); ClassMapping choiceClass = m_model.getClassMappingByPath(childPath); if (choiceClass == null) { throw new RuntimeException("Class mapping not found for path: " + childPath); } // Instantiate the choice object Object choice = createInstance(choiceClass); ClassMapping caseClass = null; Object caseObject = null; List<Element> attribElements = choiceParentNode.getChildren(); if (attribElements != null && attribElements.size() > 0) { for (Element potentialCaseAttribute : attribElements) { // Lookup the choice's case mappings and match it to ONE Of the attributes in the case node outer: for (AttributeMapping caseMapping : choiceClass.getAttributeMappings()) { if (caseMapping.getType() != AttributeMapping.Type.Class) { throw new RuntimeException( "Invalid metadata - all attributes in a Choice class MUST be Case classes"); } Path caseXmlPath = Path.fromString(choiceClass.getXmlPath()); ps = new PathSegment(choiceClass.getXmlNamespace(), choiceClass.getXmlTag()); PathSegment attrPs = new PathSegment(caseMapping.getXmlNamespace(), caseMapping.getXmlTag()); caseXmlPath.addSegment(ps); caseXmlPath.addSegment(attrPs); caseClass = m_model.getClassMappingByPath(caseXmlPath); if (caseClass == null) { throw new RuntimeException("Class mapping not found for path : " + caseXmlPath); } for (AttributeMapping caseAttrib : caseClass.getAttributeMappings()) { if (potentialCaseAttribute.getName().equals(caseAttrib.getXmlTag()) && potentialCaseAttribute.getNamespaceURI().equals(caseAttrib.getXmlNamespace())) { // We found the case - create the case object and set the choice's member to point to this caseObject = createInstance(caseClass); BeanUtil.setDirectFieldValue(caseMapping.getJavaMemberName(), choice, caseObject); break outer; } } } if (caseObject != null) { // do an XmlToCase, which is the same as fromXml - given the case class and instance m_parent.setAttributesFromXml(caseObject, choiceParentNode, caseClass); return choice; } } } return null; }
From source file:org.dvlyyon.net.netconf.transport.ssh.AsyncSshConnection.java
License:Open Source License
/** * Called when a regular (non-hello) message is received. The message can be one of three types:<ol> * <li>rpc-reply - This would be a response to the <b>create-subscription</b> message</li> * <li>replayComplete - This is an indicator that says old notifications have been replayed - ignored</li> * <li>notification - This is an actual notification - call the registered listener</li> * </ol>/* w ww . jav a 2 s . co m*/ */ @Override @SuppressWarnings("unchecked") protected void handleResponse(Element response) { try { // We are interested in three types of responses // RPC-OK (in response to create-subscription); verify using the message ID and OK response String responseType = response.getName(); if (responseType.equals("rpc-reply")) { // This must be a response to the create-subscription message; verify using the message ID Namespace ns = Namespace.getNamespace(BASE_NAMESPACE); String messageId = response.getAttributeValue("message-id"); if (m_createSubscriptionMessageId.equals(messageId)) { Element ok = response.getChild("ok", ns); if (ok != null) { s_logger.debug("Got an OK response to create-subscription."); m_readyToReceiveNotifications = true; } else { s_logger.warn("Expected an OK response to create-subscription; did not get one"); s_logger.warn("Actual response: " + XmlUtils.toXmlString(response)); } } else { //s_logger.info(XmlUtils.toXmlString(response)); s_logger.info("Reply received to keep-alive ping on async. channel"); } } else if (responseType.equals("replayComplete")) { // We don't really care about this one s_logger.info("Received ReplayComplete indicator from device"); } else if (responseType.equals("notification")) { Element root = null; if (s_logger.isDebugEnabled()) { s_logger.debug("Top-level notification XML: " + XmlUtils.toXmlString(response)); } // Notifications (call the listener) s_logger.debug("Got a notification from device: " + responseType); Timestamp eventTime = null; ArrayList<Element> dataNodes = new ArrayList<Element>(); List<Element> kids = (List<Element>) response.getChildren(); for (Element kid : kids) { if (kid.getName().equals("eventTime") && kid.getNamespaceURI().equals(NOTIF_NAMESPACE)) { try { eventTime = new RFC3399Timestamp(kid.getText()).getSqlTimestamp(); } catch (final Exception ex) { s_logger.warn("Error parsing event date: " + kid.getText() + " using current time"); ; eventTime = new Timestamp(System.currentTimeMillis()); } } else { dataNodes.add(kid); } } if (dataNodes.size() > 0) { root = new Element("data"); for (Element dataNode : dataNodes) { dataNode.detach(); root.addContent(dataNode); } if (s_logger.isDebugEnabled()) s_logger.debug("Notification data: " + XmlUtils.toXmlString(root)); } m_lastReceivedNotificationTime = eventTime; m_listener.notify(eventTime, root); } else { s_logger.warn("Unexpected XML message received from device: " + responseType); } } catch (final Exception fex) { // Any exception in event processing should just ignore the event, instead of throwing it to the // caller (since the thread it is being called in will bag out otherwise) s_logger.error("Error processing notification: " + XmlUtils.toXmlString(response, true)); if (s_logger.isDebugEnabled()) { s_logger.error(fex, fex); } } }
From source file:org.jahia.utils.osgi.parsers.AbstractXmlFileParser.java
License:Open Source License
public void dumpElementNamespaces(Element element) { Namespace mainNamespace = element.getNamespace(); getLogger().debug("Main namespace prefix=[" + mainNamespace.getPrefix() + "] uri=[" + mainNamespace.getURI() + "] getNamespaceURI=[" + element.getNamespaceURI() + "]"); for (Namespace additionalNamespace : (List<Namespace>) element.getAdditionalNamespaces()) { getLogger().debug("Additional namespace prefix=" + additionalNamespace.getPrefix() + " uri=" + additionalNamespace.getURI()); }// w w w. ja v a 2s .c om }
From source file:org.jahia.utils.osgi.parsers.TldXmlFileParser.java
License:Open Source License
public static String getTaglibUri(Element tldRootElement) throws JDOMException { boolean hasDefaultNamespace = !StringUtils.isEmpty(tldRootElement.getNamespaceURI()); Element uriElement = null;/*from w w w . j a v a2s . c o m*/ if (hasDefaultNamespace) { uriElement = getElement(tldRootElement, "/xp:taglib/xp:uri"); } else { uriElement = getElement(tldRootElement, "/taglib/uri"); } return uriElement != null ? uriElement.getTextTrim() : null; }
From source file:org.jahia.utils.osgi.parsers.TldXmlFileParser.java
License:Open Source License
@Override public void parse(String fileName, Element rootElement, String fileParent, boolean externalDependency, boolean optionalDependency, String version, ParsingContext parsingContext) throws JDOMException { dumpElementNamespaces(rootElement);/* w w w . ja v a2s . c o m*/ boolean hasDefaultNamespace = !StringUtils.isEmpty(rootElement.getNamespaceURI()); if (hasDefaultNamespace) { getLogger().debug("Using default namespace XPath queries"); } String uri = getTaglibUri(rootElement); if (uri == null) { getLogger().warn("Couldn't find /taglib/uri tag in " + fileParent + " / " + fileName + ", aborting TLD parsing !"); return; } getLogger().debug("Taglib URI=" + uri); Set<PackageInfo> taglibPackageSet = parsingContext.getTaglibPackages().get(uri); if (taglibPackageSet == null) { taglibPackageSet = new TreeSet<PackageInfo>(); } List<Element> tagClassElements = new LinkedList<Element>(); tagClassElements.addAll( getElements(rootElement, hasDefaultNamespace ? "//xp:tag/xp:tag-class" : "//tag/tag-class")); tagClassElements.addAll( getElements(rootElement, hasDefaultNamespace ? "//xp:tag/xp:tei-class" : "//tag/tei-class")); tagClassElements.addAll(getElements(rootElement, hasDefaultNamespace ? "//xp:tag/xp:attribute/xp:type" : "//tag/attribute/type")); tagClassElements .addAll(getElements(rootElement, hasDefaultNamespace ? "//xp:tag/xp:tagclass" : "//tag/tagclass")); tagClassElements .addAll(getElements(rootElement, hasDefaultNamespace ? "//xp:tag/xp:teiclass" : "//tag/teiclass")); for (Element tagClassElement : tagClassElements) { getLogger().debug(fileName + " Found tag class " + tagClassElement.getTextTrim() + " package=" + PackageUtils.getPackagesFromClass(tagClassElement.getTextTrim(), optionalDependency, version, fileParent + "/" + fileName, parsingContext).toString()); taglibPackageSet.addAll(PackageUtils.getPackagesFromClass(tagClassElement.getTextTrim(), optionalDependency, version, fileParent + "/" + fileName, parsingContext)); } // Parsing function class List<Element> functionClassElements = null; if (hasDefaultNamespace) { functionClassElements = getElements(rootElement, "//xp:function/xp:function-class"); } else { functionClassElements = getElements(rootElement, "//function/function-class"); } for (Element functionClassElement : functionClassElements) { getLogger() .debug(fileName + " Found function class " + functionClassElement.getTextTrim() + " package=" + PackageUtils.getPackagesFromClass(functionClassElement.getTextTrim(), optionalDependency, version, fileParent + "/" + fileName, parsingContext) .toString()); taglibPackageSet.addAll(PackageUtils.getPackagesFromClass(functionClassElement.getTextTrim(), optionalDependency, version, fileParent + "/" + fileName, parsingContext)); } // Parsing function signature for (Element functionSignatureElement : getElements(rootElement, hasDefaultNamespace ? "//xp:function/xp:function-signature" : "//function/function-signature")) { List<PackageInfo> pkgs = getPackagesFromFunctionSignature(functionSignatureElement.getTextTrim(), fileParent + "/" + fileName, optionalDependency, version, parsingContext); if (pkgs != null && !pkgs.isEmpty()) { getLogger().debug( fileName + " Found packages in function signature " + functionSignatureElement.getTextTrim() + " packages=[" + StringUtils.join(pkgs, ", ") + "]"); taglibPackageSet.addAll(pkgs); } } // Parsing a special "hint" in comments for (Object comment : selectNodes(rootElement, "//comment()")) { if (comment instanceof Comment) { String text = ((Comment) comment).getText(); List<PackageInfo> pkgs = getPackagesFromTagFileComment(text, fileParent + "/" + fileName, parsingContext); if (pkgs != null && !pkgs.isEmpty()) { getLogger().debug(fileName + " Found import packages hint in comment " + text + " packages=[" + StringUtils.join(pkgs, ", ") + "]"); taglibPackageSet.addAll(pkgs); } } } // Parse tag files for (Element tagFilePathElement : getElements(rootElement, hasDefaultNamespace ? "//xp:tag-file/xp:path" : "//tag-file/path")) { String tagFilePath = tagFilePathElement.getTextTrim(); if (tagFilePath.startsWith("/")) { tagFilePath = tagFilePath.substring(1); } getLogger().debug("Adding tag file to be parsed later in the process: " + tagFilePath); parsingContext.addAdditionalFileToParse(tagFilePath); } Set<PackageInfo> effectivePackages = new TreeSet<PackageInfo>(taglibPackageSet); for (PackageInfo pkg : taglibPackageSet) { if (knownTransitiveImportPackages.containsKey(pkg.getName())) { effectivePackages.addAll(knownTransitiveImportPackages.get(pkg.getName())); } } parsingContext.putTaglibPackages(uri, effectivePackages); parsingContext.putExternalTaglib(uri, externalDependency); }
From source file:org.shaman.rpg.editor.project.elements.JdomElements.java
/** * <b>Do not use, an instance is provided in the project's lookup</b>. * @param projectRoot /* www .ja v a 2s .c o m*/ */ public JdomElements(FileObject projectRoot) { try { file = projectRoot.getFileObject(FILENAME); if (file == null) { file = projectRoot.createData(FILENAME); //set hidden flag //setHidden(FileUtil.toFile(file).toPath()); root = newDoc(); save(); } else { //load SAXBuilder b = new SAXBuilder(); try (InputStream in = file.getInputStream()) { doc = b.build(in); } catch (JDOMException ex) { Exceptions.printStackTrace(ex); //create new file root = newDoc(); save(); return; } //validate file org.jdom2.Element e = doc.getRootElement(); if (!e.getName().equals(ROOT_NAME) || !e.getNamespaceURI().equals(ROOT_NAMESPACE)) { //invalid root file -> corrupt file -> create new file LOG.warning("corrupt elements file: invalid root node"); root = newDoc(); save(); return; } //create root group root = new JdomGroup(null, this, e, 0); root.load(); } } catch (IOException e) { Exceptions.printStackTrace(e); } }