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