JAL-2664 Updates following review
[jalview.git] / src / jalview / io / packed / ParsePackedSet.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.packed;
22
23 import jalview.api.FeatureColourI;
24 import jalview.datamodel.AlignmentI;
25 import jalview.io.AppletFormatAdapter;
26 import jalview.io.FileFormatI;
27 import jalview.io.FileParse;
28 import jalview.io.FormatAdapter;
29 import jalview.io.IdentifyFile;
30 import jalview.io.packed.DataProvider.JvDataType;
31
32 import java.io.BufferedReader;
33 import java.io.IOException;
34 import java.util.ArrayList;
35 import java.util.HashMap;
36 import java.util.List;
37
38 public class ParsePackedSet
39 {
40
41   /**
42    * return results as a series of jalview.datamodel objects suitable for
43    * display
44    * 
45    * @param context
46    *          - context which is updated with new data
47    * @param files
48    *          - source data
49    * @return list of data objects added to context
50    * @throws Exception
51    */
52   public Object[] getAlignment(JalviewDataset context,
53           Iterable<DataProvider> files) throws Exception
54   {
55     List<Object> rslt = new ArrayList<Object>();
56     if (context == null)
57     {
58       context = new JalviewDataset();
59     }
60     boolean deuniquify = false;
61     for (DataProvider dta : files)
62     {
63       Exception exerror = null;
64       String errmsg = null;
65       FileParse src = dta.getDataSource();
66       if (dta.getType().equals(DataProvider.JvDataType.ALIGNMENT))
67       {
68         FileFormatI fmt = null;
69         try
70         {
71           fmt = new IdentifyFile().identify(src, false);
72         } catch (Exception ex)
73         {
74           exerror = ex;
75           errmsg = "Couldn't identify alignment format.";
76         }
77
78         if (fmt != null)
79         {
80           // parse the alignment
81           AlignmentI al = null;
82           try
83           {
84             al = new FormatAdapter().readFromFile(src, fmt);
85           } catch (Exception e)
86           {
87             errmsg = "Failed to parse alignment from result set";
88             exerror = e;
89           }
90           if (al != null)
91           {
92             // deuniquify and construct/merge additional dataset entries if
93             // necessary.
94             context.addAlignment(al);
95             context.updateSetModified(true);
96             rslt.add(al);
97             deuniquify = true;
98           }
99         }
100       }
101       if (dta.getType().equals(JvDataType.ANNOTATION))
102       {
103         if (!context.hasAlignments())
104         {
105           errmsg = "No alignment or sequence dataset to associate annotation with.";
106           // could duplicate the dataset reference here as default behaviour for
107           // sequence associated annotation ?
108         }
109         try
110         {
111           BufferedReader br;
112           if (src.getReader() instanceof BufferedReader)
113           {
114             br = (BufferedReader) src.getReader();
115           }
116           else
117           {
118             br = new BufferedReader(src.getReader());
119           }
120           // TODO: add columnSelection to context
121           if (new jalview.io.AnnotationFile().parseAnnotationFrom(
122                   context.getLastAlignment(), null, br))
123           {
124             context.updateSetModified(true);
125           }
126           else
127           {
128             errmsg = "Annotation file contained no data.";
129           }
130
131         } catch (Exception e)
132         {
133           errmsg = ((errmsg == null) ? "" : errmsg)
134                   + "Failed to parse the annotation file associated with the alignment.";
135           exerror = e;
136         }
137       }
138       if (dta.getType().equals(JvDataType.SEQASSOCATED))
139       {
140         if (!context.hasSequenceAssoc())
141         {
142           errmsg = "No sequence to associate data with.";
143
144         }
145         errmsg = "parsing of sequence associated data is not implemented";
146         exerror = new Exception(errmsg);
147       }
148       if (dta.getType().equals(JvDataType.FEATURES))
149       {
150         // check the context has a place to store feature rendering definitions,
151         // if not, create one.
152         if (context.featureColours == null)
153         {
154           context.featureColours = new HashMap<String, FeatureColourI>();
155         }
156         try
157         {
158           jalview.io.FeaturesFile ff = new jalview.io.FeaturesFile(src);
159           context.updateSetModified(ff.parse(context.getLastAlignment(),
160                   context.featureColours, false, context.relaxedIdMatching));
161         } catch (Exception e)
162         {
163           errmsg = ("Failed to parse the Features file associated with the alignment.");
164           exerror = e;
165         }
166       }
167       if (dta.getType().equals(JvDataType.TREE))
168       {
169         try
170         {
171           jalview.io.NewickFile nf = new jalview.io.NewickFile(src);
172           if (!nf.isValid())
173           {
174             nf.close();
175             nf = null;
176           }
177           else
178           {
179             // do association to current alignment.
180
181             context.addTreeFromFile(nf);
182             rslt.add(nf);
183             context.updateSetModified(true);
184           }
185         } catch (Exception e)
186         {
187           errmsg = ("Failed to parse the treeFile associated with the result.");
188           exerror = e;
189         }
190
191       }
192       if (exerror != null)
193       {
194         if (errmsg != null && errmsg.length() > 0)
195         {
196           throw new IOException(errmsg, exerror);
197         }
198         else
199         {
200           throw new IOException(errmsg, exerror);
201         }
202       }
203       else
204       {
205         if (errmsg != null && errmsg.length() > 0)
206         {
207           throw new IOException(errmsg);
208         }
209       }
210     }
211     if (deuniquify)
212     {
213       context.getLastAlignmentSet().deuniquifyAlignment();
214     }
215     return rslt.toArray();
216   }
217
218   /**
219    * simple command line test. Arguments should be one or more pairs of
220    * <DataProvider.JvDataType> <Filename> arguments. The routine will attempt to
221    * read each source in turn, and report what kind of Jalview datamodel objects
222    * would be created.
223    * 
224    * @param args
225    */
226   public static void main(String args[])
227   {
228     // make data providers from the set of keys/files
229     int i = 0;
230     List<DataProvider> dp = new ArrayList<DataProvider>();
231     while ((i + 1) < args.length)
232     {
233       String type = args[i++];
234       final String file = args[i++];
235       final JvDataType jtype = DataProvider.JvDataType.valueOf(type
236               .toUpperCase());
237       if (jtype != null)
238       {
239         final FileParse fp;
240         try
241         {
242           fp = new FileParse(file, AppletFormatAdapter.checkProtocol(file));
243         } catch (Exception e)
244         {
245           System.err.println("Couldn't handle datasource of type " + jtype
246                   + " using URI " + file);
247           e.printStackTrace();
248           return;
249         }
250         dp.add(new SimpleDataProvider(jtype, fp, null));
251       }
252       else
253       {
254         System.out.println("Couldn't parse source type token '"
255                 + type.toUpperCase() + "'");
256       }
257     }
258     if (i < args.length)
259     {
260       System.out.print("** WARNING\nIgnoring unused arguments:\n");
261       while (i < args.length)
262       {
263         System.out.print(" " + args[i]);
264       }
265       System.out.print("\n");
266
267     }
268     System.out.println("Now trying to parse set:");
269     JalviewDataset context;
270     Object[] newdm;
271     ParsePackedSet pps;
272     try
273     {
274       newdm = (pps = new ParsePackedSet()).getAlignment(
275               context = new JalviewDataset(), dp);
276     } catch (Exception e)
277     {
278       System.out.println("Test failed for these arguments.\n");
279       e.printStackTrace(System.out);
280       return;
281     }
282     if (newdm != null)
283     {
284       for (Object o : newdm)
285       {
286         System.out.println("Will need to create an " + o.getClass());
287       }
288
289       // now test uniquify/deuniquify stuff
290       // uniquify alignment and write alignment, annotation, features, and trees
291       // to buffers.
292       // import with deuniquify info, and compare results to input.
293
294     }
295     else
296     {
297       if (context.getLastAlignmentSet().isModified())
298       {
299         System.err
300                 .println("Initial alignment set was modified and any associated views should be updated.");
301       }
302     }
303   }
304 }