package dev.db.biz.configuration.xml;
import dev.db.biz.configuration.xml.ex.XmlConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class XmlReadUtils {
private static final String ROOT_NODE_NAME = "root";
public XmlReadUtils() {
}
public static Node findNode( String name, Node rootNode ) {
if( name == null || rootNode == null ) {
return null;
}
NodeList configurationNodes = rootNode.getChildNodes();
for( int i = 0; i < configurationNodes.getLength(); i++ ) {
Node node = configurationNodes.item( i );
if( node == null || node.getNodeName() == null ) {
continue;
}
if( node.getNodeName().equals( name ) ) {
return node;
}
}
return null;
}
public static List<Node> findNodes( String name, Node rootNode ) {
if( name == null || rootNode == null ) {
return null;
}
NodeList configurationNodes = rootNode.getChildNodes();
List<Node> nodes = new ArrayList<Node>();
for( int i = 0; i < configurationNodes.getLength(); i++ ) {
Node node = configurationNodes.item( i );
if( node == null || node.getNodeName() == null ) {
continue;
}
if( node.getNodeName().equals( name ) ) {
nodes.add( node );
}
}
return nodes;
}
public static Document createConfigurationDocument( File configurationFilename ) throws XmlConfigurationException {
FileInputStream fis = null;
try {
fis = new FileInputStream( configurationFilename );
return createConfigurationDocument( fis );
} catch(FileNotFoundException ex ) {
throw new XmlConfigurationException( "Configuration file not found" , ex );
} finally {
if( fis != null ) {
try {
fis.close();
} catch(IOException e) {}
}
}
}
public static Document createConfigurationDocument( InputStream is ) throws XmlConfigurationException {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse( is );
doc.getDocumentElement().normalize();
return doc;
} catch ( Exception ex ){
throw new XmlConfigurationException( "Cannot create document" , ex );
}
}
public static Node getRootNode( Document doc ) {NodeList nodeList = doc.getElementsByTagName( ROOT_NODE_NAME );
if( nodeList.getLength() != 1 ) {
throw new IllegalArgumentException( "Invalid configuration object. Root element not found" );
}
return nodeList.item( 0 );
}
}