📄 readerutils.java
字号:
/* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, availible at the root
* application directory.
*/
package org.geoserver.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.ConfigurationException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
/**
* ReaderUtils purpose.
*
* <p>
* This class is intended to be used as a library of XML relevant operation for
* the XMLConfigReader class.
* </p>
*
* <p></p>
*
* @author dzwiers, Refractions Research, Inc.
* @version $Id: ReaderUtils.java 7746 2007-11-13 15:38:35Z aaime $
*
* @see XMLConfigReader
*/
public class ReaderUtils {
/** Used internally to create log information to detect errors. */
private static final Logger LOGGER = org.geotools.util.logging.Logging.getLogger("org.vfny.geoserver.global");
/**
* ReaderUtils constructor.
*
* <p>
* Static class, this should never be called.
* </p>
*/
private ReaderUtils() {
}
/**
* Parses the specified reader into a DOM tree.
*
* @param xml Reader representing xml stream to parse.
*
* @return the root element of resulting DOM tree
*
* @throws RuntimeException If reader failed to parse properly.
*/
public static Element parse(Reader xml) {
InputSource in = new InputSource(xml);
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setNamespaceAware(false);
dfactory.setValidating(false);
dfactory.setIgnoringComments(true);
dfactory.setCoalescing(true);
dfactory.setIgnoringElementContentWhitespace(true);
Document doc;
try {
doc = dfactory.newDocumentBuilder().parse(in);
} catch (Exception e) {
String msg = "Error reading : " + xml;
throw new RuntimeException(msg, e);
}
return doc.getDocumentElement();
}
/**
* Checks to ensure the file is valid.
*
* <p>
* Returns the file passed in to allow this to wrap file creations.
* </p>
*
* @param file A file Handle to test.
* @param isDir true when the File passed in is expected to be a directory,
* false when the handle is expected to be a file.
*
* @return the File handle passed in
*
* @throws Exception When the file does not exist or is not
* the type specified.
*/
public static File checkFile(File file, boolean isDir)
throws FileNotFoundException {
if (!file.exists()) {
throw new FileNotFoundException((isDir ? "Folder" : "File") + " does not exist: "
+ file);
}
if (isDir && !file.isDirectory()) {
throw new FileNotFoundException("File exists but is not a directory:" + file);
}
if (!isDir && !file.isFile()) {
//may it be some sort of OS special file (e.g. /dev/tty1)
throw new FileNotFoundException("File exists but is not a regular file:" + file);
}
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer(new StringBuffer("File is valid: ").append(file).toString());
}
return file;
}
/**
* getChildElements purpose.
*
* <p>
* Used to help with XML manipulations. Returns *all* child elements of
* the specified name.
* </p>
*
* @param root The root element to look for children in.
* @param name The name of the child element to look for.
*
* @return The child element found, null if not found.
*
* @see getChildElement(Element,String,boolean)
*/
public static Element[] getChildElements(Element root, String name) {
try {
return getChildElements(root, name, false);
} catch (Exception e) {
//will never be here.
return null;
}
}
/**
* getChildElements purpose.
*
* <p>
* Used to help with XML manipulations. Returns *all* child elements of
* the specified name. An exception occurs when the node is required and
* not found.
* </p>
*
* @param root The root element to look for children in.
* @param name The name of the child element to look for.
* @param mandatory true when an exception should be thrown if the child
* element does not exist.
*
* @return The child element found, null if not found.
*
* @throws Exception When a child element is required and not
* found.
*/
public static Element[] getChildElements(Element root, String name, boolean mandatory)
throws Exception {
ArrayList elements = new ArrayList();
Node child = root.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
if (name.equals(child.getNodeName())) {
elements.add((Element) child);
}
}
child = child.getNextSibling();
}
if (mandatory && (elements.isEmpty())) {
throw new Exception(root.getNodeName() + " does not contains a child element named "
+ name);
}
return (Element[]) elements.toArray(new Element[0]);
}
/**
* getChildElement purpose.
*
* <p>
* Used to help with XML manipulations. Returns the first child element of
* the specified name. An exception occurs when the node is required and
* not found.
* </p>
*
* @param root The root element to look for children in.
* @param name The name of the child element to look for.
* @param mandatory true when an exception should be thrown if the child
* element does not exist.
*
* @return The child element found, null if not found.
*
* @throws Exception When a child element is required and not
* found.
*/
public static Element getChildElement(Element root, String name, boolean mandatory)
throws Exception {
Node child = root.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
if (name.equals(child.getNodeName())) {
return (Element) child;
}
}
child = child.getNextSibling();
}
if (mandatory && (child == null)) {
throw new Exception(root.getNodeName() + " does not contains a child element named "
+ name);
}
return null;
}
/**
* getChildElement purpose.
*
* <p>
* Used to help with XML manipulations. Returns the first child element of
* the specified name.
* </p>
*
* @param root The root element to look for children in.
* @param name The name of the child element to look for.
*
* @return The child element found, null if not found.
*
* @see getChildElement(Element,String,boolean)
*/
public static Element getChildElement(Element root, String name) {
try {
return getChildElement(root, name, false);
} catch (Exception e) {
//will never be here.
return null;
}
}
/**
* getIntAttribute purpose.
*
* <p>
* Used to help with XML manipulations. Returns the first child integer
* attribute of the specified name. An exception occurs when the node is
* required and not found.
* </p>
*
* @param elem The root element to look for children in.
* @param attName The name of the attribute to look for.
* @param mandatory true when an exception should be thrown if the
* attribute element does not exist.
* @param defaultValue a default value to return incase the attribute was
* not found. mutually exclusive with the Exception
* thrown.
*
* @return The int value if the attribute was found, the default otherwise.
*
* @throws Exception When a attribute element is required and
* not found.
*/
public static int getIntAttribute(Element elem, String attName, boolean mandatory,
int defaultValue) throws Exception {
String attValue = getAttribute(elem, attName, mandatory);
if (!mandatory && (attValue == null)) {
return defaultValue;
}
try {
return Integer.parseInt(attValue);
} catch (Exception ex) {
if (mandatory) {
throw new Exception(attName + " attribute of element " + elem.getNodeName()
+ " must be an integer, but it's '" + attValue + "'");
} else {
return defaultValue;
}
}
}
/**
* getIntAttribute purpose.
*
* <p>
* Used to help with XML manipulations. Returns the first child integer
* attribute of the specified name. An exception occurs when the node is
* required and not found.
* </p>
*
* @param elem The root element to look for children in.
* @param attName The name of the attribute to look for.
* @param mandatory true when an exception should be thrown if the
* attribute element does not exist.
*
* @return The value if the attribute was found, the null otherwise.
*
* @throws Exception When a child attribute is required and
* not found.
* @throws NullPointerException DOCUMENT ME!
*/
public static String getAttribute(Element elem, String attName, boolean mandatory)
throws Exception {
if (elem == null) {
if (mandatory) {
throw new NullPointerException();
}
return "";
}
Attr att = elem.getAttributeNode(attName);
String value = null;
if (att != null) {
value = att.getValue();
}
if (mandatory) {
if (att == null) {
throw new Exception("element " + elem.getNodeName()
+ " does not contains an attribute named " + attName);
} else if ("".equals(value)) {
throw new Exception("attribute " + attName + "in element " + elem.getNodeName()
+ " is empty");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -