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;
27 * @param context The config context
29 public Config(String context) {
30 this.context = context;
34 * Sets the global config object.
35 * @param c The config object to use.
37 public static void setConfig(Config c) {
42 * Parses an XML config file.
43 * @param filename The path to the file to parse.
45 public void parse(String filename) throws Exception {
46 String xml = Utils.fileToString(filename);
47 JSONObject jobj = XML.toJSONObject(xml);
48 configObject = (Map) new JSONReader(jobj.toString()).readObject();
52 * Returns the configuration value found at the requested path.
53 * @see org.opensrf.util.Utils.findPath for path description.
54 * @param path The search path
55 * @return The config value, or null if no value exists at the given path.
56 * @throws ConfigException thrown if nothing is found at the path
58 public static String getString(String path) throws ConfigException {
60 return (String) get(path);
61 } catch(Exception e) {
63 ConfigException("No config string found at " + path);
68 * Gets the int value at the given path
69 * @param path The search path
71 public static int getInt(String path) throws ConfigException {
73 return Integer.parseInt(getString(path));
74 } catch(Exception e) {
76 ConfigException("No config int found at " + path);
81 * Returns the configuration object found at the requested path.
82 * @see org.opensrf.util.Utils.findPath for path description.
83 * @param path The search path
84 * @return The config value
85 * @throws ConfigException thrown if nothing is found at the path
87 public static Object get(String path) throws ConfigException {
89 Object obj = Utils.findPath(config.configObject, config.context + path);
91 throw new ConfigException("");
93 } catch(Exception e) {
95 throw new ConfigException("No config object found at " + path);
100 * Returns the first item in the list found at the given path. If
101 * no list is found, ConfigException is thrown.
102 * @param path The search path
104 public static Object getFirst(String path) throws ConfigException {
105 Object obj = get(path);
106 if(obj instanceof List)
107 return ((List) obj).get(0);
113 * Returns the config as a JSON string
115 public String toString() {
116 return new JSONWriter(configObject).write();