XMLProperties.java 22.3 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision$
 * $Date$
 *
6
 * Copyright (C) 2004 Jive Software. All rights reserved.
Matt Tucker's avatar
Matt Tucker committed
7
 *
8 9
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
Matt Tucker's avatar
Matt Tucker committed
10 11 12 13
 */

package org.jivesoftware.util;

14
import org.dom4j.CDATA;
15 16
import org.dom4j.Document;
import org.dom4j.Element;
17
import org.dom4j.Node;
18 19
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
20
import org.apache.commons.lang.StringEscapeUtils;
21

Matt Tucker's avatar
Matt Tucker committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
import java.io.*;
import java.util.*;

/**
 * Provides the the ability to use simple XML property files. Each property is
 * in the form X.Y.Z, which would map to an XML snippet of:
 * <pre>
 * &lt;X&gt;
 *     &lt;Y&gt;
 *         &lt;Z&gt;someValue&lt;/Z&gt;
 *     &lt;/Y&gt;
 * &lt;/X&gt;
 * </pre>
 * <p/>
 * The XML file is passed in to the constructor and must be readable and
 * writtable. Setting property values will automatically persist those value
 * to disk. The file encoding used is UTF-8.
 *
 * @author Derek DeMoro
 * @author Iain Shigeoka
 */
43
public class XMLProperties {
Matt Tucker's avatar
Matt Tucker committed
44 45

    private File file;
46
    private Document document;
Matt Tucker's avatar
Matt Tucker committed
47 48 49 50 51

    /**
     * Parsing the XML file every time we need a property is slow. Therefore,
     * we use a Map to cache property values that are accessed more than once.
     */
52
    private Map<String, String> propertyCache = new HashMap<String, String>();
Matt Tucker's avatar
Matt Tucker committed
53 54

    /**
Bill Lynch's avatar
Bill Lynch committed
55
     * Creates a new XMLPropertiesTest object.
Matt Tucker's avatar
Matt Tucker committed
56
     *
57 58 59
     * @param fileName the full path the file that properties should be read from
     *                 and written to.
     * @throws IOException if an error occurs loading the properties.
Matt Tucker's avatar
Matt Tucker committed
60
     */
61 62
    public XMLProperties(String fileName) throws IOException {
        this(new File(fileName));
Matt Tucker's avatar
Matt Tucker committed
63 64
    }

65 66 67 68 69 70 71 72 73 74 75
    /**
     * Loads XML properties from a stream.
     *
     * @param in the input stream of XML.
     * @throws IOException if an exception occurs when reading the stream.
     */
    public XMLProperties(InputStream in) throws IOException {
        Reader reader = new BufferedReader(new InputStreamReader(in));
        buildDoc(reader);
    }

Matt Tucker's avatar
Matt Tucker committed
76
    /**
Bill Lynch's avatar
Bill Lynch committed
77
     * Creates a new XMLPropertiesTest object.
Matt Tucker's avatar
Matt Tucker committed
78
     *
79 80
     * @param file the file that properties should be read from and written to.
     * @throws IOException if an error occurs loading the properties.
Matt Tucker's avatar
Matt Tucker committed
81
     */
82 83
    public XMLProperties(File file) throws IOException {
        this.file = file;
Matt Tucker's avatar
Matt Tucker committed
84 85 86 87 88 89 90 91
        if (!file.exists()) {
            // Attempt to recover from this error case by seeing if the
            // tmp file exists. It's possible that the rename of the
            // tmp file failed the last time Jive was running,
            // but that it exists now.
            File tempFile;
            tempFile = new File(file.getParentFile(), file.getName() + ".tmp");
            if (tempFile.exists()) {
92
                Log.error("WARNING: " + file.getName() + " was not found, but temp file from " +
Matt Tucker's avatar
Matt Tucker committed
93 94 95 96 97 98 99 100
                        "previous write operation was. Attempting automatic recovery." +
                        " Please check file for data consistency.");
                tempFile.renameTo(file);
            }
            // There isn't a possible way to recover from the file not
            // being there, so throw an error.
            else {
                throw new FileNotFoundException("XML properties file does not exist: "
101
                        + file.getName());
Matt Tucker's avatar
Matt Tucker committed
102 103 104 105
            }
        }
        // Check read and write privs.
        if (!file.canRead()) {
106
            throw new IOException("XML properties file must be readable: " + file.getName());
Matt Tucker's avatar
Matt Tucker committed
107 108
        }
        if (!file.canWrite()) {
109
            throw new IOException("XML properties file must be writable: " + file.getName());
Matt Tucker's avatar
Matt Tucker committed
110
        }
111 112 113

        FileReader reader = new FileReader(file);
        buildDoc(reader);
Matt Tucker's avatar
Matt Tucker committed
114 115 116 117 118 119 120 121 122
    }

    /**
     * Returns the value of the specified property.
     *
     * @param name the name of the property to get.
     * @return the value of the specified property.
     */
    public synchronized String getProperty(String name) {
Matt Tucker's avatar
Matt Tucker committed
123
        String value = propertyCache.get(name);
Matt Tucker's avatar
Matt Tucker committed
124 125 126 127 128 129
        if (value != null) {
            return value;
        }

        String[] propName = parsePropertyName(name);
        // Search for this property by traversing down the XML heirarchy.
130
        Element element = document.getRootElement();
131 132
        for (String aPropName : propName) {
            element = element.element(aPropName);
Matt Tucker's avatar
Matt Tucker committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
            if (element == null) {
                // This node doesn't match this part of the property name which
                // indicates this property doesn't exist so return null.
                return null;
            }
        }
        // At this point, we found a matching property, so return its value.
        // Empty strings are returned as null.
        value = element.getTextTrim();
        if ("".equals(value)) {
            return null;
        }
        else {
            // Add to cache so that getting property next time is fast.
            propertyCache.put(name, value);
            return value;
        }
    }

    /**
     * Return all values who's path matches the given property
     * name as a String array, or an empty array if the if there
     * are no children. This allows you to retrieve several values
     * with the same property name. For example, consider the
     * XML file entry:
     * <pre>
     * &lt;foo&gt;
     *     &lt;bar&gt;
     *         &lt;prop&gt;some value&lt;/prop&gt;
     *         &lt;prop&gt;other value&lt;/prop&gt;
     *         &lt;prop&gt;last value&lt;/prop&gt;
     *     &lt;/bar&gt;
     * &lt;/foo&gt;
     * </pre>
     * If you call getProperties("foo.bar.prop") will return a string array containing
     * {"some value", "other value", "last value"}.
     *
     * @param name the name of the property to retrieve
     * @return all child property values for the given node name.
     */
    public String[] getProperties(String name) {
        String[] propName = parsePropertyName(name);
        // Search for this property by traversing down the XML heirarchy,
        // stopping one short.
177
        Element element = document.getRootElement();
Matt Tucker's avatar
Matt Tucker committed
178 179 180 181 182 183 184 185 186 187
        for (int i = 0; i < propName.length - 1; i++) {
            element = element.element(propName[i]);
            if (element == null) {
                // This node doesn't match this part of the property name which
                // indicates this property doesn't exist so return empty array.
                return new String[]{};
            }
        }
        // We found matching property, return names of children.
        Iterator iter = element.elementIterator(propName[propName.length - 1]);
Matt Tucker's avatar
Matt Tucker committed
188
        List<String> props = new ArrayList<String>();
Matt Tucker's avatar
Matt Tucker committed
189 190 191 192 193 194 195 196 197
        String value;
        while (iter.hasNext()) {
            // Empty strings are skipped.
            value = ((Element)iter.next()).getTextTrim();
            if (!"".equals(value)) {
                props.add(value);
            }
        }
        String[] childrenNames = new String[props.size()];
Matt Tucker's avatar
Matt Tucker committed
198
        return props.toArray(childrenNames);
Matt Tucker's avatar
Matt Tucker committed
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    }

    /**
     * Return all values who's path matches the given property
     * name as a String array, or an empty array if the if there
     * are no children. This allows you to retrieve several values
     * with the same property name. For example, consider the
     * XML file entry:
     * <pre>
     * &lt;foo&gt;
     *     &lt;bar&gt;
     *         &lt;prop&gt;some value&lt;/prop&gt;
     *         &lt;prop&gt;other value&lt;/prop&gt;
     *         &lt;prop&gt;last value&lt;/prop&gt;
     *     &lt;/bar&gt;
     * &lt;/foo&gt;
     * </pre>
     * If you call getProperties("foo.bar.prop") will return a string array containing
     * {"some value", "other value", "last value"}.
     *
     * @param name the name of the property to retrieve
     * @return all child property values for the given node name.
     */
    public Iterator getChildProperties(String name) {
        String[] propName = parsePropertyName(name);
        // Search for this property by traversing down the XML heirarchy,
        // stopping one short.
226
        Element element = document.getRootElement();
Matt Tucker's avatar
Matt Tucker committed
227 228 229 230 231 232 233 234
        for (int i = 0; i < propName.length - 1; i++) {
            element = element.element(propName[i]);
            if (element == null) {
                // This node doesn't match this part of the property name which
                // indicates this property doesn't exist so return empty array.
                return Collections.EMPTY_LIST.iterator();
            }
        }
235
        // We found matching property, return values of the children.
Matt Tucker's avatar
Matt Tucker committed
236
        Iterator iter = element.elementIterator(propName[propName.length - 1]);
237
        ArrayList<String> props = new ArrayList<String>();
Matt Tucker's avatar
Matt Tucker committed
238
        while (iter.hasNext()) {
239
            props.add(((Element)iter.next()).getText());
Matt Tucker's avatar
Matt Tucker committed
240 241 242 243
        }
        return props.iterator();
    }

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    /**
     * Returns the value of the attribute of the given property name or <tt>null</tt>
     * if it doesn't exist. Note, this
     *
     * @param name the property name to lookup - ie, "foo.bar"
     * @param attribute the name of the attribute, ie "id"
     * @return the value of the attribute of the given property or <tt>null</tt> if
     *      it doesn't exist.
     */
    public String getAttribute(String name, String attribute) {
        if (name == null || attribute == null) {
            return null;
        }
        String[] propName = parsePropertyName(name);
        // Search for this property by traversing down the XML heirarchy.
        Element element = document.getRootElement();
260
        for (String child : propName) {
261 262 263 264 265 266 267 268 269 270 271 272 273 274
            element = element.element(child);
            if (element == null) {
                // This node doesn't match this part of the property name which
                // indicates this property doesn't exist so return empty array.
                break;
            }
        }
        if (element != null) {
            // Get its attribute values
            return element.attributeValue(attribute);
        }
        return null;
    }

Matt Tucker's avatar
Matt Tucker committed
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    /**
     * Sets a property to an array of values. Multiple values matching the same property
     * is mapped to an XML file as multiple elements containing each value.
     * For example, using the name "foo.bar.prop", and the value string array containing
     * {"some value", "other value", "last value"} would produce the following XML:
     * <pre>
     * &lt;foo&gt;
     *     &lt;bar&gt;
     *         &lt;prop&gt;some value&lt;/prop&gt;
     *         &lt;prop&gt;other value&lt;/prop&gt;
     *         &lt;prop&gt;last value&lt;/prop&gt;
     *     &lt;/bar&gt;
     * &lt;/foo&gt;
     * </pre>
     *
290 291
     * @param name the name of the property.
     * @param values the values for the property (can be empty but not null).
Matt Tucker's avatar
Matt Tucker committed
292
     */
293
    public void setProperties(String name, List<String> values) {
Matt Tucker's avatar
Matt Tucker committed
294 295 296
        String[] propName = parsePropertyName(name);
        // Search for this property by traversing down the XML heirarchy,
        // stopping one short.
297
        Element element = document.getRootElement();
Matt Tucker's avatar
Matt Tucker committed
298 299 300 301 302 303 304 305 306 307
        for (int i = 0; i < propName.length - 1; i++) {
            // If we don't find this part of the property in the XML heirarchy
            // we add it as a new node
            if (element.element(propName[i]) == null) {
                element.addElement(propName[i]);
            }
            element = element.element(propName[i]);
        }
        String childName = propName[propName.length - 1];
        // We found matching property, clear all children.
308
        List<Element> toRemove = new ArrayList<Element>();
Matt Tucker's avatar
Matt Tucker committed
309 310
        Iterator iter = element.elementIterator(childName);
        while (iter.hasNext()) {
311
            toRemove.add((Element) iter.next());
Matt Tucker's avatar
Matt Tucker committed
312 313 314 315
        }
        for (iter = toRemove.iterator(); iter.hasNext();) {
            element.remove((Element)iter.next());
        }
316 317
        // Add the new children.
        for (String value : values) {
318 319
            Element childElement = element.addElement(childName);
            if (value.startsWith("<![CDATA[")) {
320 321 322 323 324 325 326 327
                Iterator it = childElement.nodeIterator();
                while (it.hasNext()) {
                    Node node = (Node) it.next();
                    if (node instanceof CDATA) {
                        childElement.remove(node);
                        break;
                    }
                }
328 329 330
                childElement.addCDATA(value.substring(9, value.length()-3));
            }
            else {
331
                childElement.setText(StringEscapeUtils.escapeXml(value));
332
            }
Matt Tucker's avatar
Matt Tucker committed
333 334
        }
        saveProperties();
335 336

        // Generate event.
Matt Tucker's avatar
Matt Tucker committed
337
        Map<String, Object> params = new HashMap<String, Object>();
338
        params.put("value", values);
Matt Tucker's avatar
Matt Tucker committed
339
        PropertyEventDispatcher.dispatchEvent(name,
340
                PropertyEventDispatcher.EventType.xml_property_set, params);
Matt Tucker's avatar
Matt Tucker committed
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
    }

    /**
     * Return all children property names of a parent property as a String array,
     * or an empty array if the if there are no children. For example, given
     * the properties <tt>X.Y.A</tt>, <tt>X.Y.B</tt>, and <tt>X.Y.C</tt>, then
     * the child properties of <tt>X.Y</tt> are <tt>A</tt>, <tt>B</tt>, and
     * <tt>C</tt>.
     *
     * @param parent the name of the parent property.
     * @return all child property values for the given parent.
     */
    public String[] getChildrenProperties(String parent) {
        String[] propName = parsePropertyName(parent);
        // Search for this property by traversing down the XML heirarchy.
356
        Element element = document.getRootElement();
357 358
        for (String aPropName : propName) {
            element = element.element(aPropName);
Matt Tucker's avatar
Matt Tucker committed
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
            if (element == null) {
                // This node doesn't match this part of the property name which
                // indicates this property doesn't exist so return empty array.
                return new String[]{};
            }
        }
        // We found matching property, return names of children.
        List children = element.elements();
        int childCount = children.size();
        String[] childrenNames = new String[childCount];
        for (int i = 0; i < childCount; i++) {
            childrenNames[i] = ((Element)children.get(i)).getName();
        }
        return childrenNames;
    }

    /**
     * Sets the value of the specified property. If the property doesn't
     * currently exist, it will be automatically created.
     *
     * @param name  the name of the property to set.
     * @param value the new value for the property.
     */
    public synchronized void setProperty(String name, String value) {
383 384 385
        if(!StringEscapeUtils.escapeXml(name).equals(name)) {
            throw new IllegalArgumentException("Property name cannot contain XML entities.");
        }
386 387 388 389 390 391
        if (name == null) {
            return;
        }
        if (value == null) {
            value = "";
        }
Matt Tucker's avatar
Matt Tucker committed
392 393 394 395 396 397

        // Set cache correctly with prop name and value.
        propertyCache.put(name, value);

        String[] propName = parsePropertyName(name);
        // Search for this property by traversing down the XML heirarchy.
398
        Element element = document.getRootElement();
399
        for (String aPropName : propName) {
Matt Tucker's avatar
Matt Tucker committed
400 401
            // If we don't find this part of the property in the XML heirarchy
            // we add it as a new node
402 403
            if (element.element(aPropName) == null) {
                element.addElement(aPropName);
Matt Tucker's avatar
Matt Tucker committed
404
            }
405
            element = element.element(aPropName);
Matt Tucker's avatar
Matt Tucker committed
406 407
        }
        // Set the value of the property in this node.
408
        if (value.startsWith("<![CDATA[")) {
409 410 411 412 413 414 415 416
            Iterator it = element.nodeIterator();
            while (it.hasNext()) {
                Node node = (Node) it.next();
                if (node instanceof CDATA) {
                    element.remove(node);
                    break;
                }
            }
417 418 419
            element.addCDATA(value.substring(9, value.length()-3));
        }
        else {
420
            element.setText(value);
421
        }
422
        // Write the XML properties to disk
Matt Tucker's avatar
Matt Tucker committed
423
        saveProperties();
424 425

        // Generate event.
426
        Map<String, Object> params = new HashMap<String, Object>();
427
        params.put("value", value);
Matt Tucker's avatar
Matt Tucker committed
428
        PropertyEventDispatcher.dispatchEvent(name,
429
                PropertyEventDispatcher.EventType.xml_property_set, params);
Matt Tucker's avatar
Matt Tucker committed
430 431 432 433 434 435 436 437 438 439 440 441 442
    }

    /**
     * Deletes the specified property.
     *
     * @param name the property to delete.
     */
    public synchronized void deleteProperty(String name) {
        // Remove property from cache.
        propertyCache.remove(name);

        String[] propName = parsePropertyName(name);
        // Search for this property by traversing down the XML heirarchy.
443
        Element element = document.getRootElement();
Matt Tucker's avatar
Matt Tucker committed
444 445 446 447 448 449 450 451 452 453 454
        for (int i = 0; i < propName.length - 1; i++) {
            element = element.element(propName[i]);
            // Can't find the property so return.
            if (element == null) {
                return;
            }
        }
        // Found the correct element to remove, so remove it...
        element.remove(element.element(propName[propName.length - 1]));
        // .. then write to disk.
        saveProperties();
455 456

        // Generate event.
457 458
        Map<String, Object> params = Collections.emptyMap();
        PropertyEventDispatcher.dispatchEvent(name, PropertyEventDispatcher.EventType.xml_property_deleted, params);
Matt Tucker's avatar
Matt Tucker committed
459 460
    }

461 462
    /**
     * Builds the document XML model up based the given reader of XML data.
463 464
     * @param in the input stream used to build the xml document
     * @throws java.io.IOException thrown when an error occurs reading the input stream.
465 466 467 468
     */
    private void buildDoc(Reader in) throws IOException {
        try {
            SAXReader xmlReader = new SAXReader();
469
            xmlReader.setEncoding("UTF-8");
470 471 472 473 474 475 476 477 478 479 480 481 482
            document = xmlReader.read(in);
        }
        catch (Exception e) {
            Log.error("Error reading XML properties", e);
            throw new IOException(e.getMessage());
        }
        finally {
            if (in != null) {
                in.close();
            }
        }
    }

Matt Tucker's avatar
Matt Tucker committed
483 484 485 486 487 488 489 490 491 492 493
    /**
     * Saves the properties to disk as an XML document. A temporary file is
     * used during the writing process for maximum safety.
     */
    private synchronized void saveProperties() {
        boolean error = false;
        // Write data out to a temporary file first.
        File tempFile = null;
        Writer writer = null;
        try {
            tempFile = new File(file.getParentFile(), file.getName() + ".tmp");
494
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8"));
495 496 497
            OutputFormat prettyPrinter = OutputFormat.createPrettyPrint();
            XMLWriter xmlWriter = new XMLWriter(writer, prettyPrinter);
            xmlWriter.write(document);
Matt Tucker's avatar
Matt Tucker committed
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
        }
        catch (Exception e) {
            Log.error(e);
            // There were errors so abort replacing the old property file.
            error = true;
        }
        finally {
            if (writer != null) {
                try {
                    writer.close();
                }
                catch (IOException e1) {
                    Log.error(e1);
                    error = true;
                }
            }
        }

        // No errors occured, so delete the main file.
        if (!error) {
            // Delete the old file so we can replace it.
            if (!file.delete()) {
                Log.error("Error deleting property file: " + file.getAbsolutePath());
                return;
            }
            // Copy new contents to the file.
            try {
525
                copy(tempFile, file);
Matt Tucker's avatar
Matt Tucker committed
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
            }
            catch (Exception e) {
                Log.error(e);
                // There were errors so abort replacing the old property file.
                error = true;
            }
            // If no errors, delete the temp file.
            if (!error) {
                tempFile.delete();
            }
        }
    }

    /**
     * Returns an array representation of the given Jive property. Jive
     * properties are always in the format "prop.name.is.this" which would be
     * represented as an array of four Strings.
     *
     * @param name the name of the Jive property.
     * @return an array representation of the given Jive property.
     */
    private String[] parsePropertyName(String name) {
Matt Tucker's avatar
Matt Tucker committed
548
        List<String> propName = new ArrayList<String>(5);
Matt Tucker's avatar
Matt Tucker committed
549 550 551 552 553
        // Use a StringTokenizer to tokenize the property name.
        StringTokenizer tokenizer = new StringTokenizer(name, ".");
        while (tokenizer.hasMoreTokens()) {
            propName.add(tokenizer.nextToken());
        }
Matt Tucker's avatar
Matt Tucker committed
554
        return propName.toArray(new String[propName.size()]);
Matt Tucker's avatar
Matt Tucker committed
555 556
    }

Matt Tucker's avatar
Matt Tucker committed
557 558 559
    public void setProperties(Map<String, String> propertyMap) {
        for (String propertyName : propertyMap.keySet()) {
            String propertyValue = propertyMap.get(propertyName);
Matt Tucker's avatar
Matt Tucker committed
560 561
            setProperty(propertyName, propertyValue);
        }
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
    }

    /**
     * Copies the inFile to the outFile.
     *
     * @param inFile  The file to copy from
     * @param outFile The file to copy to
     * @throws IOException If there was a problem making the copy
     */
    private static void copy(File inFile, File outFile) throws IOException {
        FileInputStream fin = null;
        FileOutputStream fout = null;
        try {
            fin = new FileInputStream(inFile);
            fout = new FileOutputStream(outFile);
            copy(fin, fout);
        }
        finally {
            try {
                if (fin != null) fin.close();
            }
            catch (IOException e) {
                // do nothing
            }
            try {
                if (fout != null) fout.close();
            }
            catch (IOException e) {
                // do nothing
            }
        }
    }

    /**
     * Copies data from an input stream to an output stream
     *
598 599 600
     * @param in the stream to copy data from.
     * @param out the stream to copy data to.
     * @throws IOException if there's trouble during the copy.
601 602
     */
    private static void copy(InputStream in, OutputStream out) throws IOException {
603
        // Do not allow other threads to intrude on streams during copy.
604 605 606 607 608 609 610 611 612 613
        synchronized (in) {
            synchronized (out) {
                byte[] buffer = new byte[256];
                while (true) {
                    int bytesRead = in.read(buffer);
                    if (bytesRead == -1) break;
                    out.write(buffer, 0, bytesRead);
                }
            }
        }
Matt Tucker's avatar
Matt Tucker committed
614 615
    }
}