javadoc and main method for testing file input routines
[jalview.git] / src / jalview / io / AppletFormatAdapter.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.io;
20
21 import java.io.File;
22
23 import jalview.datamodel.*;
24
25 /**
26  * A low level class for alignment and feature IO
27  * with alignment formatting methods used by both applet 
28  * and application for generating flat alignment files.
29  * It also holds the lists of magic format names
30  * that the applet and application will allow the user to read or write files with.
31  *
32  * @author $author$
33  * @version $Revision$
34  */
35 public class AppletFormatAdapter
36 {
37   /** 
38    * List of valid format strings used in the isValidFormat method 
39    */
40   public static final String[] READABLE_FORMATS = new String[]
41       {
42       "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH", "PDB", "JnetFile"
43   };
44   /**
45    * List of valid format strings for use by callers of the formatSequences method
46    */
47   public static final String[] WRITEABLE_FORMATS = new String[]
48       {
49       "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM" , "AMSA"
50   };
51   /**
52    * List of extensions corresponding to file format types 
53    * in WRITABLE_FNAMES that are writable by the
54    * application.
55    */
56   public static final String[] WRITABLE_EXTENSIONS = new String[]
57         { "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc","amsa","jar" };
58   /**
59    * List of writable formats by the application. Order must
60    * correspond with the WRITABLE_EXTENSIONS list of formats.
61    */
62   public static final String[] WRITABLE_FNAMES = new String[]
63         { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview" };
64
65   /**
66    * List of readable format file extensions by application in order
67    * corresponding to READABLE_FNAMES 
68    */
69   public static final String[] READABLE_EXTENSIONS =         new String[]
70         {
71         "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc",
72         "amsa","jar"
73     };
74   /**
75    * List of readable formats by application in order
76    * corresponding to READABLE_EXTENSIONS
77    */
78   public static final String[] READABLE_FNAMES =         new String[]
79         {
80         "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA","Jalview"
81     };
82         
83   public static String INVALID_CHARACTERS = "Contains invalid characters";
84   // TODO: make these messages dynamic
85   public static String SUPPORTED_FORMATS = "Formats currently supported are\n" +
86     prettyPrint(READABLE_FORMATS);
87   /**
88    * 
89    * @param els
90    * @return grammatically correct(ish) list consisting of els elements.
91    */
92   public static String prettyPrint(String[] els) {
93     StringBuffer list = new StringBuffer();
94     for (int i=0,iSize=els.length-1; i<iSize;i++)
95     {
96       list.append(els[i]);
97       list.append(",");
98     }
99     list.append(" and "+els[els.length-1]+".");
100     return list.toString();
101   }
102   public static String FILE = "File";
103   public static String URL = "URL";
104   public static String PASTE = "Paste";
105   public static String CLASSLOADER = "ClassLoader";
106
107   AlignFile afile = null;
108   String inFile;
109   /**
110    * check that this format is valid for reading
111    * @param format a format string to be compared with READABLE_FORMATS
112    * @return true if format is readable
113    */
114   public static final boolean isValidFormat(String format)
115   {
116     boolean valid = false;
117     for (int i = 0; i < READABLE_FORMATS.length; i++)
118     {
119       if (READABLE_FORMATS[i].equalsIgnoreCase(format))
120       {
121         return true;
122       }
123     }
124
125     return valid;
126   }
127
128   /**
129    * Constructs the correct filetype parser for a characterised datasource
130    *
131    * @param inFile data/data location
132    * @param type type of datasource
133    * @param format File format of data provided by datasource
134    *
135    * @return DOCUMENT ME!
136    */
137   public Alignment readFile(String inFile, String type, String format)
138       throws java.io.IOException
139   {
140     this.inFile = inFile;
141     try
142     {
143       if (format.equals("FASTA"))
144       {
145         afile = new FastaFile(inFile, type);
146       }
147       else if (format.equals("MSF"))
148       {
149         afile = new MSFfile(inFile, type);
150       }
151       else if (format.equals("PileUp"))
152       {
153         afile = new PileUpfile(inFile, type);
154       }
155       else if (format.equals("CLUSTAL"))
156       {
157         afile = new ClustalFile(inFile, type);
158       }
159       else if (format.equals("BLC"))
160       {
161         afile = new BLCFile(inFile, type);
162       }
163       else if (format.equals("PIR"))
164       {
165         afile = new PIRFile(inFile, type);
166       }
167       else if (format.equals("PFAM"))
168       {
169         afile = new PfamFile(inFile, type);
170       }
171       else if (format.equals("JnetFile"))
172       {
173         afile = new JPredFile(inFile, type);
174         ( (JPredFile) afile).removeNonSequences();
175       }
176       else if (format.equals("PDB"))
177       {
178         afile = new MCview.PDBfile(inFile, type);
179       }
180       else if (format.equals("STH"))
181       {
182         afile = new StockholmFile(inFile, type);
183       }
184
185       Alignment al = new Alignment(afile.getSeqsAsArray());
186
187       afile.addAnnotations(al);
188
189       return al;
190     }
191     catch (Exception e)
192     {
193       e.printStackTrace();
194       System.err.println("Failed to read alignment using the '" + format +
195                          "' reader.\n" + e);
196
197       if (e.getMessage() != null &&
198           e.getMessage().startsWith(INVALID_CHARACTERS))
199       {
200         throw new java.io.IOException(e.getMessage());
201       }
202
203       // Finally test if the user has pasted just the sequence, no id
204       if (type.equalsIgnoreCase("Paste"))
205       {
206         try
207         {
208           // Possible sequence is just residues with no label
209           afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
210           Alignment al = new Alignment(afile.getSeqsAsArray());
211           afile.addAnnotations(al);
212           return al;
213
214         }
215         catch (Exception ex)
216         {
217           if (ex.toString().startsWith(INVALID_CHARACTERS))
218           {
219             throw new java.io.IOException(e.getMessage());
220           }
221
222           ex.printStackTrace();
223         }
224       }
225
226       // If we get to this stage, the format was not supported
227       throw new java.io.IOException(SUPPORTED_FORMATS);
228     }
229   }
230
231   /**
232    * Construct an output class for an alignment in a particular filetype
233    *
234    * @param format string name of alignment format 
235    * @param alignment the alignment to be written out
236    * @param jvsuffix passed to AlnFile class controls whether /START-END is added to sequence names
237    *
238    * @return alignment flat file contents
239    */
240   public String formatSequences(String format,
241                                 AlignmentI alignment,
242                                 boolean jvsuffix)
243   {
244     try
245     {
246       AlignFile afile = null;
247
248       if (format.equalsIgnoreCase("FASTA"))
249       {
250         afile = new FastaFile();
251       }
252       else if (format.equalsIgnoreCase("MSF"))
253       {
254         afile = new MSFfile();
255       }
256       else if (format.equalsIgnoreCase("PileUp"))
257       {
258         afile = new PileUpfile();
259       }
260       else if (format.equalsIgnoreCase("CLUSTAL"))
261       {
262         afile = new ClustalFile();
263       }
264       else if (format.equalsIgnoreCase("BLC"))
265       {
266         afile = new BLCFile();
267       }
268       else if (format.equalsIgnoreCase("PIR"))
269       {
270         afile = new PIRFile();
271       }
272       else if (format.equalsIgnoreCase("PFAM"))
273       {
274         afile = new PfamFile();
275       }
276       else if (format.equalsIgnoreCase("STH"))
277       {
278         afile = new StockholmFile();
279       }
280       else if (format.equalsIgnoreCase("AMSA"))
281       {
282         afile = new AMSAFile(alignment);
283       } else {
284         throw new Exception("Implementation error: Unknown file format string");
285       }
286
287       afile.addJVSuffix(jvsuffix);
288
289       afile.setSeqs(alignment.getSequencesArray());
290
291       return afile.print();
292     }
293     catch (Exception e)
294     {
295       System.err.println("Failed to write alignment as a '" + format +
296                          "' file\n");
297       e.printStackTrace();
298     }
299
300     return null;
301   }
302   public static void main(String[] args)
303   {
304     int i=0;
305     while (i<args.length)
306     {
307       File f = new File(args[i]);
308       if (f.exists())
309       {
310         try {
311           AppletFormatAdapter afa = new AppletFormatAdapter();
312           afa.readFile(args[i], FILE, new IdentifyFile().Identify(args[i], FILE));
313         } catch (Exception e)
314         {
315           System.err.println("Exception when dealing with "+i+"'th argument: "+args[i]+"\n"+e);
316         }
317       } else {
318           System.err.println("Ignoring argument '"+args[i]+"' ("+i+"'th)- not a readable file.");
319       }
320       i++;
321     }
322     
323   }
324 }