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