01 /*
02 * Copyright (c) 1995-2010, The University of Sheffield. See the file
03 * COPYRIGHT.txt in the software or at http://gate.ac.uk/gate/COPYRIGHT.txt
04 *
05 * This file is part of GATE (see http://gate.ac.uk/), and is free
06 * software, licenced under the GNU Library General Public License,
07 * Version 2, June 1991 (in the distribution as file licence.html,
08 * and also available at http://gate.ac.uk/gate/licence.html).
09 *
10 * Valentin Tablan 26/10/2001
11 *
12 * $Id: MapPersistence.java 12006 2009-12-01 17:24:28Z thomas_heitz $
13 *
14 */
15 package gate.util.persistence;
16
17 import java.util.*;
18
19 import gate.creole.ResourceInstantiationException;
20 import gate.persist.PersistenceException;
21
22 public class MapPersistence implements Persistence {
23 /**
24 * Populates this Persistence with the data that needs to be stored from the
25 * original source object.
26 */
27 public void extractDataFromSource(Object source)throws PersistenceException{
28 if(! (source instanceof Map)){
29 throw new UnsupportedOperationException(
30 getClass().getName() + " can only be used for " +
31 Map.class.getName() +
32 " objects!\n" + source.getClass().getName() +
33 " is not a " + Map.class.getName());
34 }
35 mapType = source.getClass();
36
37 Map map = (Map)source;
38 List keysList = new ArrayList();
39 List valuesList = new ArrayList();
40 localMap = new HashMap(map.size());
41 //collect the keys in the order given by the entrySet().iterator();
42 Iterator keyIter = map.keySet().iterator();
43 while(keyIter.hasNext()){
44 Object key = keyIter.next();
45 Object value = map.get(key);
46
47 key = PersistenceManager.getPersistentRepresentation(key);
48 value = PersistenceManager.getPersistentRepresentation(value);
49 localMap.put(key, value);
50 }
51 }
52
53 /**
54 * Creates a new object from the data contained. This new object is supposed
55 * to be a copy for the original object used as source for data extraction.
56 */
57 public Object createObject()throws PersistenceException,
58 ResourceInstantiationException{
59 //let's try to create a map of the same type as the original
60 Map result = null;
61 try{
62 result = (Map)mapType.newInstance();
63 }catch(Exception e){
64 }
65 if(result == null) result = new HashMap(localMap.size());
66
67 //now we have a map let's populate it
68 Iterator keyIter = localMap.keySet().iterator();
69 while(keyIter.hasNext()){
70 Object key = keyIter.next();
71 Object value = localMap.get(key);
72
73 key = PersistenceManager.getTransientRepresentation(key);
74 value = PersistenceManager.getTransientRepresentation(value);
75 result.put(key, value);
76 }
77
78 return result;
79 }
80
81 protected Class mapType;
82 protected HashMap localMap;
83 static final long serialVersionUID = 1835776085941379996L;
84 }
|