DefaultGroupPropertyMap.java 16.1 KB
Newer Older
1 2 3 4 5 6 7
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;
8
import java.util.Collections;
9 10 11 12 13 14 15 16
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;
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

	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
	 */
68
	@Override
69 70 71 72
	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) {
73 74
			if (logger.isDebugEnabled())
				logger.debug("Persisting group property [" + key + "]: " + value);
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
			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()
117
		return Collections.unmodifiableCollection(super.values());
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
	}

	@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}
		 */
172
		@Override
173 174 175 176 177 178 179
		public boolean hasNext() {
			return delegate.hasNext();
		}

		/**
		 * Delegated to corresponding method in the backing {@link Iterator}
		 */
180
		@Override
181 182 183 184 185 186 187 188 189
		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.
		 */
190
		@Override
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
		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
		 */
218
		@Override
219 220 221 222 223 224 225 226 227 228 229
		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
		 */
230
		@Override
231 232 233 234 235 236 237 238 239 240 241 242
		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.
		 */
243
		@Override
244 245 246 247 248 249 250 251 252 253 254
		public void clear() {
			delegate.clear();
			deleteAllProperties();
		}

		// these methods are problematic (and not really necessary),
		// so they are not implemented
		
		/**
		 * @throws UnsupportedOperationException
		 */
255
		@Override
256 257 258 259 260 261 262
		public boolean removeAll(Collection<?> c) {
			throw new UnsupportedOperationException();
		}

		/**
		 * @throws UnsupportedOperationException
		 */
263
		@Override
264 265 266 267 268 269 270 271 272
		public boolean retainAll(Collection<?> c) {
			throw new UnsupportedOperationException();
		}
		
		// per docs for {@link Map.entrySet}, these methods are not supported

		/**
		 * @throws UnsupportedOperationException
		 */
273
		@Override
274 275 276 277 278 279 280
		public boolean add(Entry<K, V> o) {
			return delegate.add(o);
		}

		/**
		 * @throws UnsupportedOperationException
		 */
281
		@Override
282 283 284 285 286 287 288 289 290
		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}
		 */
291
		@Override
292 293 294 295 296 297 298
		public int size() {
			return delegate.size();
		}

		/**
		 * Delegated to corresponding method in the backing {@link Set}
		 */
299
		@Override
300 301 302 303 304 305 306
		public boolean isEmpty() {
			return delegate.isEmpty();
		}

		/**
		 * Delegated to corresponding method in the backing {@link Set}
		 */
307
		@Override
308 309 310 311 312 313 314
		public boolean contains(Object o) {
			return delegate.contains(o);
		}

		/**
		 * Delegated to corresponding method in the backing {@link Set}
		 */
315
		@Override
316 317 318 319 320 321 322
		public Object[] toArray() {
			return delegate.toArray();
		}

		/**
		 * Delegated to corresponding method in the backing {@link Set}
		 */
323
		@Override
324 325 326 327 328 329 330
		public <T> T[] toArray(T[] a) {
			return delegate.toArray(a);
		}

		/**
		 * Delegated to corresponding method in the backing {@link Set}
		 */
331
		@Override
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
		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}
		 */
370
		@Override
371 372 373 374 375 376 377
		public boolean hasNext() {
			return delegate.hasNext();
		}

		/**
		 * Delegated to corresponding method in the backing {@link Iterator}
		 */
378
		@Override
379
		public Entry<K,V> next() {
380
			current = new EntryWrapper<>(delegate.next());
381 382 383 384 385 386 387
			return current;
		}

		/**
		 * Removes the property corresponding to the current key from
		 * the underlying map. Also applies update to the database.
		 */
388
		@Override
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
		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}
		 */
416
		@Override
417 418 419 420 421 422 423
		public K getKey() {
			return delegate.getKey();
		}
		
		/**
		 * Delegated to corresponding method in the backing {@link Map.Entry}
		 */
424
		@Override
425 426 427 428 429 430 431 432 433 434 435 436 437
		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
		 */
438
		@Override
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 477 478 479
		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);
        }
480
        Map<String, Object> event = new HashMap<>();
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
        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);
500 501
            pstmt.setString(1, value);
            pstmt.setString(2, key);
502 503 504 505 506 507 508 509 510
            pstmt.setString(3, group.getName());
            pstmt.executeUpdate();
        }
        catch (SQLException e) {
            logger.error(e.getMessage(), e);
        }
        finally {
            DbConnectionManager.closeConnection(pstmt, con);
        }
511
        Map<String, Object> event = new HashMap<>();
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
        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);
        }
540
        Map<String, Object> event = new HashMap<>();
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
        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);
        }
565
        Map<String, Object> event = new HashMap<>();
566 567 568 569 570 571
        event.put("type", "propertyDeleted");
        event.put("propertyKey", "*");
        GroupEventDispatcher.dispatchEvent(group,
            GroupEventDispatcher.EventType.group_modified, event);
    }
}