View Javadoc

1   package com.explosion.utilities.preferences.impl.inmemory;
2   
3   /*
4    * =============================================================================
5    * 
6    * Copyright 2004 Stephen Cowx
7    * 
8    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
9    * use this file except in compliance with the License. You may obtain a copy of
10   * the License at
11   * 
12   * http://www.apache.org/licenses/LICENSE-2.0
13   * 
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17   * License for the specific language governing permissions and limitations under
18   * the License.
19   * 
20   * =============================================================================
21   */
22  
23  import java.awt.Color;
24  import java.io.File;
25  import java.util.ArrayList;
26  import java.util.List;
27  import java.util.Map;
28  
29  import com.explosion.utilities.GeneralConstants;
30  import com.explosion.utilities.GeneralUtils;
31  import com.explosion.utilities.preferences.EncryptionException;
32  import com.explosion.utilities.preferences.Preference;
33  import com.explosion.utilities.preferences.groups.PreferenceGroup;
34  import com.explosion.utilities.preferences.groups.PreferencePersistenceException;
35  import com.explosion.utilities.preferences.persist.PreferencePersister;
36  
37  /***
38   * @author: Stephen Cowx
39   *
40   * This class saves preference objects to a map in Memory
41   */
42  
43  public class InMemoryPreferencePersister implements PreferencePersister
44  {
45      private Map map;
46  
47      /***
48       * Hidden constructor, want to use the factory method
49       */
50      private InMemoryPreferencePersister()    {        
51      }
52      
53      /***
54       * Constructs an instance of an InMemoryPreferencePersistor
55       * @param referenceToStore
56       * @return
57       */
58      public static PreferencePersister createPreferencePersistor(Object referenceToStore)
59      {
60          InMemoryPreferencePersister persister = new InMemoryPreferencePersister();
61          persister.map = (Map) referenceToStore;
62          return persister;
63      }
64      
65      /***
66       * Returns a reference to the backing store as understood by the PreferencePersister
67       * @return
68       */
69      public Object getReferenceToStore()
70      {
71          return map;
72      }
73      
74      /***
75       * Sets the reference to the backing store as understood by the PreferencePersister
76       * Effectively moving it from one store to another or moving it from one location in the same store to another
77       * @return
78       */
79      public void setReferenceToStore(Object referenceToStore)
80      {
81          this.map = (Map) referenceToStore;
82      }
83      
84      /***
85       * This method saves the property to persistent storage, if the value is
86       * null, it should delete the entire key/value pair persisted if it exists
87       * or not save it if it does.
88       * 
89       * @throws Exception
90       */
91      public void save(Preference preference) throws PreferencePersistenceException
92      {
93          if (preference.isDefaulted())
94          {
95              /* If it is defaulted and this node exists then delete it */
96              if (map.get(preference.getUniqueIdentifier()) != null)
97                  map.remove(preference.getUniqueIdentifier());
98  
99              return;
100         }
101 
102         if (preference.getType() == Preference.PROPERTY_TYPE_COLLECTION)
103         	map.put(preference.getUniqueIdentifier(), preference.getValues());
104         else
105             map.put(preference.getUniqueIdentifier(), preference.getValue());
106     }
107     
108     /***
109      * This method loads the property from persistent storage if it is there, if
110      * it is not it should not populate the value.
111      * 
112      * @throws Exception
113      */
114     public void load(Preference preference) throws PreferencePersistenceException
115     {
116         try
117         {
118         	if (map.get(preference.getUniqueIdentifier()) == null)
119                 return;
120         	
121             if (preference.getType() != Preference.PROPERTY_TYPE_COLLECTION)
122             {
123                 Object object = getTypedValue(preference.getType(), preference.getUniqueIdentifier());
124                 preference.setValue(object);
125 
126                 /* Do some cleaning for files etc */
127                 switch (preference.getType())
128                 {
129                 case (Preference.PROPERTY_TYPE_FILE):
130                     if (((File) preference.getValue()).getName().indexOf(GeneralConstants.DEFAULT_FILE) >= 0)
131                         preference.setValue(preference.createDefaultFile());
132                     break;
133                 case (Preference.PROPERTY_TYPE_DIRECTORY):
134                     if (((File) preference.getValue()).getName().equals(GeneralConstants.DEFAULT_FILE))
135                         preference.setValue(preference.createDefaultFile());
136                     break;
137                 }
138             }
139             else
140             {
141             	List items = (ArrayList) map.get(preference.getUniqueIdentifier());
142                 preference.setValues(items, preference.getCollectionType());
143             }
144         }
145         catch (PreferencePersistenceException e)
146         {
147             throw e;
148         }
149         catch (Exception e)
150         {
151             throw new PreferencePersistenceException("Error caught while persisting data", e);
152         }
153     }
154 
155     /***
156      * Obtains and creates the object from the persistent store based on it's
157      * type
158      * 
159      * @param type
160      * @param node
161      * @param uniqueIdentifier
162      * @param defaultValue
163      * @return @throws Exception
164      */
165     private Object getTypedValue(int type, String uniqueIdentifier) throws PreferencePersistenceException
166     {
167         try
168         {
169             switch (type)
170             {
171                 case (Preference.PROPERTY_TYPE_TEXT):
172                     return map.get(uniqueIdentifier);
173                 case (Preference.PROPERTY_TYPE_FILE):
174                     return (File) map.get(uniqueIdentifier);
175                 case (Preference.PROPERTY_TYPE_DIRECTORY):
176                     return (File) map.get(uniqueIdentifier);
177                 case (Preference.PROPERTY_TYPE_COLOR):
178                     return (Color) map.get(uniqueIdentifier);
179                 case (Preference.PROPERTY_TYPE_INT):
180                     return (Integer) map.get(uniqueIdentifier);
181                 case (Preference.PROPERTY_TYPE_FLOAT):
182                     return (Float)map.get(uniqueIdentifier);
183                 case (Preference.PROPERTY_TYPE_STRING_CHOICE):
184                     return getTypedValue(Preference.PROPERTY_TYPE_TEXT, uniqueIdentifier);
185                 case (Preference.PROPERTY_TYPE_INT_CHOICE):
186                     return getTypedValue(Preference.PROPERTY_TYPE_INT, uniqueIdentifier);
187                 case (Preference.PROPERTY_TYPE_BOOLEAN):
188                     return (Boolean) map.get(uniqueIdentifier);
189                 case (Preference.PROPERTY_TYPE_FONT):
190                     return Preference.deriveFont((String)map.get(uniqueIdentifier));
191                 case (Preference.PROPERTY_TYPE_ENCRYPTED):
192                     /* decrypt it as you read it */
193                     return Preference.decrypt((String)map.get(uniqueIdentifier));
194                 default:
195                     return null;
196             }
197         }
198         catch (PreferencePersistenceException e)
199         {
200             throw e;
201         }
202         catch (EncryptionException e)
203         {
204             throw new PreferencePersistenceException("Error caught while persisting data", e);
205         }
206     }
207     
208     /***
209      * @see com.explosion.utilities.preferences.ExpAbstractPreference#getNode()
210      */
211     public Object getNode()
212     {
213         return map;
214     }
215 
216     /***
217      * @see com.explosion.utilities.preferences.ExpAbstractPreference#setNode(Object)
218      */
219     public void setNode(Object node)
220     {
221         this.map = (Map) node;
222     }
223 
224     /***
225      * This method turns the given String into an object of the desired type.
226      * Null's just get returned.
227      * @throws Exception
228      */
229     public synchronized static Object convertToInstanceOfType(int type, String string) throws Exception
230     {
231         if (string == null)
232             return null;
233         
234         /* Load it */
235         switch (type)
236         {
237         case (Preference.PROPERTY_TYPE_TEXT):
238             return string;
239         case (Preference.PROPERTY_TYPE_FILE):
240             return (new File(string));
241         case (Preference.PROPERTY_TYPE_DIRECTORY):
242             return (new File(string));
243         case (Preference.PROPERTY_TYPE_COLOR):
244             return new Color(Integer.parseInt(string));
245         case (Preference.PROPERTY_TYPE_INT):
246             return new Integer(string);
247         case (Preference.PROPERTY_TYPE_FLOAT):
248             return new Float(string);
249         case (Preference.PROPERTY_TYPE_STRING_CHOICE):
250             return string;
251         case (Preference.PROPERTY_TYPE_INT_CHOICE):
252             return new Integer(string);
253         case (Preference.PROPERTY_TYPE_BOOLEAN):
254             return new Boolean(GeneralUtils.getLenientBoolean(string));
255         case (Preference.PROPERTY_TYPE_FONT):
256             return Preference.deriveFont(string);
257         case (Preference.PROPERTY_TYPE_ENCRYPTED):
258             return Preference.decrypt(string);
259         }
260         return null;
261     }
262     
263     
264     /***
265      * This method deletes the preferenceGroup from the backing store
266      * @param group
267      * @throws PreferencePersistenceException
268      */
269     public void deleteGroup(PreferenceGroup group) throws PreferencePersistenceException
270 	{
271     	/* Remove the node from thebacking store */
272         //Preferences.userRoot().node(uri + "/" + identifier).removeNode();
273         //Preferences.userRoot().node(uri).flush();
274 	}
275     
276     /***
277      * This method saves a preference group in the store
278      * @param group
279      * @throws PreferencePersistenceException
280      */
281     public void saveGroup(PreferenceGroup group) throws PreferencePersistenceException
282 	{
283     	
284 	}
285     
286     public void relocateGroup(PreferenceGroup group, Object referenceToNewStore) throws PreferencePersistenceException
287     {
288 //        if (!editable) 
289 //        {
290 //           log.warn("Attempt to edit non editable preference group " + identifier);
291 //           return;
292 //        }
293 //
294 //        /* Remove the old node */
295 //        preferenceNode.removeNode();
296 //        Preferences.userRoot().node(uri).flush();
297 //
298 //        /* Create a new node */
299 //        preferenceNode = Preferences.userRoot().node(newUri + "/" + newIdentifier);
300 //
301 //        /* Assign the old preferences to the new node */
302 //        for (int i = 0; i < attributesVector.size(); i++)
303 //        {
304 //            Preference pref = (Preference) attributesVector.elementAt(i);
305 //            pref.getPreferencePersister().setReferenceToStore(preferenceNode);
306 //        }
307 //
308 //        commit();
309 //
310 //        this.uri = newUri;
311 //        this.identifier = newIdentifier;
312     }
313     
314 }