JiveProperties.java 10.9 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5 6 7 8 9 10 11 12 13
/**
 * $RCSfile$
 * $Revision$
 * $Date$
 *
 * Copyright (C) 1999-2004 Jive Software. All rights reserved.
 *
 * This software is the proprietary information of Jive Software.
 * Use is subject to license terms.
 */

package org.jivesoftware.util;

14
import org.jivesoftware.database.DbConnectionManager;
15
import org.jivesoftware.util.cache.CacheFactory;
16 17 18 19 20

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
Matt Tucker's avatar
Matt Tucker committed
21 22 23 24 25 26 27 28
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Retrieves and stores Jive properties. Properties are stored in the database.
 *
 * @author Matt Tucker
 */
29
public class JiveProperties implements Map<String, String> {
Matt Tucker's avatar
Matt Tucker committed
30 31 32 33 34 35

    private static final String LOAD_PROPERTIES = "SELECT name, propValue FROM jiveProperty";
    private static final String INSERT_PROPERTY = "INSERT INTO jiveProperty(name, propValue) VALUES(?,?)";
    private static final String UPDATE_PROPERTY = "UPDATE jiveProperty SET propValue=? WHERE name=?";
    private static final String DELETE_PROPERTY = "DELETE FROM jiveProperty WHERE name LIKE ?";

36 37 38 39 40 41
    private static class JivePropertyHolder {
        private static final JiveProperties instance = new JiveProperties();
        static {
            instance.init();
        }
    }
Matt Tucker's avatar
Matt Tucker committed
42 43 44 45 46 47 48 49

    private Map<String, String> properties;

    /**
     * Returns a singleton instance of JiveProperties.
     *
     * @return an instance of JiveProperties.
     */
50 51
    public static JiveProperties getInstance() {
        return JivePropertyHolder.instance;
Matt Tucker's avatar
Matt Tucker committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
    }

    private JiveProperties() {
    }

    /**
     * For internal use only. This method allows for the reloading of all properties from the
     * values in the datatabase. This is required since it's quite possible during the setup
     * process that a database connection will not be available till after this class is
     * initialized. Thus, if there are existing properties in the database we will want to reload
     * this class after the setup process has been completed.
     */
    public void init() {
        if (properties == null) {
            properties = new ConcurrentHashMap<String, String>();
        }
        else {
            properties.clear();
        }

        loadProperties();
    }

    public int size() {
        return properties.size();
    }

    public void clear() {
        throw new UnsupportedOperationException();
    }

    public boolean isEmpty() {
        return properties.isEmpty();
    }

    public boolean containsKey(Object key) {
        return properties.containsKey(key);
    }

    public boolean containsValue(Object value) {
        return properties.containsValue(value);
    }

95
    public Collection<String> values() {
Matt Tucker's avatar
Matt Tucker committed
96 97 98
        return Collections.unmodifiableCollection(properties.values());
    }

99 100
    public void putAll(Map<? extends String, ? extends String> t) {
        for (Map.Entry<? extends String, ? extends String> entry : t.entrySet() ) {
Matt Tucker's avatar
Matt Tucker committed
101 102 103 104
            put(entry.getKey(), entry.getValue());
        }
    }

105
    public Set<Map.Entry<String, String>> entrySet() {
Matt Tucker's avatar
Matt Tucker committed
106 107 108
        return Collections.unmodifiableSet(properties.entrySet());
    }

109
    public Set<String> keySet() {
Matt Tucker's avatar
Matt Tucker committed
110 111 112
        return Collections.unmodifiableSet(properties.keySet());
    }

113
    public String get(Object key) {
Matt Tucker's avatar
Matt Tucker committed
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 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
        return properties.get(key);
    }

    /**
     * Return all children property names of a parent property as a Collection
     * of String objects. 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>X.Y.A</tt>, <tt>X.Y.B</tt>, and <tt>X.Y.C</tt>. The method
     * is not recursive; ie, it does not return children of children.
     *
     * @param parentKey the name of the parent property.
     * @return all child property names for the given parent.
     */
    public Collection<String> getChildrenNames(String parentKey) {
        Collection<String> results = new HashSet<String>();
        for (String key : properties.keySet()) {
            if (key.startsWith(parentKey + ".")) {
                if (key.equals(parentKey)) {
                    continue;
                }
                int dotIndex = key.indexOf(".", parentKey.length()+1);
                if (dotIndex < 1) {
                    if (!results.contains(key)) {
                        results.add(key);
                    }
                }
                else {
                    String name = parentKey + key.substring(parentKey.length(), dotIndex);
                    results.add(name);
                }
            }
        }
        return results;
    }

    /**
     * Returns all property names as a Collection of String values.
     *
     * @return all property names.
     */
    public Collection<String> getPropertyNames() {
        return properties.keySet();
    }

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    public String remove(Object key) {
        String value;
        synchronized (this) {
            value = properties.remove(key);
            // Also remove any children.
            Collection<String> propNames = getPropertyNames();
            for (String name : propNames) {
                if (name.startsWith((String)key)) {
                    properties.remove(name);
                }
            }
            deleteProperty((String)key);
        }

        // Generate event.
        Map<String, Object> params = Collections.emptyMap();
        PropertyEventDispatcher.dispatchEvent((String)key, PropertyEventDispatcher.EventType.property_deleted, params);

        // Send update to other cluster members.
        CacheFactory.doClusterTask(PropertyClusterEventTask.createDeteleTask((String) key));

        return value;
    }

    void localRemove(String key) {
        properties.remove(key);
Matt Tucker's avatar
Matt Tucker committed
184
        // Also remove any children.
185 186
        Collection<String> propNames = getPropertyNames();
        for (String name : propNames) {
187
            if (name.startsWith(key)) {
Matt Tucker's avatar
Matt Tucker committed
188 189 190
                properties.remove(name);
            }
        }
191 192

        // Generate event.
193
        Map<String, Object> params = Collections.emptyMap();
194
        PropertyEventDispatcher.dispatchEvent(key, PropertyEventDispatcher.EventType.property_deleted, params);
Matt Tucker's avatar
Matt Tucker committed
195 196
    }

197
    public String put(String key, String value) {
Matt Tucker's avatar
Matt Tucker committed
198 199 200 201
        if (key == null || value == null) {
            throw new NullPointerException("Key or value cannot be null. Key=" +
                    key + ", value=" + value);
        }
202 203
        if (key.endsWith(".")) {
            key = key.substring(0, key.length()-1);
Matt Tucker's avatar
Matt Tucker committed
204
        }
205
        key = key.trim();
206 207 208 209 210 211 212 213 214
        String result;
        synchronized (this) {
            if (properties.containsKey(key)) {
                if (!properties.get(key).equals(value)) {
                    updateProperty(key, value);
                }
            }
            else {
                insertProperty(key, value);
Matt Tucker's avatar
Matt Tucker committed
215
            }
216

217 218
            result = properties.put(key, value);
        }
219

220
        // Generate event.
221
        Map<String, Object> params = new HashMap<String, Object>();
222
        params.put("value", value);
223
        PropertyEventDispatcher.dispatchEvent(key, PropertyEventDispatcher.EventType.property_set, params);
224

225 226 227
        // Send update to other cluster members.
        CacheFactory.doClusterTask(PropertyClusterEventTask.createPutTask(key, value));

228
        return result;
Matt Tucker's avatar
Matt Tucker committed
229 230
    }

231 232 233 234 235 236 237 238 239
    void localPut(String key, String value) {
        properties.put(key, value);

        // Generate event.
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("value", value);
        PropertyEventDispatcher.dispatchEvent(key, PropertyEventDispatcher.EventType.property_set, params);
    }

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    public String getProperty(String name, String defaultValue) {
        String value = properties.get(name);
        if (value != null) {
            return value;
        }
        else {
            return defaultValue;
        }
    }

    public boolean getBooleanProperty(String name) {
        return Boolean.valueOf(get(name));
    }

    public boolean getBooleanProperty(String name, boolean defaultValue) {
        String value = get(name);
        if (value != null) {
            return Boolean.valueOf(value);
        }
        else {
            return defaultValue;
        }
    }

Matt Tucker's avatar
Matt Tucker committed
264 265 266 267 268 269 270 271
    private void insertProperty(String name, String value) {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(INSERT_PROPERTY);
            pstmt.setString(1, name);
            pstmt.setString(2, value);
Derek DeMoro's avatar
Derek DeMoro committed
272
            pstmt.executeUpdate();
Matt Tucker's avatar
Matt Tucker committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
        }
        catch (SQLException e) {
            Log.error(e);
        }
        finally {
            try { if (pstmt != null) { pstmt.close(); } }
            catch (Exception e) { Log.error(e); }
            try { if (con != null) { con.close(); } }
            catch (Exception e) { Log.error(e); }
        }
    }

    private void updateProperty(String name, String value) {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(UPDATE_PROPERTY);
            pstmt.setString(1, value);
            pstmt.setString(2, name);
Derek DeMoro's avatar
Derek DeMoro committed
293
            pstmt.executeUpdate();
Matt Tucker's avatar
Matt Tucker committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
        }
        catch (SQLException e) {
            Log.error(e);
        }
        finally {
            try { if (pstmt != null) { pstmt.close(); } }
            catch (Exception e) { Log.error(e); }
            try { if (con != null) { con.close(); } }
            catch (Exception e) { Log.error(e); }
        }
    }

    private void deleteProperty(String name) {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(DELETE_PROPERTY);
            pstmt.setString(1, name + "%");
Derek DeMoro's avatar
Derek DeMoro committed
313
            pstmt.executeUpdate();
Matt Tucker's avatar
Matt Tucker committed
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
        }
        catch (SQLException e) {
            Log.error(e);
        }
        finally {
            try { if (pstmt != null) { pstmt.close(); } }
            catch (Exception e) { Log.error(e); }
            try { if (con != null) { con.close(); } }
            catch (Exception e) { Log.error(e); }
        }
    }

    private void loadProperties() {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(LOAD_PROPERTIES);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                String name = rs.getString(1);
                String value = rs.getString(2);
                properties.put(name, value);
            }
            rs.close();
        }
        catch (Exception e) {
            Log.error(e);
        }
        finally {
            try { if (pstmt != null) { pstmt.close(); } }
            catch (Exception e) { Log.error(e); }
            try { if (con != null) { con.close(); } }
            catch (Exception e) { Log.error(e); }
        }
    }
}