close filehandles straight after parse, without setting an error
[jalview.git] / src / jalview / io / AlignFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.io;
22
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.Enumeration;
26 import java.util.Hashtable;
27 import java.util.List;
28 import java.util.Vector;
29
30 import jalview.datamodel.AlignmentAnnotation;
31 import jalview.datamodel.AlignmentI;
32 import jalview.datamodel.Sequence;
33 import jalview.datamodel.SequenceGroup;
34 import jalview.datamodel.SequenceI;
35 import jalview.util.MessageManager;
36
37 /**
38  * DOCUMENT ME!
39  * 
40  * @author $author$
41  * @version $Revision$
42  */
43 public abstract class AlignFile extends FileParse
44         implements AlignmentFileReaderI, AlignmentFileWriterI
45 {
46   int noSeqs = 0;
47
48   int maxLength = 0;
49
50   /**
51    * Sequences to be added to form a new alignment. TODO: remove vector in this
52    * class
53    */
54   protected Vector<SequenceI> seqs;
55
56   /**
57    * annotation to be added to generated alignment object
58    */
59   protected Vector<AlignmentAnnotation> annotations;
60
61   /**
62    * SequenceGroups to be added to the alignment object
63    */
64   protected List<SequenceGroup> seqGroups;
65
66   /**
67    * Properties to be added to generated alignment object
68    */
69   private Hashtable properties;
70
71   long start;
72
73   long end;
74
75   /**
76    * true if parse() has been called
77    */
78   private boolean parseCalled = false;
79
80   private boolean parseImmediately = true;
81
82   /**
83    * @return if doParse() was called at construction time
84    */
85   protected boolean isParseImmediately()
86   {
87     return parseImmediately;
88   }
89
90   /**
91    * Creates a new AlignFile object.
92    */
93   public AlignFile()
94   {
95     // Shouldn't we init data structures (JBPNote: not sure - initData is for
96     // initialising the structures used for reading from a datasource, and the
97     // bare constructor hasn't got any datasource)
98     initData();
99   }
100
101   public AlignFile(SequenceI[] seqs)
102   {
103     this();
104     setSeqs(seqs);
105   }
106
107   /**
108    * Constructor which parses the data from a file of some specified type.
109    * 
110    * @param dataObject
111    *          Filename, URL or Pasted String to read from.
112    * @param sourceType
113    *          What type of file to read from (File, URL, Pasted String)
114    */
115   public AlignFile(String dataObject, DataSourceType sourceType)
116           throws IOException
117   {
118     this(true, dataObject, sourceType);
119   }
120
121   /**
122    * Constructor which (optionally delays) parsing of data from a file of some
123    * specified type.
124    * 
125    * @param parseImmediately
126    *          if false, need to call 'doParse()' to begin parsing data
127    * @param dataObject
128    *          Filename, URL or Pasted String to read from.
129    * @param sourceType
130    *          What type of file to read from (File, URL)
131    * @throws IOException
132    */
133   public AlignFile(boolean parseImmediately, String dataObject,
134           DataSourceType sourceType) throws IOException
135   {
136     super(dataObject, sourceType);
137     initData();
138     if (parseImmediately)
139     {
140       doParse();
141     }
142   }
143
144   /**
145    * Attempt to read from the position where some other parsing process left
146    * off.
147    * 
148    * @param source
149    * @throws IOException
150    */
151   public AlignFile(FileParse source) throws IOException
152   {
153     this(true, source);
154   }
155
156   /**
157    * Construct a new parser to read from the position where some other parsing
158    * process left
159    * 
160    * @param parseImmediately
161    *          if false, need to call 'doParse()' to begin parsing data
162    * @param source
163    */
164   public AlignFile(boolean parseImmediately, FileParse source)
165           throws IOException
166   {
167     super(source);
168     initData();
169
170     // stash flag in case parse needs to know if it has to autoconfigure or was
171     // configured after construction
172     this.parseImmediately = parseImmediately;
173
174     if (parseImmediately)
175     {
176       doParse();
177     }
178   }
179
180   /**
181    * called if parsing was delayed till after parser was constructed
182    * 
183    * @throws IOException
184    */
185   public void doParse() throws IOException
186   {
187     if (parseCalled)
188     {
189       throw new IOException(
190               "Implementation error: Parser called twice for same data.\n"
191                       + "Need to call initData() again before parsing can be reattempted.");
192     }
193     parseCalled = true;
194     parse();
195     dataIn.close();
196   }
197
198   /**
199    * Return the seqs Vector
200    */
201   public Vector<SequenceI> getSeqs()
202   {
203     return seqs;
204   }
205
206   public List<SequenceGroup> getSeqGroups()
207   {
208     return seqGroups;
209   }
210
211   /**
212    * Return the Sequences in the seqs Vector as an array of Sequences
213    */
214   @Override
215   public SequenceI[] getSeqsAsArray()
216   {
217     SequenceI[] s = new SequenceI[seqs.size()];
218
219     for (int i = 0; i < seqs.size(); i++)
220     {
221       s[i] = seqs.elementAt(i);
222     }
223
224     return s;
225   }
226
227   /**
228    * called by AppletFormatAdapter to generate an annotated alignment, rather
229    * than bare sequences.
230    * 
231    * @param al
232    */
233   @Override
234   public void addAnnotations(AlignmentI al)
235   {
236     addProperties(al);
237     for (int i = 0; i < annotations.size(); i++)
238     {
239       // detect if annotations.elementAt(i) rna secondary structure
240       // if so then do:
241       /*
242        * SequenceFeature[] pairArray =
243        * Rna.GetBasePairsFromAlignmentAnnotation(annotations.elementAt(i));
244        * Rna.HelixMap(pairArray);
245        */
246       AlignmentAnnotation an = annotations.elementAt(i);
247       an.validateRangeAndDisplay();
248       al.addAnnotation(an);
249     }
250
251   }
252
253   /**
254    * register sequence groups on the alignment for **output**
255    * 
256    * @param al
257    */
258   public void addSeqGroups(AlignmentI al)
259   {
260     this.seqGroups = al.getGroups();
261
262   }
263
264   /**
265    * Add any additional information extracted from the file to the alignment
266    * properties.
267    * 
268    * @note implicitly called by addAnnotations()
269    * @param al
270    */
271   public void addProperties(AlignmentI al)
272   {
273     if (properties != null && properties.size() > 0)
274     {
275       Enumeration keys = properties.keys();
276       Enumeration vals = properties.elements();
277       while (keys.hasMoreElements())
278       {
279         al.setProperty(keys.nextElement(), vals.nextElement());
280       }
281     }
282   }
283
284   /**
285    * Store a non-null key-value pair in a hashtable used to set alignment
286    * properties note: null keys will raise an error, null values will result in
287    * the key/value pair being silently ignored.
288    * 
289    * @param key
290    *          - non-null key object
291    * @param value
292    *          - non-null value
293    */
294   protected void setAlignmentProperty(Object key, Object value)
295   {
296     if (key == null)
297     {
298       throw new Error(MessageManager.getString(
299               "error.implementation_error_cannot_have_null_alignment"));
300     }
301     if (value == null)
302     {
303       return; // null properties are ignored.
304     }
305     if (properties == null)
306     {
307       properties = new Hashtable();
308     }
309     properties.put(key, value);
310   }
311
312   protected Object getAlignmentProperty(Object key)
313   {
314     if (properties != null && key != null)
315     {
316       return properties.get(key);
317     }
318     return null;
319   }
320
321   /**
322    * Initialise objects to store sequence data in.
323    */
324   protected void initData()
325   {
326     seqs = new Vector<SequenceI>();
327     annotations = new Vector<AlignmentAnnotation>();
328     seqGroups = new ArrayList<SequenceGroup>();
329     parseCalled = false;
330   }
331
332   /**
333    * DOCUMENT ME!
334    * 
335    * @param s
336    *          DOCUMENT ME!
337    */
338   @Override
339   public void setSeqs(SequenceI[] s)
340   {
341     seqs = new Vector<SequenceI>();
342
343     for (int i = 0; i < s.length; i++)
344     {
345       seqs.addElement(s[i]);
346     }
347   }
348
349   /**
350    * This method must be implemented to parse the contents of the file.
351    */
352   public abstract void parse() throws IOException;
353
354   /**
355    * A general parser for ids.
356    * 
357    * @String id Id to be parsed
358    */
359   Sequence parseId(String id)
360   {
361     Sequence seq = null;
362     id = id.trim();
363     int space = id.indexOf(" ");
364     if (space > -1)
365     {
366       seq = new Sequence(id.substring(0, space), "");
367       String desc = id.substring(space + 1);
368       seq.setDescription(desc);
369
370       /*
371        * it is tempting to parse Ensembl style gene description e.g.
372        * chromosome:GRCh38:7:140696688:140721955:1 and set the
373        * start position of the sequence, but this causes much confusion
374        * for reverse strand feature locations
375        */
376     }
377     else
378     {
379       seq = new Sequence(id, "");
380     }
381
382     return seq;
383   }
384
385   /**
386    * Creates the output id. Adds prefix Uniprot format source|id and optionally
387    * suffix Jalview /start-end
388    * 
389    * @param jvsuffix
390    * 
391    * @String id Id to be parsed
392    */
393   String printId(SequenceI seq, boolean jvsuffix)
394   {
395     return seq.getDisplayId(jvsuffix);
396   }
397
398   String printId(SequenceI seq)
399   {
400     return printId(seq, true);
401   }
402
403   /**
404    * vector of String[] treeName, newickString pairs
405    */
406   Vector<String[]> newickStrings = null;
407
408   protected void addNewickTree(String treeName, String newickString)
409   {
410     if (newickStrings == null)
411     {
412       newickStrings = new Vector<String[]>();
413     }
414     newickStrings.addElement(new String[] { treeName, newickString });
415   }
416
417   protected int getTreeCount()
418   {
419     return newickStrings == null ? 0 : newickStrings.size();
420   }
421
422   @Override
423   public void addGroups(AlignmentI al)
424   {
425
426     for (SequenceGroup sg : getSeqGroups())
427     {
428       al.addGroup(sg);
429     }
430   }
431
432   protected void addSequence(SequenceI seq)
433   {
434     seqs.add(seq);
435   }
436 }