001 /*
002 GRANITE DATA SERVICES
003 Copyright (C) 2011 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.messaging.persistence;
022
023 import java.lang.reflect.ParameterizedType;
024 import java.lang.reflect.Type;
025 import java.util.Comparator;
026 import java.util.HashSet;
027 import java.util.Set;
028 import java.util.SortedSet;
029 import java.util.TreeSet;
030
031 import org.granite.config.GraniteConfig;
032 import org.granite.context.GraniteContext;
033 import org.granite.messaging.amf.io.convert.Converters;
034 import org.granite.util.ClassUtil;
035
036 /**
037 * @author Franck WOLFF
038 */
039 public class ExternalizablePersistentSet extends AbstractExternalizablePersistentCollection {
040
041 private static final long serialVersionUID = 1L;
042
043 public ExternalizablePersistentSet() {
044 }
045
046 public ExternalizablePersistentSet(Set<?> content, boolean initialized, boolean dirty) {
047 super(null, initialized, dirty);
048 setContentFromSet(content);
049 }
050
051 public ExternalizablePersistentSet(Object[] content, boolean initialized, boolean dirty) {
052 super(content, initialized, dirty);
053 }
054
055 public Set<?> getContentAsSet(Type target) {
056 return getContentAsSet(target, null);
057 }
058
059 @SuppressWarnings({ "unchecked", "rawtypes" })
060 public Set<?> getContentAsSet(Type target, Comparator comparator) {
061 Set set = null;
062 if (content != null) {
063 if (SortedSet.class.isAssignableFrom(ClassUtil.classOfType(target))) {
064 if (comparator != null)
065 set = new TreeSet(comparator);
066 else
067 set = new TreeSet();
068 }
069 else
070 set = new HashSet(content.length);
071
072 GraniteConfig config = GraniteContext.getCurrentInstance().getGraniteConfig();
073 Converters converters = config.getConverters();
074 Type[] typeArguments = null;
075 if (target instanceof ParameterizedType)
076 typeArguments = ((ParameterizedType)target).getActualTypeArguments();
077
078 for (Object o : content) {
079 if (typeArguments != null)
080 set.add(converters.convert(o, typeArguments[0]));
081 else
082 set.add(o);
083 }
084 }
085 return set;
086 }
087
088 public void setContentFromSet(Set<?> set) {
089 content = (set != null ? set.toArray() : null);
090 }
091 }