blob: e4425e94bd42831a9f0a805827659ae80790e039 [file] [log] [blame]
/* --COPYRIGHT--,EPL
* Copyright (c) 2008 Texas Instruments and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Texas Instruments - initial implementation
*
* --/COPYRIGHT--*/
/*
* ======== XML.java ========
* This class parses XML documents and provides primitive accessor
* methods to the XML data.
*/
package xdc.services.global;
import xdc.services.global.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.io.File;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.Vector;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;
import org.w3c.dom.Node;
import org.w3c.dom.Attr;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
/*
* ======== XML ========
*/
public class XML {
/*
* ======== getList ========
*/
public static String[] getList(Document doc, String listName,
String attrName)
{
return (getList(doc, listName, attrName, null, null));
}
public static String[] getList(Document doc, String listName,
String attrName, String keyName, String keyValue)
{
Vector<String> result = new Vector<String>();
NodeList nl = doc.getElementsByTagName(listName);
int n = (nl == null) ? 0 : nl.getLength();
for (int k = 0; k < n; k++) {
NodeList nodes = nl.item(k).getChildNodes();
if (nodes != null) {
/* for each ELEMENT, get the named attribute */
int len = nodes.getLength();
for (int i = 0; i < len; i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element elem = (Element)node;
/* determine if we should add this elem */
boolean append = false;
if (keyName != null) {
Attr key = elem.getAttributeNode(keyName);
String tmp = key != null ? key.getValue() : "";
if (tmp.equals(keyValue)) {
append = true;
}
}
else {
append = true;
}
if (append == true) {
/* add elem to result */
Attr attr = elem.getAttributeNode(attrName);
result.add(attr != null ? attr.getValue() : null);
}
}
}
}
}
return ((String [])result.toArray(new String [result.size()]));
}
/*
* ======== getListAttrs ========
*/
public static HashMap getListAttrs(Document doc,
String listName, String [] keys)
{
NodeList nl = doc.getElementsByTagName(listName);
int len = (nl == null) ? 0 : nl.getLength();
for (int k = 0; k < len; k++) {
Node node = nl.item(k);
if (node.getNodeType() == Node.ELEMENT_NODE) {
HashMap<String,String> map = new HashMap<String,String>();
Element elem = (Element)node;
/* populate map with specified keys */
for (int j = 0; j < keys.length; j++) {
Attr anode = elem.getAttributeNode(keys[j]);
if (anode != null) {
map.put(keys[j], anode.getValue());
}
}
/* return result */
return (map);
}
}
return (null);
}
/*
* ======== getHMaps ========
*/
public static HashMap[] getHMaps(Document doc,
String listName, String [] keys)
{
Vector<HashMap> result = new Vector<HashMap>();
NodeList nl = doc.getElementsByTagName(listName);
int n = (nl == null) ? 0 : nl.getLength();
for (int k = 0; k < n; k++) {
NodeList nodes = nl.item(k).getChildNodes();
if (nodes != null) {
/* for each ELEMENT, get the named attribute */
int len = nodes.getLength();
for (int i = 0; i < len; i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
HashMap<String,String> map = new HashMap<String,String>();
Element elem = (Element)node;
/* populate map with specified keys */
for (int j = 0; j < keys.length; j++) {
Attr anode = elem.getAttributeNode(keys[j]);
if (anode != null) {
map.put(keys[j], anode.getValue());
}
}
/* add map to result */
result.add(map);
}
}
}
}
return ((HashMap [])result.toArray(new HashMap [result.size()]));
}
/*
* ======== parse ========
* Parse the specified XML file and return a Document object
* that represents the contents of the XML file.
*
* Returns non-null Document instance if the file is found and
* properly parsed; otherwise it returns null.
*/
public static Document parse(String fileName)
{
return (parse(new File(fileName)));
}
public static Document parse(File file)
{
Document document = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
/* we don't validate (yet) because we get an exception if a
* schema/DTD is not specified in the document and we don't (yet)
* know how to avoid this.
*/
// factory.setValidating(true);
factory.setNamespaceAware(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(
new org.xml.sax.ErrorHandler() {
/* ignore fatal errors (an exception is guaranteed) */
public void fatalError(SAXParseException exception)
throws SAXException
{
}
/* treat validation errors as fatal */
public void error(SAXParseException e)
throws SAXParseException
{
throw e;
}
/* display warnings */
public void warning(SAXParseException err)
throws SAXParseException
{
System.out.println("Warning:"
+ " line " + err.getLineNumber()
+ ", uri " + err.getSystemId());
System.out.println(" " + err.getMessage());
}
}
);
/* parse the document */
/* NOTE: we use a FileInputStream to avoid a Java exception
* that occurs when a UNC path is used (e.g., //Sambasb/ztree/....)
* this may not be necessary with JVMs 1.4.2 and greater; see
* bugzilla 405
*/
document = builder.parse(
new BufferedInputStream(new FileInputStream(file))
);
/* BUG?: should we close the file stream here???? */
}
catch (SAXException sxe) {
/* Error generated during parsing */
System.err.println(sxe.getMessage());
// Exception x = sxe;
if (sxe.getException() != null) {
// x = sxe.getException();
}
// x.printStackTrace();
}
catch (ParserConfigurationException pce) {
/* Parser with specified options can't be built */
System.err.println(pce.getMessage());
// pce.printStackTrace();
}
catch (IOException ioe) {
/* I/O error */
ioe.printStackTrace();
}
return (document);
}
/*
* ======== main ========
* Read XML file specified on the command line, display its contents,
* and extract and display the "references".
*/
public static void main(String argv[])
{
if (argv.length != 1) {
System.err.println("Usage: java xdc.services.global.Vers filename");
System.exit(1);
}
Document doc = XML.parse(argv[0]);
if (doc != null) {
dump(doc);
System.out.println("\n target references:");
String [] refs = XML.getList(doc, "targets", "version");
for (int i = 0; i < refs.length; i++) {
System.out.println(" " + refs[i]);
}
}
}
/*
* ======== dump ========
* Print a representation of the model starting from node.
*/
static void dump(Node top)
{
dump(top, "");
}
static void dump(Node top, String prefix)
{
/* print top node */
System.out.println(prefix + nodeToString(top));
/* print all attributes of the top node */
org.w3c.dom.NamedNodeMap map = top.getAttributes();
if (map != null) {
for (int i = 0; i < map.getLength(); i++) {
dump(map.item(i), prefix + " ");
}
}
/* recursively dump all children of top */
NodeList nl = top.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
dump(nl.item(i), prefix + " ");
}
}
/*
* ======== nodeToString ========
*/
static String nodeToString(Node domNode)
{
/* An array of names for DOM node-types
* (Array indexes = nodeType() values.)
*/
String[] typeName = {
"none",
"Element",
"Attr",
"Text",
"CDATA",
"EntityRef",
"Entity",
"ProcInstr",
"Comment",
"Document",
"DocType",
"DocFragment",
"Notation",
};
/* Return a string that identifies this node in the tree
* (Refer to table at top of org.w3c.dom.Node)
*/
String s = typeName[domNode.getNodeType()];
String nodeName = domNode.getNodeName();
if (! nodeName.startsWith("#")) {
s += ": " + nodeName;
}
if (domNode.getNodeValue() != null) {
if (s.startsWith("ProcInstr")) {
s += ", ";
}
else {
s += ": ";
}
/* Trim the value to get rid of NL's at the front */
String t = domNode.getNodeValue().trim();
int x = t.indexOf("\n");
if (x >= 0) {
t = t.substring(0, x);
}
s += t;
}
return (s);
}
}