List of usage examples for org.jdom2 Element getAttributeValue
public String getAttributeValue(final String attname)
This returns the attribute value for the attribute with the given name and within no namespace, null if there is no such attribute, and the empty string if the attribute value is empty.
From source file:ca.nrc.cadc.vos.NodeReader.java
License:Open Source License
/** * Constructs a ContainerNode from the given Element of the * Document, Document Namespace, and Node path. * * @param el a node Element of the Document. * @param namespace Document Namespace./*from w w w . ja va 2 s .co m*/ * @param uri Node uri attribute. * @return ContainerNode * @throws NodeParsingException if there is an error parsing the XML. * @throws URISyntaxException */ protected Node buildContainerNode(Element el, Namespace namespace, String uri) throws NodeParsingException, URISyntaxException { // Instantiate a ContainerNode class ContainerNode node; try { node = new ContainerNode(new VOSURI(uri)); } catch (URISyntaxException e) { String error = "invalid node uri " + uri; throw new NodeParsingException(error, e); } // properties element node.setProperties(getProperties(el, namespace)); // nodes element Element nodes = el.getChild("nodes", namespace); if (nodes == null) { String error = "nodes element not found in node"; throw new NodeParsingException(error); } // list of child nodes List<Element> nodesList = nodes.getChildren("node", namespace); for (Element childNode : nodesList) { String childNodeUri = childNode.getAttributeValue("uri"); if (childNodeUri == null) { String error = "uri attribute not found in nodes node element"; throw new NodeParsingException(error); } // Get the xsi:type attribute which defines the Node class String xsiType = childNode.getAttributeValue("type", xsiNamespace); if (xsiType == null) { String error = "xsi:type attribute not found in node element " + uri; throw new NodeParsingException(error); } // Split the type attribute into namespace and Node type String[] types = xsiType.split(":"); String type = types[1]; log.debug("node type: " + type); if (type.equals(ContainerNode.class.getSimpleName())) node.getNodes().add(buildContainerNode(childNode, namespace, childNodeUri)); else if (type.equals(DataNode.class.getSimpleName())) node.getNodes().add(buildDataNode(childNode, namespace, childNodeUri)); else if (type.equals(LinkNode.class.getSimpleName())) node.getNodes().add(buildLinkNode(childNode, namespace, childNodeUri)); else throw new NodeParsingException("unsupported node type " + type); log.debug("added child node: " + childNodeUri); } return node; }
From source file:ca.nrc.cadc.vos.NodeReader.java
License:Open Source License
/** * Sets the attributes of a DataNode from the given DataNode, Element * of the Document and Document Namespace. * * @parm node a DataNode/*from w w w . j av a 2 s . c om*/ * @param el a node Element in the Document. * @param namespace Document Namespace. * @throws NodeParsingException if there is an error parsing the XML. * @throws URISyntaxException */ protected void setDataNodeAttributes(DataNode node, Element el, Namespace namespace) throws NodeParsingException, URISyntaxException { // busy attribute String busy = el.getAttributeValue("busy"); if (busy == null) { String error = "busy element not found in DataNode"; throw new NodeParsingException(error); } boolean isBusy = busy.equalsIgnoreCase("true") ? true : false; // TODO: BM: Change the XML schema to support the three possible // values for the busy state: not busy, busy with read, busy // with write. For now, we'll consider busy to be the more // restrictive busy with write. if (isBusy) { node.setBusy(NodeBusyState.busyWithWrite); } else { node.setBusy(NodeBusyState.notBusy); } log.debug("busy: " + isBusy); // properties element node.setProperties(getProperties(el, namespace)); // accepts element node.accepts().addAll(getViewURIs(el, namespace, "accepts")); // provides element node.provides().addAll(getViewURIs(el, namespace, "provides")); }
From source file:ca.nrc.cadc.vos.NodeReader.java
License:Open Source License
/** * Builds a List of NodeProperty objects from the Document property Elements. * * @param el a node Element of the Document. * @param namespace Document Namespace./* w ww. j a v a2 s . com*/ * @return List of NodeProperty objects. * @throws NodeParsingException if there is an error parsing the XML. */ protected List<NodeProperty> getProperties(Element el, Namespace namespace) throws NodeParsingException { // properties element Element properties = el.getChild("properties", namespace); if (properties == null) { String error = "properties element not found"; throw new NodeParsingException(error); } // new NodeProperty List List<NodeProperty> set = new ArrayList<NodeProperty>(); // properties property elements List<Element> propertyList = properties.getChildren("property", namespace); for (Element property : propertyList) { String propertyUri = property.getAttributeValue("uri"); if (propertyUri == null) { String error = "uri attribute not found in property element " + property; throw new NodeParsingException(error); } // xsi:nil set to true indicates Property is to be deleted String xsiNil = property.getAttributeValue("nil", xsiNamespace); boolean markedForDeletion = false; if (xsiNil != null) markedForDeletion = xsiNil.equalsIgnoreCase("true") ? true : false; // if marked for deletetion, property can not contain text content String text = property.getText(); if (markedForDeletion) text = ""; // create new NodeProperty NodeProperty nodeProperty = new NodeProperty(propertyUri, text); // set readOnly attribute String readOnly = property.getAttributeValue("readOnly"); if (readOnly != null) nodeProperty.setReadOnly((readOnly.equalsIgnoreCase("true") ? true : false)); // markedForDeletion attribute nodeProperty.setMarkedForDeletion(markedForDeletion); set.add(nodeProperty); } return set; }
From source file:ca.nrc.cadc.vos.NodeReader.java
License:Open Source License
protected List<URI> getViewURIs(Element root, Namespace namespace, String parent) throws NodeParsingException, URISyntaxException { // new View List List<URI> list = new ArrayList<URI>(); // view parent element Element parentElement = root.getChild(parent, namespace); if (parentElement == null) { return list; }//from ww w. j av a2 s . c o m // view elements List<Element> uriList = parentElement.getChildren("view", namespace); for (Element view : uriList) { // view uri attribute String viewUri = view.getAttributeValue("uri"); if (viewUri == null) { String error = "uri attribute not found in " + parent + " view element"; throw new NodeParsingException(error); } log.debug(parent + "view uri: " + viewUri); list.add(new URI(viewUri)); } return list; }
From source file:ca.nrc.cadc.vos.NodeReader.java
License:Open Source License
/** * Builds a List of View objects from the view elements contained within * the given parent element./*w w w.j av a 2 s . co m*/ * * @param root Root Element of the Document. * @param namespace Document Namespace. * @param parent View Parent Node. * @return List of View objects. * @throws NodeParsingException if there is an error parsing the XML. */ protected List<View> getViews(Element root, Namespace namespace, String parent) throws NodeParsingException { // view parent element Element parentElement = root.getChild(parent, namespace); if (parentElement == null) { String error = parent + " element not found in node"; throw new NodeParsingException(error); } // new View List List<View> list = new ArrayList<View>(); // view elements List<Element> viewList = parentElement.getChildren("view", namespace); for (Element view : viewList) { // view uri attribute String viewUri = view.getAttributeValue("uri"); if (viewUri == null) { String error = "uri attribute not found in " + parent + " view element"; throw new NodeParsingException(error); } log.debug(parent + "view uri: " + viewUri); // new View // View acceptsView = new View(viewUri, node); // view original attribute String original = view.getAttributeValue("original"); if (original != null) { boolean isOriginal = original.equalsIgnoreCase("true") ? true : false; // view.setOriginal(isOriginal); log.debug(parent + " view original: " + isOriginal); } List<Element> paramList = view.getChildren("param", namespace); for (Element param : paramList) { String paramUri = param.getAttributeValue("uri"); if (paramUri == null) { String error = "param uri attribute not found in accepts view element"; throw new NodeParsingException(error); } log.debug("accepts view param uri: " + paramUri); // TODO: what are params??? } } return list; }
From source file:ca.nrc.cadc.vos.TransferReader.java
License:Open Source License
private Transfer parseTransfer(Document document) throws URISyntaxException { Element root = document.getRootElement(); Direction direction = parseDirection(root); // String serviceUrl; // not in XML yet VOSURI target = new VOSURI(root.getChildText("target", VOS_NS)); // TODO: get view nodes and uri attribute View view = null;/*from w ww .j a v a2s . co m*/ Parameter param = null; List views = root.getChildren("view", VOS_NS); if (views != null && views.size() > 0) { Element v = (Element) views.get(0); view = new View(new URI(v.getAttributeValue("uri"))); List params = v.getChildren("param", VOS_NS); if (params != null) { for (Object o : params) { Element p = (Element) o; param = new Parameter(new URI(p.getAttributeValue("uri")), p.getText()); view.getParameters().add(param); } } } List<Protocol> protocols = parseProtocols(root); String keepBytesStr = root.getChildText("keepBytes", VOS_NS); if (keepBytesStr != null) { boolean keepBytes = true; keepBytes = keepBytesStr.equalsIgnoreCase("true"); return new Transfer(target, direction, view, protocols, keepBytes); } return new Transfer(target, direction, view, protocols); }
From source file:ca.nrc.cadc.vos.TransferReader.java
License:Open Source License
private List<Protocol> parseProtocols(Element root) { List<Protocol> rtn = null; //Element e = root.getChild("protocols", NS); List prots = root.getChildren("protocol", VOS_NS); if (prots != null && prots.size() > 0) { rtn = new ArrayList<Protocol>(prots.size()); for (Object obj : prots) { Element eProtocol = (Element) obj; String uri = eProtocol.getAttributeValue("uri"); String endpoint = eProtocol.getChildText("endpoint", VOS_NS); rtn.add(new Protocol(uri, endpoint, null)); }/* w w w. ja va2 s . c o m*/ } return rtn; }
From source file:cager.parser.test.SimpleTest2.java
License:Open Source License
private void XMLtoJavaParser() { // Creamos el builder basado en SAX SAXBuilder builder = new SAXBuilder(); try {/*from w ww .j av a 2 s . c o m*/ String nombreMetodo = null; List<String> atributos = new ArrayList<String>(); String tipoRetorno = null; String nombreArchivo = null; String exportValue = ""; String codigoFuente = ""; HashMap<String, String> tipos = new HashMap<String, String>(); // Construimos el arbol DOM a partir del fichero xml Document doc = builder.build(new FileInputStream(ruta + "VBParser\\ejemplosKDM\\archivo.kdm")); //Document doc = builder.build(new FileInputStream("E:\\WorkspaceParser\\VBParser\\ejemplosKDM\\archivo.kdm")); Namespace xmi = Namespace.getNamespace("xmi", "http://www.omg.org/XMI"); XPathExpression<Element> xpath = XPathFactory.instance().compile("//codeElement", Filters.element()); List<Element> elements = xpath.evaluate(doc); for (Element emt : elements) { if (emt.getAttribute("type", xmi).getValue().compareTo("code:CompilationUnit") == 0) { nombreArchivo = emt.getAttributeValue("name").substring(0, emt.getAttributeValue("name").indexOf('.')); } if (emt.getAttribute("type", xmi).getValue().compareTo("code:LanguageUnit") == 0) { List<Element> hijos = emt.getChildren(); for (Element hijo : hijos) { tipos.put(hijo.getAttributeValue("id", xmi), hijo.getAttributeValue("name")); } } } FileOutputStream fout; fout = new FileOutputStream(ruta + "VBParser\\src\\cager\\parser\\test\\" + nombreArchivo + ".java"); //fout = new FileOutputStream("E:\\WorkspaceParser\\VBParser\\src\\cager\\parser\\test\\"+nombreArchivo+".java"); // get the content in bytes byte[] contentInBytes = null; contentInBytes = ("package cager.parser.test;\n\n").getBytes(); fout.write(contentInBytes); fout.flush(); contentInBytes = ("public class " + nombreArchivo + "{\n\n").getBytes(); fout.write(contentInBytes); fout.flush(); for (Element emt : elements) { // System.out.println("XPath has result: " + emt.getName()+" "+emt.getAttribute("type",xmi)); if (emt.getAttribute("type", xmi).getValue().compareTo("code:MethodUnit") == 0) { nombreMetodo = emt.getAttribute("name").getValue(); if (emt.getAttribute("export") != null) exportValue = emt.getAttribute("export").getValue(); atributos = new ArrayList<String>(); List<Element> hijos = emt.getChildren(); for (Element hijo : hijos) { if (hijo.getAttribute("type", xmi) != null) { if (hijo.getAttribute("type", xmi).getValue().compareTo("code:Signature") == 0) { List<Element> parametros = hijo.getChildren(); for (Element parametro : parametros) { if (parametro.getAttribute("kind") == null || parametro.getAttribute("kind").getValue().compareTo("return") != 0) { atributos.add(tipos.get(parametro.getAttribute("type").getValue()) + " " + parametro.getAttributeValue("name")); } else { tipoRetorno = tipos.get(parametro.getAttribute("type").getValue()); } } } } else if (hijo.getAttribute("snippet") != null) { codigoFuente = hijo.getAttribute("snippet").getValue(); } } //System.out.println("MethodUnit!! " + emt.getName()+" "+emt.getAttribute("type",xmi)+" "+emt.getAttribute("name").getValue()); //System.out.println(emt.getAttribute("name").getValue()); if (tipoRetorno.compareTo("Void") == 0) { tipoRetorno = "void"; } contentInBytes = ("\t" + exportValue + " " + tipoRetorno + " " + nombreMetodo + " (") .getBytes(); fout.write(contentInBytes); fout.flush(); int n = 0; for (String parametro : atributos) { if (atributos.size() > 0 && n < atributos.size() - 1) { contentInBytes = (" " + parametro + ",").getBytes(); } else { contentInBytes = (" " + parametro).getBytes(); } fout.write(contentInBytes); fout.flush(); n++; } contentInBytes = (" ) {\n").getBytes(); fout.write(contentInBytes); fout.flush(); contentInBytes = ("\n/* \n " + codigoFuente + " \n */\n").getBytes(); fout.write(contentInBytes); fout.flush(); contentInBytes = ("\t}\n\n").getBytes(); fout.write(contentInBytes); fout.flush(); System.out.print("\t" + exportValue + " " + tipoRetorno + " " + nombreMetodo + " ("); n = 0; for (String parametro : atributos) { if (atributos.size() > 0 && n < atributos.size() - 1) { System.out.print(" " + parametro + ", "); } else { System.out.print(" " + parametro); } n++; } System.out.println(" ) {"); System.out.println("/* \n " + codigoFuente + " \n */"); System.out.println("\t}\n"); } } contentInBytes = ("}\n").getBytes(); fout.write(contentInBytes); fout.flush(); fout.close(); XPathExpression<Attribute> xp = XPathFactory.instance().compile("//@*", Filters.attribute(xmi)); for (Attribute a : xp.evaluate(doc)) { a.setName(a.getName().toLowerCase()); } xpath = XPathFactory.instance().compile("//codeElement/@name='testvb.cls'", Filters.element()); Element emt = xpath.evaluateFirst(doc); if (emt != null) { System.out.println("XPath has result: " + emt.getName()); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:ch.kostceco.tools.kostval.validation.modulesiard.impl.ValidationEcolumnModuleImpl.java
License:Open Source License
private boolean validateColumnOccurrence(ValidationContext validationContext) throws Exception { int onWork = 41; boolean validTable; boolean validDatabase; Properties properties = validationContext.getValidationProperties(); List<SiardTable> siardTables = validationContext.getSiardTables(); StringBuilder namesOfInvalidTables = new StringBuilder(); StringBuilder namesOfInvalidColumns = new StringBuilder(); validDatabase = true;//from w w w . j av a 2s .c om // Iterate over the SIARD tables and verify the nullable attribute for (SiardTable siardTable : siardTables) { String nullable = new String(); String minOccurs = new String(); validTable = true; // Number of attributes in metadata.xml int metadataXMLColumnsCount = siardTable.getMetadataXMLElements().size(); // Number of attributes in schema.xsd int tableXSDColumnsCount = siardTable.getTableXSDElements().size(); /* Counter. In order to prevent indexOutOfBorder errors columnsCounter is assigned to the * smaller number of columns */ int columnCount = (metadataXMLColumnsCount >= tableXSDColumnsCount) ? tableXSDColumnsCount : metadataXMLColumnsCount; // Element/Attributes of the actual SIARD table List<Element> xmlElements = siardTable.getMetadataXMLElements(); // Elements/Attributes of the according XML schema List<Element> xsdElements = siardTable.getTableXSDElements(); Namespace xmlNamespace = validationContext.getXmlNamespace(); for (int i = 0; i < columnCount; i++) { // Actual Element of the metadata.xml Element xmlElement = xmlElements.get(i); // Actual Element of the according XML schema Element xsdElement = xsdElements.get(i); String nullableElementDescription = properties .getProperty("module.e.siard.metadata.xml.nullable.element.name"); String minuOccursAttributeDescription = properties .getProperty("module.e.siard.table.xsd.attribute.minOccurs.name"); String nameAttributeDescription = properties.getProperty("module.e.siard.table.xsd.attribute.name"); // Value of the nullable Element in metadata.xml nullable = xmlElement.getChild(nullableElementDescription, xmlNamespace).getValue(); // Value of the minOccurs attribute in the according XML schema minOccurs = xsdElement.getAttributeValue(minuOccursAttributeDescription); // If the nullable Element is set to true and the minOccurs attribute is null if (nullable.equalsIgnoreCase("true") && minOccurs == null) { validTable = false; validDatabase = false; namesOfInvalidColumns.append((namesOfInvalidColumns.length() > 0) ? ", " : ""); namesOfInvalidColumns.append(xsdElement.getAttributeValue(nameAttributeDescription)); // If the nullable Element is set to true and the minOccurs attribute is set to zero } else if (nullable.equalsIgnoreCase("true") && minOccurs.equalsIgnoreCase("0")) { } else if (nullable.equalsIgnoreCase("false") && minOccurs == null) { } else if (nullable.equalsIgnoreCase("false") && minOccurs.equalsIgnoreCase("0")) { validTable = false; validDatabase = false; namesOfInvalidColumns.append((namesOfInvalidColumns.length() > 0) ? ", " : ""); namesOfInvalidColumns.append(xsdElement.getAttributeValue(nameAttributeDescription)); } } if (validTable == false) { namesOfInvalidTables.append((namesOfInvalidTables.length() > 0) ? ", " : ""); namesOfInvalidTables.append(siardTable.getTableName()); namesOfInvalidTables.append(properties.getProperty("module.e.siard.table.xsd.file.extension")); namesOfInvalidTables.append("("); namesOfInvalidTables.append(namesOfInvalidColumns); namesOfInvalidTables.append(")"); namesOfInvalidColumns = null; namesOfInvalidColumns = new StringBuilder(); } if (onWork == 41) { onWork = 2; System.out.print("E- "); System.out.print("\r"); } else if (onWork == 11) { onWork = 12; System.out.print("E\\ "); System.out.print("\r"); } else if (onWork == 21) { onWork = 22; System.out.print("E| "); System.out.print("\r"); } else if (onWork == 31) { onWork = 32; System.out.print("E/ "); System.out.print("\r"); } else { onWork = onWork + 1; } } // Writing back error log this.setIncongruentColumnOccurrence(namesOfInvalidTables); return validDatabase; }
From source file:ch.kostceco.tools.kostval.validation.modulesiard.impl.ValidationEcolumnModuleImpl.java
License:Open Source License
private boolean validateColumnType(ValidationContext validationContext) throws Exception { int onWork = 41; boolean validTable; boolean validDatabase; Properties properties = validationContext.getValidationProperties(); List<SiardTable> siardTables = validationContext.getSiardTables(); StringBuilder namesOfInvalidTables = new StringBuilder(); StringBuilder namesOfInvalidColumns = new StringBuilder(); // List of all XML column elements to verify the allover sequence List<String> xmlElementSequence = new ArrayList<String>(); // List of all XSD column elements List<String> xsdElementSequence = new ArrayList<String>(); // Iterate over the SIARD tables and verify the column types validDatabase = true;//from w w w. jav a2 s. c om for (SiardTable siardTable : siardTables) { // Elements of the actual SIARD table List<Element> xmlElements = siardTable.getMetadataXMLElements(); // Elements of the according XML schema List<Element> xsdElements = siardTable.getTableXSDElements(); // Number of attributes in metadata.xml int metadataXMLColumnsCount = xmlElements.size(); // Number of attributes in schema.xsd int tableXSDColumnsCount = xsdElements.size(); /* Counter. In order to prevent indexOutOfBorder errors columnsCounter is assigned to the * smaller number of columns */ int columnCount = (metadataXMLColumnsCount >= tableXSDColumnsCount) ? tableXSDColumnsCount : metadataXMLColumnsCount; validTable = true; // Verify whether the number of column elements in XML and XSD are equal for (int i = 0; i < columnCount; i++) { Element xmlElement = xmlElements.get(i); Element xsdElement = xsdElements.get(i); // Retrieve the Elements name String xmlTypeElementName = properties.getProperty("module.e.siard.metadata.xml.type.element.name"); String xsdTypeAttribute = properties.getProperty("module.e.siard.table.xsd.type.attribute.name"); String xsdAttribute = properties.getProperty("module.e.siard.table.xsd.attribute.name"); String columnName = xsdElement.getAttributeValue(xsdAttribute); // Retrieve the original column type from metadata.xml String leftSide = xmlElement.getChild(xmlTypeElementName, validationContext.getXmlNamespace()) .getValue(); // Retrieve the original column type from table.xsd String rightSide = xsdElement.getAttributeValue(xsdTypeAttribute); String delimiter = properties .getProperty("module.e.attribute.type.validator.original.type.delimiter"); // Trim the column types - eliminates the brackets and specific numeric parameters String trimmedExpectedType = trimLeftSideType(leftSide, delimiter); // Designing expected column type in table.xsd, called "rightSide" String expectedType = properties.getProperty(trimmedExpectedType); // In case the expected type does not exist if (expectedType == null) { expectedType = properties.getProperty("module.e.type.validator.unknown.type"); validTable = false; validDatabase = false; namesOfInvalidColumns.append((namesOfInvalidColumns.length() > 0) ? ", " : ""); namesOfInvalidColumns.append(columnName + "{" + expectedType + "}"); } else if (!expectedType.equalsIgnoreCase(rightSide) && expectedType != null) { validTable = false; validDatabase = false; namesOfInvalidColumns.append((namesOfInvalidColumns.length() > 0) ? ", " : ""); namesOfInvalidColumns.append(columnName); } // Convey the column types for the all over sequence test [E.4] xmlElementSequence.add(expectedType); xsdElementSequence.add(rightSide); } if (validTable == false) { namesOfInvalidTables.append((namesOfInvalidTables.length() > 0) ? ", " : ""); namesOfInvalidTables.append(siardTable.getTableName()); namesOfInvalidTables.append(properties.getProperty("module.e.siard.table.xsd.file.extension")); namesOfInvalidTables.append("("); namesOfInvalidTables.append(namesOfInvalidColumns); namesOfInvalidTables.append(")"); namesOfInvalidColumns = null; namesOfInvalidColumns = new StringBuilder(); } if (onWork == 41) { onWork = 2; System.out.print("E- "); System.out.print("\r"); } else if (onWork == 11) { onWork = 12; System.out.print("E\\ "); System.out.print("\r"); } else if (onWork == 21) { onWork = 22; System.out.print("E| "); System.out.print("\r"); } else if (onWork == 31) { onWork = 32; System.out.print("E/ "); System.out.print("\r"); } else { onWork = onWork + 1; } } this.setIncongruentColumnType(namesOfInvalidTables); // Save the allover column elements for [E.4] validationContext.setXmlElementsSequence(xmlElementSequence); validationContext.setXsdElementsSequence(xsdElementSequence); this.setValidationContext(validationContext); // Return the current validation state return validDatabase; }