update author list in license for (JAL-826)
[jalview.git] / src / jalview / io / packed / ParsePackedSet.java
1 /*******************************************************************************
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  *
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  *******************************************************************************/
18 package jalview.io.packed;
19
20 import jalview.datamodel.AlignmentI;
21 import jalview.io.AppletFormatAdapter;
22 import jalview.io.FileParse;
23 import jalview.io.FormatAdapter;
24 import jalview.io.IdentifyFile;
25 import jalview.io.packed.DataProvider.JvDataType;
26
27 import java.io.BufferedReader;
28 import java.io.IOException;
29 import java.util.ArrayList;
30 import java.util.Hashtable;
31 import java.util.List;
32
33 public class ParsePackedSet
34 {
35
36   /**
37    * return results as a series of jalview.datamodel objects suitable for
38    * display
39    * 
40    * @param context
41    *          - context which is updated with new data
42    * @param files
43    *          - source data
44    * @return list of data objects added to context
45    * @throws Exception
46    */
47   public Object[] getAlignment(JalviewDataset context,
48           Iterable<DataProvider> files) throws Exception
49   {
50     List<Object> rslt = new ArrayList<Object>();
51     if (context == null)
52     {
53       context = new JalviewDataset();
54     }
55     boolean deuniquify = false;
56     for (DataProvider dta : files)
57     {
58       Exception exerror = null;
59       String errmsg = null;
60       FileParse src = dta.getDataSource();
61       if (dta.getType().equals(DataProvider.JvDataType.ALIGNMENT))
62       {
63         String fmt = null;
64         try
65         {
66           fmt = new IdentifyFile().Identify(src, false);
67         } catch (Exception ex)
68         {
69           exerror = ex;
70           errmsg = "Couldn't identify alignment format.";
71         }
72
73         if (fmt != null)
74         {
75           if (!FormatAdapter.isValidIOFormat(fmt, false))
76           {
77             errmsg = fmt;
78             exerror = null;
79           }
80           else
81           {
82             // parse the alignment
83             AlignmentI al = null;
84             try
85             {
86               al = new FormatAdapter().readFromFile(src, fmt);
87             } catch (Exception e)
88             {
89               errmsg = "Failed to parse alignment from result set";
90               exerror = e;
91             }
92             if (al != null)
93             {
94               // deuniquify and construct/merge additional dataset entries if
95               // necessary.
96               context.addAlignment(al);
97               context.updateSetModified(true);
98               rslt.add(al);
99               deuniquify = true;
100             }
101           }
102         }
103       }
104       if (dta.getType().equals(JvDataType.ANNOTATION))
105       {
106         if (!context.hasAlignments())
107         {
108           errmsg = "No alignment or sequence dataset to associate annotation with.";
109           // could duplicate the dataset reference here as default behaviour for
110           // sequence associated annotation ?
111         }
112         try
113         {
114           BufferedReader br;
115           if (src.getReader() instanceof BufferedReader)
116           {
117             br = (BufferedReader) src.getReader();
118           }
119           else
120           {
121             br = new BufferedReader(src.getReader());
122           }
123           if (new jalview.io.AnnotationFile()
124                   .parseAnnotationFrom(context.getLastAlignment(), br))
125           {
126             context.updateSetModified(true);
127           } else {
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 Hashtable();
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         } else {
198           throw new IOException(errmsg,exerror);
199         }
200       } else {
201       if (errmsg!=null && errmsg.length()>0)
202       {
203         throw new IOException(errmsg);
204       }
205       }
206     }
207     if (deuniquify)
208     {
209       context.getLastAlignmentSet().deuniquifyAlignment();
210     }
211     return rslt.toArray();
212   }
213
214   /**
215    * simple command line test. Arguments should be one or more pairs of
216    * <DataProvider.JvDataType> <Filename> arguments. The routine will attempt to
217    * read each source in turn, and report what kind of Jalview datamodel objects
218    * would be created.
219    * 
220    * @param args
221    */
222   public static void main(String args[])
223   {
224     // make data providers from the set of keys/files
225     int i = 0;
226     List<DataProvider> dp = new ArrayList<DataProvider>();
227     while ((i + 1) < args.length)
228     {
229       String type = args[i++];
230       final String file = args[i++];
231       final JvDataType jtype = DataProvider.JvDataType.valueOf(type
232               .toUpperCase());
233       if (jtype != null)
234       {
235         final FileParse fp;
236         try
237         {
238           fp = new FileParse(file, AppletFormatAdapter.checkProtocol(file));
239         } catch (Exception e)
240         {
241           System.err.println("Couldn't handle datasource of type " + jtype
242                   + " using URI " + file);
243           e.printStackTrace();
244           return;
245         }
246         dp.add(new SimpleDataProvider(jtype, fp, null));
247       }
248       else
249       {
250         System.out.println("Couldn't parse source type token '"
251                 + type.toUpperCase() + "'");
252       }
253     }
254     if (i < args.length)
255     {
256       System.out.print("** WARNING\nIgnoring unused arguments:\n");
257       while (i < args.length)
258       {
259         System.out.print(" " + args[i]);
260       }
261       System.out.print("\n");
262
263     }
264     System.out.println("Now trying to parse set:");
265     JalviewDataset context;
266     Object[] newdm;
267     ParsePackedSet pps;
268     try
269     {
270       newdm = (pps = new ParsePackedSet()).getAlignment(
271               context = new JalviewDataset(), dp);
272     } catch (Exception e)
273     {
274       System.out.println("Test failed for these arguments.\n");
275       e.printStackTrace(System.out);
276       return;
277     }
278     if (newdm != null)
279     {
280       for (Object o : newdm)
281       {
282         System.out.println("Will need to create an " + o.getClass());
283       }
284
285       // now test uniquify/deuniquify stuff
286       // uniquify alignment and write alignment, annotation, features, and trees
287       // to buffers.
288       // import with deuniquify info, and compare results to input.
289
290     } else {
291       if (context.getLastAlignmentSet().isModified())
292       {
293         System.err.println("Initial alignment set was modified and any associated views should be updated.");
294       }
295     }
296   }
297 }