001 /*
002 GRANITE DATA SERVICES
003 Copyright (C) 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
021 package org.granite.client.persistence.collection;
022
023 import java.io.ObjectInput;
024 import java.util.HashMap;
025 import java.util.Map;
026 import java.util.SortedMap;
027
028 import org.granite.messaging.persistence.PersistentCollectionSnapshot;
029 import org.granite.messaging.persistence.PersistentCollectionSnapshotFactory;
030
031 /**
032 * @author Franck WOLFF
033 */
034 public class PersistentMap<K, V> extends AbstractPersistentMapCollection<K, V, Map<K, V>> implements Map<K, V> {
035
036 public PersistentMap() {
037 }
038
039 public PersistentMap(Map<K, V> collection) {
040 this(collection, true);
041 }
042
043 public PersistentMap(Map<K, V> collection, boolean clone) {
044 if (collection instanceof SortedMap)
045 throw new IllegalArgumentException("Should not be a SortedMap: " + collection);
046
047 if (collection != null)
048 init(clone ? new HashMap<K, V>(collection) : collection, false);
049 }
050
051 @Override
052 protected PersistentCollectionSnapshot createSnapshot(boolean forReading) {
053 PersistentCollectionSnapshotFactory factory = PersistentCollectionSnapshotFactory.newInstance();
054 if (forReading || !wasInitialized())
055 return factory.newPersistentCollectionSnapshot();
056 return factory.newPersistentCollectionSnapshot(true, isDirty(), this);
057 }
058
059 @SuppressWarnings("unchecked")
060 @Override
061 protected void updateFromSnapshot(ObjectInput in, PersistentCollectionSnapshot snapshot) {
062 if (snapshot.isInitialized())
063 init(new HashMap<K, V>((Map<K, V>)snapshot.getElementsAsMap()), snapshot.isDirty());
064 else
065 init(null, false);
066 }
067 }