Parsing moved to (new) ScoreMatrixFile, drag and drop to alignment now
[jalview.git] / src / jalview / io / IdentifyFile.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;
22
23 import java.io.IOException;
24
25 /**
26  * DOCUMENT ME!
27  *
28  * @author $author$
29  * @version $Revision$
30  */
31 public class IdentifyFile
32 {
33   /**
34    * Identify a datasource's file content.
35    *
36    * @note Do not use this method for stream sources - create a FileParse object
37    *       instead.
38    *
39    * @param file
40    * @param sourceType
41    * @return
42    * @throws FileFormatException
43    */
44   public FileFormatI identify(String file, DataSourceType sourceType)
45           throws FileFormatException
46   {
47     String emessage = "UNIDENTIFIED FILE PARSING ERROR";
48     FileParse parser = null;
49     try
50     {
51       parser = new FileParse(file, sourceType);
52       if (parser.isValid())
53       {
54         return identify(parser);
55       }
56     } catch (Exception e)
57     {
58       System.err.println("Error whilst identifying");
59       e.printStackTrace(System.err);
60       emessage = e.getMessage();
61     }
62     if (parser != null)
63     {
64       throw new FileFormatException(parser.errormessage);
65     }
66     throw new FileFormatException(emessage);
67   }
68
69   public FileFormatI identify(FileParse source) throws FileFormatException
70   {
71     return identify(source, true);
72     // preserves original behaviour prior to version 2.3
73   }
74
75   public FileFormatI identify(AlignmentFileReaderI file, boolean closeSource)
76           throws IOException
77   {
78     FileParse fp = new FileParse(file.getInFile(), file.getDataSourceType());
79     return identify(fp, closeSource);
80   }
81
82   /**
83    * Identify contents of source, closing it or resetting source to start
84    * afterwards.
85    *
86    * @param source
87    * @param closeSource
88    * @return (best guess at) file format
89    * @throws FileFormatException
90    */
91   public FileFormatI identify(FileParse source, boolean closeSource)
92           throws FileFormatException
93   {
94     FileFormatI reply = FileFormat.Pfam;
95     String data;
96     int bytesRead = 0;
97     int trimmedLength = 0;
98     boolean lineswereskipped = false;
99     boolean isBinary = false; // true if length is non-zero and non-printable
100     // characters are encountered
101     try
102     {
103       if (!closeSource)
104       {
105         source.mark();
106       }
107       while ((data = source.nextLine()) != null)
108       {
109         bytesRead += data.length();
110         trimmedLength += data.trim().length();
111         if (!lineswereskipped)
112         {
113           for (int i = 0; !isBinary && i < data.length(); i++)
114           {
115             char c = data.charAt(i);
116             isBinary = (c < 32 && c != '\t' && c != '\n' && c != '\r'
117                     && c != 5 && c != 27); // nominal binary character filter
118             // excluding CR, LF, tab,DEL and ^E
119             // for certain blast ids
120           }
121         }
122         if (isBinary)
123         {
124           // jar files are special - since they contain all sorts of random
125           // characters.
126           if (source.inFile != null)
127           {
128             String fileStr = source.inFile.getName();
129             // possibly a Jalview archive.
130             if (fileStr.lastIndexOf(".jar") > -1
131                     || fileStr.lastIndexOf(".zip") > -1)
132             {
133               reply = FileFormat.Jalview;
134             }
135           }
136           if (!lineswereskipped && data.startsWith("PK"))
137           {
138             reply = FileFormat.Jalview; // archive.
139             break;
140           }
141         }
142         data = data.toUpperCase();
143
144         if (data.startsWith(ScoreMatrixFile.SCOREMATRIX))
145         {
146           reply = FileFormat.ScoreMatrix;
147           break;
148         }
149         if (data.startsWith("##GFF-VERSION"))
150         {
151           // GFF - possibly embedded in a Jalview features file!
152           reply = FileFormat.Features;
153           break;
154         }
155         if (looksLikeFeatureData(data))
156         {
157           reply = FileFormat.Features;
158           break;
159         }
160         if (data.indexOf("# STOCKHOLM") > -1)
161         {
162           reply = FileFormat.Stockholm;
163           break;
164         }
165         if (data.indexOf("_ENTRY.ID") > -1
166                 || data.indexOf("_AUDIT_AUTHOR.NAME") > -1
167                 || data.indexOf("_ATOM_SITE.") > -1)
168         {
169           reply = FileFormat.MMCif;
170           break;
171         }
172         // if (data.indexOf(">") > -1)
173         if (data.startsWith(">"))
174         {
175           // FASTA, PIR file or BLC file
176           boolean checkPIR = false, starterm = false;
177           if ((data.indexOf(">P1;") > -1) || (data.indexOf(">DL;") > -1))
178           {
179             // watch for PIR file attributes
180             checkPIR = true;
181             reply = FileFormat.PIR;
182           }
183           // could also be BLC file, read next line to confirm
184           data = source.nextLine();
185
186           if (data.indexOf(">") > -1)
187           {
188             reply = FileFormat.BLC;
189           }
190           else
191           {
192             // Is this a single line BLC file?
193             String data1 = source.nextLine();
194             String data2 = source.nextLine();
195             int c1;
196             if (checkPIR)
197             {
198               starterm = (data1 != null && data1.indexOf("*") > -1)
199                       || (data2 != null && data2.indexOf("*") > -1);
200             }
201             if (data2 != null && (c1 = data.indexOf("*")) > -1)
202             {
203               if (c1 == 0 && c1 == data2.indexOf("*"))
204               {
205                 reply = FileFormat.BLC;
206               }
207               else
208               {
209                 reply = FileFormat.Fasta; // possibly a bad choice - may be
210                                           // recognised as
211                 // PIR
212               }
213               // otherwise can still possibly be a PIR file
214             }
215             else
216             {
217               reply = FileFormat.Fasta;
218               // TODO : AMSA File is indicated if there is annotation in the
219               // FASTA file - but FASTA will automatically generate this at the
220               // mo.
221               if (!checkPIR)
222               {
223                 break;
224               }
225             }
226           }
227           // final check for PIR content. require
228           // >P1;title\n<blah>\nterminated sequence to occur at least once.
229
230           // TODO the PIR/fasta ambiguity may be the use case that is needed to
231           // have
232           // a 'Parse as type XXX' parameter for the applet/application.
233           if (checkPIR)
234           {
235             String dta = null;
236             if (!starterm)
237             {
238               do
239               {
240                 try
241                 {
242                   dta = source.nextLine();
243                 } catch (IOException ex)
244                 {
245                 }
246                 if (dta != null && dta.indexOf("*") > -1)
247                 {
248                   starterm = true;
249                 }
250               } while (dta != null && !starterm);
251             }
252             if (starterm)
253             {
254               reply = FileFormat.PIR;
255               break;
256             }
257             else
258             {
259               reply = FileFormat.Fasta; // probably a bad choice!
260             }
261           }
262           // read as a FASTA (probably)
263           break;
264         }
265         int lessThan = data.indexOf("<");
266         if ((lessThan > -1)) // possible Markup Language data i.e HTML,
267                              // RNAML, XML
268         {
269           String upper = data.toUpperCase();
270           if (upper.substring(lessThan).startsWith("<HTML"))
271           {
272             reply = FileFormat.Html;
273             break;
274           }
275           if (upper.substring(lessThan).startsWith("<RNAML"))
276           {
277             reply = FileFormat.Rnaml;
278             break;
279           }
280         }
281
282         if (data.indexOf("{\"") > -1)
283         {
284           reply = FileFormat.Json;
285           break;
286         }
287         if ((data.length() < 1) || (data.indexOf("#") == 0))
288         {
289           lineswereskipped = true;
290           continue;
291         }
292
293         if (data.indexOf("PILEUP") > -1)
294         {
295           reply = FileFormat.Pileup;
296
297           break;
298         }
299
300         if ((data.indexOf("//") == 0)
301                 || ((data.indexOf("!!") > -1) && (data.indexOf("!!") < data
302                         .indexOf("_MULTIPLE_ALIGNMENT "))))
303         {
304           reply = FileFormat.MSF;
305
306           break;
307         }
308         else if (data.indexOf("CLUSTAL") > -1)
309         {
310           reply = FileFormat.Clustal;
311
312           break;
313         }
314
315         else if (data.indexOf("HEADER") == 0 || data.indexOf("ATOM") == 0)
316         {
317           reply = FileFormat.PDB;
318           break;
319         }
320         else if (data.matches("\\s*\\d+\\s+\\d+\\s*"))
321         {
322           reply = FileFormat.Phylip;
323           break;
324         }
325         else
326         {
327           if (!lineswereskipped && looksLikeJnetData(data))
328           {
329             reply = FileFormat.Jnet;
330             break;
331           }
332         }
333
334         lineswereskipped = true; // this means there was some junk before any
335         // key file signature
336       }
337       if (closeSource)
338       {
339         source.close();
340       }
341       else
342       {
343         source.reset(bytesRead); // so the file can be parsed from the mark
344       }
345     } catch (Exception ex)
346     {
347       System.err.println("File Identification failed!\n" + ex);
348       throw new FileFormatException(source.errormessage);
349     }
350     if (trimmedLength == 0)
351     {
352       System.err
353               .println("File Identification failed! - Empty file was read.");
354       throw new FileFormatException("EMPTY DATA FILE");
355     }
356     System.out.println("File format identified as " + reply.toString());
357     return reply;
358   }
359
360   /**
361    * Returns true if the data appears to be Jnet concise annotation format
362    * 
363    * @param data
364    * @return
365    */
366   protected boolean looksLikeJnetData(String data)
367   {
368     char firstChar = data.charAt(0);
369     int colonPos = data.indexOf(":");
370     int commaPos = data.indexOf(",");
371     boolean isJnet = firstChar != '*' && firstChar != ' ' && colonPos > -1
372             && commaPos > -1 && colonPos < commaPos;
373     // && data.indexOf(",")<data.indexOf(",", data.indexOf(","))) / ??
374     return isJnet;
375   }
376
377   /**
378    * Returns true if the data has at least 6 tab-delimited fields _and_ fields 4
379    * and 5 are integer (start/end)
380    * 
381    * @param data
382    * @return
383    */
384   protected boolean looksLikeFeatureData(String data)
385   {
386     if (data == null)
387     {
388       return false;
389     }
390     String[] columns = data.split("\t");
391     if (columns.length < 6)
392     {
393       return false;
394     }
395     for (int col = 3; col < 5; col++)
396     {
397       try
398       {
399         Integer.parseInt(columns[col]);
400       } catch (NumberFormatException e)
401       {
402         return false;
403       }
404     }
405     return true;
406   }
407
408   public static void main(String[] args)
409   {
410     for (int i = 0; args != null && i < args.length; i++)
411     {
412       IdentifyFile ider = new IdentifyFile();
413       FileFormatI type = null;
414       try
415       {
416         type = ider.identify(args[i], DataSourceType.FILE);
417       } catch (FileFormatException e)
418       {
419         System.err.println(String.format(
420                 "Error '%s' identifying file type for %s", args[i],
421                 e.getMessage()));
422       }
423       System.out.println("Type of " + args[i] + " is " + type);
424     }
425     if (args == null || args.length == 0)
426     {
427       System.err.println("Usage: <Filename> [<Filename> ...]");
428     }
429   }
430 }