1 package org.opensrf.util;
9 * Config reader and accesor module. This module reads an XML config file,
10 * then loads the file into an internal config, whose values may be accessed
11 * by xpath-style lookup paths.
15 /** The globl config instance */
16 private static Config config;
17 /** The object form of the parsed config */
18 private Map configObject;
20 * The log parsing context. This is used as a prefix to the
21 * config item search path. This allows config XML chunks to
22 * be inserted into arbitrary XML files.
24 private String context;
26 public static Config global() {
32 * @param context The config context
34 public Config(String context) {
35 this.context = context;
39 * Sets the global config object.
40 * @param c The config object to use.
42 public static void setGlobalConfig(Config c) {
47 * Parses an XML config file.
48 * @param filename The path to the file to parse.
50 public void parse(String filename) throws ConfigException {
52 String xml = Utils.fileToString(filename);
53 JSONObject jobj = XML.toJSONObject(xml);
54 configObject = (Map) new JSONReader(jobj.toString()).readObject();
55 } catch(Exception e) {
56 throw new ConfigException("Error parsing config", e);
60 public static void setConfig(Config conf) {
64 public void setConfigObject(Map config) {
65 this.configObject = config;
68 protected Map getConfigObject() {
69 return this.configObject;
74 * Returns the configuration value found at the requested path.
75 * @param path The search path
76 * @return The config value, or null if no value exists at the given path.
77 * @throws ConfigException thrown if nothing is found at the path
79 public String getString(String path) throws ConfigException {
81 return (String) get(path);
82 } catch(Exception e) {
84 ConfigException("No config string found at " + path);
89 * Gets the int value at the given path
90 * @param path The search path
92 public int getInt(String path) throws ConfigException {
94 return Integer.parseInt(getString(path));
95 } catch(Exception e) {
97 ConfigException("No config int found at " + path);
102 * Returns the configuration object found at the requested path.
103 * @param path The search path
104 * @return The config value
105 * @throws ConfigException thrown if nothing is found at the path
107 public Object get(String path) throws ConfigException {
109 Object obj = Utils.findPath(configObject, context + path);
111 throw new ConfigException("");
113 } catch(Exception e) {
115 throw new ConfigException("No config object found at " + path);
120 * Returns the first item in the list found at the given path. If
121 * no list is found, ConfigException is thrown.
122 * @param path The search path
124 public Object getFirst(String path) throws ConfigException {
125 Object obj = get(path);
126 if(obj instanceof List)
127 return ((List) obj).get(0);
133 * Returns the config as a JSON string
135 public String toString() {
136 return new JSONWriter(configObject).write();