001 /**
002 * GRANITE DATA SERVICES
003 * Copyright (C) 2006-2013 GRANITE DATA SERVICES S.A.S.
004 *
005 * This file is part of Granite Data Services.
006 *
007 * Granite Data Services is free software; you can redistribute it and/or modify
008 * it under the terms of the GNU Library General Public License as published by
009 * the Free Software Foundation; either version 2 of the License, or (at your
010 * option) any later version.
011 *
012 * Granite Data Services is distributed in the hope that it will be useful, but
013 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
014 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
015 * for more details.
016 *
017 * You should have received a copy of the GNU Library General Public License
018 * along with this library; if not, see <http://www.gnu.org/licenses/>.
019 */
020 package org.granite.client.persistence.collection;
021
022 import java.io.ObjectInput;
023 import java.util.HashMap;
024 import java.util.Map;
025 import java.util.SortedMap;
026
027 import org.granite.messaging.persistence.PersistentCollectionSnapshot;
028
029 /**
030 * @author Franck WOLFF
031 */
032 public class PersistentMap<K, V> extends AbstractPersistentMapCollection<K, V, Map<K, V>> implements Map<K, V> {
033
034 public PersistentMap() {
035 }
036
037 public PersistentMap(boolean initialized) {
038 this(initialized ? new HashMap<K, V>() : null, false);
039 }
040
041 public PersistentMap(Map<K, V> collection) {
042 this(collection, true);
043 }
044
045 public PersistentMap(Map<K, V> collection, boolean clone) {
046 if (collection instanceof SortedMap)
047 throw new IllegalArgumentException("Should not be a SortedMap: " + collection);
048
049 if (collection != null)
050 init(clone ? new HashMap<K, V>(collection) : collection, null, false);
051 }
052
053 @Override
054 public void doInitialize() {
055 init(new HashMap<K, V>(), null, false);
056 }
057
058 @Override
059 protected PersistentCollectionSnapshot createSnapshot(Object io, boolean forReading) {
060 PersistentCollectionSnapshotFactory factory = PersistentCollectionSnapshotFactory.newInstance(io);
061 if (forReading || !wasInitialized())
062 return factory.newPersistentCollectionSnapshot(getDetachedState());
063 return factory.newPersistentCollectionSnapshot(true, getDetachedState(), isDirty(), this);
064 }
065
066 @SuppressWarnings("unchecked")
067 @Override
068 protected void updateFromSnapshot(ObjectInput in, PersistentCollectionSnapshot snapshot) {
069 if (snapshot.isInitialized())
070 init(new HashMap<K, V>((Map<K, V>)snapshot.getElementsAsMap()), snapshot.getDetachedState(), snapshot.isDirty());
071 else
072 init(null, snapshot.getDetachedState(), false);
073 }
074
075 public PersistentMap<K, V> clone(boolean uninitialize) {
076 PersistentMap<K, V> map = new PersistentMap<K, V>();
077 if (wasInitialized() && !uninitialize)
078 map.init(getCollection(), null, isDirty());
079 return map;
080 }
081 }