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;
19 private String context;
21 public Config(String context) {
22 this.context = context;
26 * Sets the global config object.
27 * @param c The config object to use.
29 public static void setConfig(Config c) {
34 * Parses an XML config file.
35 * @param filename The path to the file to parse.
37 public void parse(String filename) throws Exception {
38 String xml = Utils.fileToString(filename);
39 JSONObject jobj = XML.toJSONObject(xml);
40 configObject = (Map) new JSONReader(jobj.toString()).readObject();
44 * Returns the configuration value found at the requested path.
45 * @see org.opensrf.util.Utils.findPath for path description.
46 * @param path The search path
47 * @return The config value, or null if no value exists at the given path.
48 * @throws ConfigException thrown if nothing is found at the path
50 public static String getString(String path) throws ConfigException {
52 return (String) get(path);
53 } catch(Exception e) {
55 ConfigException("No config string found at " + path);
60 * Returns the configuration object found at the requested path.
61 * @see org.opensrf.util.Utils.findPath for path description.
62 * @param path The search path
63 * @return The config value
64 * @throws ConfigException thrown if nothing is found at the path
66 public static Object get(String path) throws ConfigException {
68 Object obj = Utils.findPath(config.configObject, config.context + path);
70 throw new ConfigException("");
72 } catch(Exception e) {
74 throw new ConfigException("No config object found at " + path);
78 public static Object getFirst(String path) throws ConfigException {
79 Object obj = get(path);
80 if(obj instanceof List)
81 return ((List) obj).get(0);
87 * Returns the config as a JSON string
89 public String toString() {
90 return new JSONWriter(configObject).write();