1   /*
2    * MappingDefinition.java
3    *
4    * Copyright (c) 2002, The University of Sheffield.
5    *
6    * This file is part of GATE (see http://gate.ac.uk/), and is free
7    * software, licenced under the GNU Library General Public License,
8    * Version 2, June1991.
9    *
10   * A copy of this licence is included in the distribution in the file
11   * licence.html, and is also available at http://gate.ac.uk/gate/licence.html.
12   *
13   * borislav popov 02/2002
14   *
15   */
16  package gate.creole.gazetteer;
17  
18  
19  import java.io.*;
20  import java.net.URL;
21  import java.util.*;
22  
23  import gate.creole.ResourceInstantiationException;
24  
25  /** Represents a mapping definition which maps gazetteer lists to ontology classes */
26  public class MappingDefinition extends gate.creole.AbstractLanguageResource
27                                implements List {
28  
29    /** the default encoding of the mapping */
30    private final static String ENCODING = "UTF-8";
31  
32    /** the list of nodes */
33    private List nodes = new ArrayList();
34  
35    /** the url of the mapping definition */
36    private URL url;
37  
38    /** set of gaz lists */
39    private Set lists = new HashSet();
40  
41    /** mapping between a list and a node */
42    private Map nodesByList = new HashMap();
43  
44  
45    /** Creates a new mapping definition */
46    public MappingDefinition() {
47    }
48  
49    /**Gets the urls from this definition
50     * @return a list of all the ontology urls present in this mapping def   */
51    public List getUrls() {
52      Set result = new HashSet();
53      for ( int i = 0 ; i < nodes.size() ; i++ ) {
54        result.add(((MappingNode)nodes.get(i)).getOntologyID());
55      } // for
56      return new ArrayList(result);
57    }  // getUrls()
58  
59    /** Gets the url of this definition
60     *  @return the url of the definition */
61    public URL getURL() {
62      return url;
63    }
64  
65    /** Sets the url of this definition
66     *  @param aUrl the url of the definition*/
67    public void setURL(URL aUrl) {
68      url = aUrl;
69    }
70  
71    /**Loads the mapping definition
72     * @throws ResourceInstantiationException if load fails.
73     */
74    public void load() throws ResourceInstantiationException,InvalidFormatException {
75      if (null == url) {
76        throw new ResourceInstantiationException("URL not set (null).");
77      }
78      try {
79        BufferedReader mapReader =
80        new BufferedReader(new InputStreamReader((url).openStream(), ENCODING));
81  
82        String line;
83        MappingNode node;
84        while (null != (line = mapReader.readLine())) {
85          if (0 != line.trim().length()) {
86            node = new MappingNode(line);
87            this.add(node);
88          } // if
89        } //while
90  
91        mapReader.close();
92  
93      } catch (InvalidFormatException ife){
94        throw new InvalidFormatException(url,"on load");
95      } catch (IOException ioe) {
96        throw new ResourceInstantiationException(ioe);
97      }
98  
99  
100   } // load();
101 
102   /**
103    * Stores the mapping definition
104    * @throws ResourceInstantiationException if store fails.
105    */
106   public void store()throws ResourceInstantiationException{
107     if (null == url) {
108       throw new ResourceInstantiationException("URL not set (null).");
109     }
110     try {
111     File fileo = new File(url.getFile());
112     fileo.delete();
113     BufferedWriter mapWriter = new BufferedWriter(new FileWriter(fileo));
114     for (int index = 0 ; index < nodes.size() ; index++) {
115       mapWriter.write(nodes.get(index).toString());
116       mapWriter.newLine();
117     }
118     mapWriter.close();
119     } catch (IOException ioe) {
120       throw new ResourceInstantiationException(ioe);
121     }
122   } //store();
123 
124   /**
125    * Gets the gaz lists.
126    * @return set of the gazetteer lists
127    */
128   public Set getLists() {
129     return new HashSet(lists);
130   }
131 
132   /**
133    * Gets node by list
134    * @param list a gazetteer list filename
135    * @return the mapping node that matches the list
136    */
137   public MappingNode getNodeByList(String list) {
138     return (MappingNode)nodesByList.get(list);
139   }
140 
141   /*---implementation of interface java.util.List---*/
142 
143   public int size() {
144     return nodes.size();
145   }
146 
147   public boolean isEmpty() {
148     return nodes.isEmpty();
149   }
150 
151   public boolean contains(Object o) {
152     return nodes.contains(o);
153   }
154 
155   public Iterator iterator() {
156     return new SafeIterator();
157   }
158 
159   public Object[] toArray() {
160     return nodes.toArray();
161   }
162 
163   public Object[] toArray(Object[] a) {
164     return nodes.toArray(a);
165   }
166 
167   /**
168    * adds a new node, only if its list is new and uniquely mapped to this node.
169    * @param o a node
170    * @return true if the list of node is not already mapped with another node.
171    */
172   public boolean add(Object o) {
173     boolean result = false;
174     if (o instanceof MappingNode) {
175       String list = ((MappingNode)o).getList();
176       if (!nodesByList.containsKey(list)) {
177         result = nodes.add(o);
178         nodesByList.put(list,o);
179         lists.add(list);
180       } // if unique
181     } // if a linear node
182     return result;
183   } // add()
184 
185   /**
186    * adds a new node at the specified position, only if its list is new and uniquely mapped to this node.
187    * @param o a node
188    * @param index position in the list
189    */
190   public void add(int index,Object o) {
191     if (o instanceof MappingNode) {
192       String list = ((MappingNode)o).getList();
193       if (!nodesByList.containsKey(list)) {
194         nodes.add(index,o);
195         nodesByList.put(list,o);
196         lists.add(list);
197       } // if unique
198     } // if a linear node
199   } // add()
200 
201   public Object set(int index, Object o) {
202     throw new UnsupportedOperationException("this method has not been implemented");
203   }
204 
205   public Object get(int index){
206     return nodes.get(index);
207   }
208 
209   public boolean remove(Object o) {
210     boolean result = false;
211     if (o instanceof MappingNode) {
212       result = nodes.remove(o);
213       String list = ((MappingNode)o).getList();
214       lists.remove(list);
215       nodesByList.remove(list);
216     } // if linear node
217     return result;
218   }// remove
219 
220   public Object remove(int index) {
221     Object result = null;
222     result = nodes.remove(index);
223     if (null!=result) {
224       String list = ((MappingNode)result).getList();
225       lists.remove(list);
226       nodesByList.remove(list);
227     }
228     return result;
229   }
230 
231   public boolean containsAll(Collection c) {
232     return nodes.containsAll(c);
233   }
234 
235   public boolean addAll(Collection c) {
236     boolean result = false;
237     Iterator iter = c.iterator();
238     Object o;
239     while (iter.hasNext()) {
240       o = iter.next();
241       if (o instanceof MappingNode)  {
242         result |= add(o);
243       } // instance of MappingNode
244     } // while
245     return result;
246   } // addAll(Collection)
247 
248   public boolean addAll(int index,Collection c) {
249     int size = nodes.size();
250     Iterator iter = c.iterator();
251     Object o;
252     while (iter.hasNext()) {
253       o = iter.next();
254       if (o instanceof MappingNode)  {
255         add(index++, o);
256       } // instance of MappingNode
257     } // while
258     return (size!=nodes.size());
259   }//addAll(int,Collection)
260 
261   public boolean removeAll(Collection c) {
262     boolean result = false;
263     Iterator iter = c.iterator();
264     Object o;
265     while (iter.hasNext()) {
266       o = iter.next();
267       result |= remove(o);
268     }
269     return result;
270   }// removeAll()
271 
272 
273   public boolean retainAll(Collection c) {
274     int aprioriSize = nodes.size();
275     List scrap = new ArrayList();
276 
277     MappingNode node;
278     for (int index = 0; index < nodes.size(); index++) {
279       node = (MappingNode) nodes.get(index);
280       if (c.contains(node)) {
281         scrap.add(node);
282       }
283     } //for
284 
285     removeAll(scrap);
286 
287     return (aprioriSize != nodes.size());
288   }
289 
290 
291   public void clear() {
292     nodes.clear();
293     lists.clear();
294     nodesByList.clear();
295   }
296 
297   public boolean equals(Object o) {
298     boolean result = false;
299     if ( o instanceof MappingDefinition ) {
300       MappingDefinition def = (MappingDefinition) o;
301       result &= nodes.equals(def.nodes);
302       result &= lists.equals(def.lists);
303       result &= nodesByList.equals(def.lists);
304     }// if
305     return result;
306   } // equals()
307 
308   public List subList(int i1, int i2) {
309     return nodes.subList(i1,i2);
310   }
311 
312   public ListIterator listIterator(int index) {
313     throw new UnsupportedOperationException("this method is not implemented");
314   }
315   public ListIterator listIterator() {
316     throw new UnsupportedOperationException("this method is not implemented");
317   }
318 
319   public int lastIndexOf(Object o) {
320     return nodes.lastIndexOf(o);
321   }
322 
323   public int indexOf(Object o) {
324     return nodes.indexOf(o);
325   }
326 
327  /*---end of implementation of interface java.util.List---*/
328 
329  /*-----------internal classes -------------*/
330 
331   /**Provides means for safe iteration over
332    * the entries of the Mapping Definition  */
333   private class SafeIterator implements Iterator {
334     private int index = 0;
335     private boolean removeCalled = false;
336 
337     public boolean hasNext() {
338       return (index < nodes.size());
339     }
340 
341     public Object next() {
342       removeCalled = false;
343       return nodes.get(index++);
344     }
345 
346     public void remove() {
347       if (!removeCalled && index > 0  ) {
348         index--;
349         MappingDefinition.this.remove(nodes.get(index));
350       }// if possible remove
351       removeCalled = true;
352     } // remove
353 
354 
355   } // class SafeIterator
356 
357 } // class MappingDefinition