001: package org.shiftone.cache.config;
002:
003: import org.shiftone.cache.ConfigurationException;
004: import org.shiftone.cache.util.Log;
005:
006: import java.io.PrintStream;
007: import java.util.*;
008:
009: /**
010: * @version $Revision: 1.5 $
011: * @author <a href="mailto:jeff@shiftone.org">Jeff Drost</a>
012: */
013: public class PropertiesTree {
014:
015: private static final Log LOG = new Log(PropertiesTree.class);
016: private Node root = null;
017:
018: /**
019: * Constructor PropertiesTree
020: */
021: public PropertiesTree() throws ConfigurationException {
022: initialize(new Properties());
023: }
024:
025: /**
026: * Constructor PropertiesTree
027: */
028: public PropertiesTree(Properties properties)
029: throws ConfigurationException {
030: initialize(properties);
031: }
032:
033: /**
034: * Method initialize
035: */
036: private void initialize(Properties properties)
037: throws ConfigurationException {
038:
039: this .root = new Node("ROOT", null);
040:
041: Enumeration keys = properties.keys();
042:
043: while (keys.hasMoreElements()) {
044: String key = (String) keys.nextElement();
045: String value = properties.getProperty(key);
046:
047: root.createNode(key, value);
048: }
049: }
050:
051: /**
052: * Regenerates a Properties object based on the tree.
053: */
054: public Properties getProperties() {
055:
056: Properties properties = new Properties();
057:
058: populateProperties(properties, root, "");
059:
060: return properties;
061: }
062:
063: /**
064: * Method populateProperties
065: */
066: private void populateProperties(Properties properties, Node node,
067: String prefix) {
068:
069: Collection children = node.getChildren();
070: Iterator i = children.iterator();
071:
072: while (i.hasNext()) {
073: Node child = (Node) i.next();
074: String key = prefix + child.getKey();
075: String value = child.getValue();
076:
077: if (value != null) {
078: properties.setProperty(key, value);
079: }
080:
081: populateProperties(properties, child, key + ".");
082: }
083: }
084:
085: /**
086: * Method getRoot
087: *
088: * @return .
089: */
090: public Node getRoot() {
091: return root;
092: }
093:
094: /**
095: * Prints out the tree in a cheezy XML like format
096: */
097: public void print(PrintStream out) {
098: root.print();
099: }
100:
101: public static String[] tokenize(String text) {
102: return tokenize(text, ".");
103: }
104:
105: public static String[] tokenize(String text, String token) {
106:
107: StringTokenizer tokenizer = new StringTokenizer(text, token,
108: false);
109: List list = new ArrayList(5);
110: String[] array;
111:
112: while (tokenizer.hasMoreTokens()) {
113: list.add(tokenizer.nextToken());
114: }
115:
116: array = new String[list.size()];
117: array = (String[]) list.toArray(array);
118:
119: return array;
120: }
121: }
|