DefaultGroupPropertyMap.java 15.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
package org.jivesoftware.openfire.group;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.openfire.event.GroupEventDispatcher;
import org.jivesoftware.util.Immutable;
17
import org.jivesoftware.util.PersistableMap;
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Default implementation of a writable {@link Map} to manage group properties.
 * Updates made to the elements in this map will also be applied to the database.
 * Note this implementation assumes group property changes will be relatively
 * infrequent and therefore does not try to optimize database I/O for performance.
 * Each call to a {@link Map} mutator method (direct or indirect via {@link Iterator})
 * will result in a corresponding synchronous update to the database.
 * 
 * @param <K> Property key
 * @param <V> Property value
 */

33
public class DefaultGroupPropertyMap<K,V> extends PersistableMap<K,V> {
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

	private static final long serialVersionUID = 3128889631577167040L;
    private static final Logger logger = LoggerFactory.getLogger(DefaultGroupPropertyMap.class);

	// moved from {@link Group} as these are specific to the default provider
    private static final String DELETE_PROPERTY =
            "DELETE FROM ofGroupProp WHERE groupName=? AND name=?";
    private static final String DELETE_ALL_PROPERTIES =
            "DELETE FROM ofGroupProp WHERE groupName=?";
    private static final String UPDATE_PROPERTY =
        "UPDATE ofGroupProp SET propValue=? WHERE name=? AND groupName=?";
    private static final String INSERT_PROPERTY =
        "INSERT INTO ofGroupProp (groupName, name, propValue) VALUES (?, ?, ?)";

    private Group group;
	
    /**
     * Group properties map constructor; requires associated {@link Group} instance
     * @param group The group that owns these properties
     */
	public DefaultGroupPropertyMap(Group group) {
		this.group = group;
	}
	
	/**
	 * Custom method to put properties into the map, optionally without
	 * triggering persistence. This is used when the map is being 
	 * initially loaded from the database.
	 * 
	 * @param key The property name
	 * @param value The property value
	 * @param persist True if the changes should be persisted to the database
	 * @return The original value or null if the property did not exist
	 */
	public V put(K key, V value, boolean persist) {
		V originalValue = super.put(key, value);
		// we only support persistence for <String, String>
		if (persist && key instanceof String && value instanceof String) {
72 73
			if (logger.isDebugEnabled())
				logger.debug("Persisting group property [" + key + "]: " + value);
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 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 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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 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 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 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 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
			if (originalValue instanceof String) { // existing property		
				updateProperty((String)key, (String)value, (String)originalValue);
			} else {
				insertProperty((String)key, (String)value);
			}
		}
		return originalValue;
	}

	@Override
	public V put(K key, V value) {
		if (value == null) { // treat null value as "remove"
			return remove(key);
		} else {
			return put(key, value, true);
		}
	}
	
	@Override
	public V remove(Object key) {
		V result = super.remove(key);
		if (key instanceof String) {
			deleteProperty((String)key);
		}
		return result;
	}

	@Override
	public void clear() {
		super.clear();
		deleteAllProperties();
	}

	@Override
	public Set<K> keySet() {
		// custom class needed here to handle key.remove()
		return new PersistenceAwareKeySet<K>(super.keySet());
	}

	@Override
	public Collection<V> values() {
		// custom class needed here to suppress value.remove()
		return (Collection<V>) new Immutable.Collection<V>(super.values());
	}

	@Override
	public Set<Entry<K, V>> entrySet() {
		// custom class needed here to handle entrySet mutators
		return new PersistenceAwareEntrySet<Entry<K,V>>(super.entrySet());
	}

	/**
	 * Persistence-aware {@link Set} for group property keys. This class returns
	 * a custom iterator that can handle property removal.
	 */
	private class PersistenceAwareKeySet<E> extends AbstractSet<K> {

		private Set<K> delegate;
		
		/**
		 * Sole constructor; requires wrapped {@link Set} for delegation
		 * @param delegate A collection of keys from the map
		 */
		public PersistenceAwareKeySet(Set<K> delegate) {
			this.delegate = delegate;
		}

		@Override
		public Iterator<K> iterator() {
			return new KeyIterator<E>(delegate.iterator());
		}

		@Override
		public int size() {
			return delegate.size();
		}
	}

	/**
	 * This iterator updates the database when a property key is removed.
	 */
	private class KeyIterator<E> implements Iterator<K> {

		private Iterator<K> delegate;
		private K current;
		
		/**
		 * Sole constructor; requires wrapped {@link Iterator} for delegation
		 * @param delegate An iterator for all the keys from the map
		 */
		public KeyIterator(Iterator<K> delegate) {
			this.delegate = delegate;
		}
		
		/**
		 * Delegated to corresponding method in the backing {@link Iterator}
		 */
		public boolean hasNext() {
			return delegate.hasNext();
		}

		/**
		 * Delegated to corresponding method in the backing {@link Iterator}
		 */
		public K next() {
			current = delegate.next();
			return current;
		}

		/**
		 * Removes the property corresponding to the current key from
		 * the underlying map. Also applies update to the database.
		 */
		public void remove() {
			delegate.remove();
			if (current instanceof String) {
				deleteProperty((String)current);
			}
			current = null;
		}
	}
	
	/**
	 * Persistence-aware {@link Set} for group properties (as {@link Map.Entry})
	 */
	private class PersistenceAwareEntrySet<E> implements Set<Entry<K, V>> {

		private Set<Entry<K, V>> delegate;
		
		/**
		 * Sole constructor; requires wrapped {@link Set} for delegation
		 * @param delegate A collection of entries ({@link Map.Entry}) from the map
		 */
		public PersistenceAwareEntrySet(Set<Entry<K, V>> delegate) {
			this.delegate = delegate;
		}

		/**
		 * Returns a custom iterator for the entries in the backing map
		 */
		public Iterator<Entry<K, V>> iterator() {
			return new EntryIterator<Entry<K,V>>(delegate.iterator());
		}

		/**
		 * Removes the given key from the backing map, and applies the
		 * corresponding update to the database.
		 * 
		 * @param o A {@link Map.Entry} within this set
		 * @return True if the set contained the given key
		 */
		public boolean remove(Object o) {
			boolean propertyExists = delegate.remove(o);
			if (propertyExists) {
				deleteProperty((String)((Entry<K,V>)o).getKey());
			}
			return propertyExists;
		}

		/**
		 * Removes all the elements in the set, and applies the
		 * corresponding update to the database.
		 */
		public void clear() {
			delegate.clear();
			deleteAllProperties();
		}

		// these methods are problematic (and not really necessary),
		// so they are not implemented
		
		/**
		 * @throws UnsupportedOperationException
		 */
		public boolean removeAll(Collection<?> c) {
			throw new UnsupportedOperationException();
		}

		/**
		 * @throws UnsupportedOperationException
		 */
		public boolean retainAll(Collection<?> c) {
			throw new UnsupportedOperationException();
		}
		
		// per docs for {@link Map.entrySet}, these methods are not supported

		/**
		 * @throws UnsupportedOperationException
		 */
		public boolean add(Entry<K, V> o) {
			return delegate.add(o);
		}

		/**
		 * @throws UnsupportedOperationException
		 */
		public boolean addAll(Collection<? extends Entry<K, V>> c) {
			return delegate.addAll(c);
		}

		// remaining {@link Set} methods can be delegated safely
		
		/**
		 * Delegated to corresponding method in the backing {@link Set}
		 */
		public int size() {
			return delegate.size();
		}

		/**
		 * Delegated to corresponding method in the backing {@link Set}
		 */
		public boolean isEmpty() {
			return delegate.isEmpty();
		}

		/**
		 * Delegated to corresponding method in the backing {@link Set}
		 */
		public boolean contains(Object o) {
			return delegate.contains(o);
		}

		/**
		 * Delegated to corresponding method in the backing {@link Set}
		 */
		public Object[] toArray() {
			return delegate.toArray();
		}

		/**
		 * Delegated to corresponding method in the backing {@link Set}
		 */
		public <T> T[] toArray(T[] a) {
			return delegate.toArray(a);
		}

		/**
		 * Delegated to corresponding method in the backing {@link Set}
		 */
		public boolean containsAll(Collection<?> c) {
			return delegate.containsAll(c);
		}

		/**
		 * Delegated to corresponding method in the backing {@link Set}
		 */
		public boolean equals(Object o) {
			return delegate.equals(o);
		}

		/**
		 * Delegated to corresponding method in the backing {@link Set}
		 */
		public int hashCode() {
			return delegate.hashCode();
		}
	}

	/**
	 * Remove group property from the database when the {@link Iterator.remove}
	 * method is invoked via the {@link Map.entrySet} set
	 */
	private class EntryIterator<E> implements Iterator<Entry<K, V>> {

		private Iterator<Entry<K,V>> delegate;
		private EntryWrapper<E> current;
		
		/**
		 * Sole constructor; requires wrapped {@link Iterator} for delegation
		 * @param delegate An iterator for all the keys from the map
		 */
		public EntryIterator(Iterator<Entry<K,V>> delegate) {
			this.delegate = delegate;
		}
		/**
		 * Delegated to corresponding method in the backing {@link Iterator}
		 */
		public boolean hasNext() {
			return delegate.hasNext();
		}

		/**
		 * Delegated to corresponding method in the backing {@link Iterator}
		 */
		public Entry<K,V> next() {
			current = new EntryWrapper<E>(delegate.next());
			return current;
		}

		/**
		 * Removes the property corresponding to the current key from
		 * the underlying map. Also applies update to the database.
		 */
		public void remove() {
			delegate.remove();
			K key = current.getKey();
			if (key instanceof String) {
				deleteProperty((String)key);
			}
			current = null;
		}
	}
	
	/**
	 * Update the database when a group property is updated via {@link Map.Entry.setValue}
	 */
	private class EntryWrapper<E> implements Entry<K,V> {
		private Entry<K,V> delegate;

		/**
		 * Sole constructor; requires wrapped {@link Map.Entry} for delegation
		 * @param delegate The corresponding entry from the map
		 */
		public EntryWrapper(Entry<K,V> delegate) {
			this.delegate = delegate;
		}
		
		/**
		 * Delegated to corresponding method in the backing {@link Map.Entry}
		 */
		public K getKey() {
			return delegate.getKey();
		}
		
		/**
		 * Delegated to corresponding method in the backing {@link Map.Entry}
		 */
		public V getValue() {
			return delegate.getValue();
		}
		
		/**
		 * Set the value of the property corresponding to this entry. This
		 * method also updates the database as needed depending on the new
		 * property value. A null value will cause the property to be deleted
		 * from the database.
		 * 
		 * @param value The new property value
		 * @return The old value of the corresponding property
		 */
		public V setValue(V value) {
			V oldValue = delegate.setValue(value);
			K key = delegate.getKey();
			if (key instanceof String) {
				if (value instanceof String) {
					if (oldValue == null) {
						insertProperty((String) key, (String) value);
					} else if (!value.equals(oldValue)) {
						updateProperty((String)key,(String)value, (String)oldValue);
					}
				} else {
					deleteProperty((String)key);
				}
			}
			return oldValue;
		}
	}

	/**
	 * Persist a new group property to the database for the current group
	 * 
	 * @param key Property name
	 * @param value Property value
	 */
	private synchronized void insertProperty(String key, String value) {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(INSERT_PROPERTY);
            pstmt.setString(1, group.getName());
            pstmt.setString(2, key);
            pstmt.setString(3, value);
            pstmt.executeUpdate();
        }
        catch (SQLException e) {
            logger.error(e.getMessage(), e);
        }
        finally {
            DbConnectionManager.closeConnection(pstmt, con);
        }
        Map<String, Object> event = new HashMap<String, Object>();
        event.put("propertyKey", key);
        event.put("type", "propertyAdded");
        GroupEventDispatcher.dispatchEvent(group,
                GroupEventDispatcher.EventType.group_modified, event);
    }

	/**
	 * Update the value of an existing group property for the current group
	 * 
	 * @param key Property name
	 * @param value Property value
	 * @param originalValue Original property value
	 */
    private synchronized void updateProperty(String key, String value, String originalValue) {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(UPDATE_PROPERTY);
477 478
            pstmt.setString(1, value);
            pstmt.setString(2, key);
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 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 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
            pstmt.setString(3, group.getName());
            pstmt.executeUpdate();
        }
        catch (SQLException e) {
            logger.error(e.getMessage(), e);
        }
        finally {
            DbConnectionManager.closeConnection(pstmt, con);
        }
        Map<String, Object> event = new HashMap<String, Object>();
        event.put("propertyKey", key);
        event.put("type", "propertyModified");
        event.put("originalValue", originalValue);
        GroupEventDispatcher.dispatchEvent(group,
                GroupEventDispatcher.EventType.group_modified, event);
    }

    /**
     * Delete a group property from the database for the current group
     * 
     * @param key Property name
     */
    private synchronized void deleteProperty(String key) {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(DELETE_PROPERTY);
            pstmt.setString(1, group.getName());
            pstmt.setString(2, key);
            pstmt.executeUpdate();
        }
        catch (SQLException e) {
            logger.error(e.getMessage(), e);
        }
        finally {
            DbConnectionManager.closeConnection(pstmt, con);
        }
        Map<String, Object> event = new HashMap<String, Object>();
        event.put("type", "propertyDeleted");
        event.put("propertyKey", key);
        GroupEventDispatcher.dispatchEvent(group,
            GroupEventDispatcher.EventType.group_modified, event);
    }

    /**
     * Delete all properties from the database for the current group
     */
    private synchronized void deleteAllProperties() {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(DELETE_ALL_PROPERTIES);
            pstmt.setString(1, group.getName());
            pstmt.executeUpdate();
        }
        catch (SQLException e) {
            logger.error(e.getMessage(), e);
        }
        finally {
            DbConnectionManager.closeConnection(pstmt, con);
        }
        Map<String, Object> event = new HashMap<String, Object>();
        event.put("type", "propertyDeleted");
        event.put("propertyKey", "*");
        GroupEventDispatcher.dispatchEvent(group,
            GroupEventDispatcher.EventType.group_modified, event);
    }
}