72a1155d0630435c2dd1bb2de8ebcad20a77b655
[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(AlignmentFileI 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("##GFF-VERSION"))
145         {
146           // GFF - possibly embedded in a Jalview features file!
147           reply = FileFormat.Features;
148           break;
149         }
150         if (looksLikeFeatureData(data))
151         {
152           reply = FileFormat.Features;
153           break;
154         }
155         if (data.indexOf("# STOCKHOLM") > -1)
156         {
157           reply = FileFormat.Stockholm;
158           break;
159         }
160         if (data.indexOf("_ENTRY.ID") > -1
161                 || data.indexOf("_AUDIT_AUTHOR.NAME") > -1
162                 || data.indexOf("_ATOM_SITE.") > -1)
163         {
164           reply = FileFormat.MMCif;
165           break;
166         }
167         // if (data.indexOf(">") > -1)
168         if (data.startsWith(">"))
169         {
170           // FASTA, PIR file or BLC file
171           boolean checkPIR = false, starterm = false;
172           if ((data.indexOf(">P1;") > -1) || (data.indexOf(">DL;") > -1))
173           {
174             // watch for PIR file attributes
175             checkPIR = true;
176             reply = FileFormat.PIR;
177           }
178           // could also be BLC file, read next line to confirm
179           data = source.nextLine();
180
181           if (data.indexOf(">") > -1)
182           {
183             reply = FileFormat.BLC;
184           }
185           else
186           {
187             // Is this a single line BLC file?
188             String data1 = source.nextLine();
189             String data2 = source.nextLine();
190             int c1;
191             if (checkPIR)
192             {
193               starterm = (data1 != null && data1.indexOf("*") > -1)
194                       || (data2 != null && data2.indexOf("*") > -1);
195             }
196             if (data2 != null && (c1 = data.indexOf("*")) > -1)
197             {
198               if (c1 == 0 && c1 == data2.indexOf("*"))
199               {
200                 reply = FileFormat.BLC;
201               }
202               else
203               {
204                 reply = FileFormat.Fasta; // possibly a bad choice - may be
205                                           // recognised as
206                 // PIR
207               }
208               // otherwise can still possibly be a PIR file
209             }
210             else
211             {
212               reply = FileFormat.Fasta;
213               // TODO : AMSA File is indicated if there is annotation in the
214               // FASTA file - but FASTA will automatically generate this at the
215               // mo.
216               if (!checkPIR)
217               {
218                 break;
219               }
220             }
221           }
222           // final check for PIR content. require
223           // >P1;title\n<blah>\nterminated sequence to occur at least once.
224
225           // TODO the PIR/fasta ambiguity may be the use case that is needed to
226           // have
227           // a 'Parse as type XXX' parameter for the applet/application.
228           if (checkPIR)
229           {
230             String dta = null;
231             if (!starterm)
232             {
233               do
234               {
235                 try
236                 {
237                   dta = source.nextLine();
238                 } catch (IOException ex)
239                 {
240                 }
241                 if (dta != null && dta.indexOf("*") > -1)
242                 {
243                   starterm = true;
244                 }
245               } while (dta != null && !starterm);
246             }
247             if (starterm)
248             {
249               reply = FileFormat.PIR;
250               break;
251             }
252             else
253             {
254               reply = FileFormat.Fasta; // probably a bad choice!
255             }
256           }
257           // read as a FASTA (probably)
258           break;
259         }
260         int lessThan = data.indexOf("<");
261         if ((lessThan > -1)) // possible Markup Language data i.e HTML,
262                              // RNAML, XML
263         {
264           String upper = data.toUpperCase();
265           if (upper.substring(lessThan).startsWith("<HTML"))
266           {
267             reply = FileFormat.Html;
268             break;
269           }
270           if (upper.substring(lessThan).startsWith("<RNAML"))
271           {
272             reply = FileFormat.Rnaml;
273             break;
274           }
275         }
276
277         if (data.indexOf("{\"") > -1)
278         {
279           reply = FileFormat.Json;
280           break;
281         }
282         if ((data.length() < 1) || (data.indexOf("#") == 0))
283         {
284           lineswereskipped = true;
285           continue;
286         }
287
288         if (data.indexOf("PILEUP") > -1)
289         {
290           reply = FileFormat.Pileup;
291
292           break;
293         }
294
295         if ((data.indexOf("//") == 0)
296                 || ((data.indexOf("!!") > -1) && (data.indexOf("!!") < data
297                         .indexOf("_MULTIPLE_ALIGNMENT "))))
298         {
299           reply = FileFormat.MSF;
300
301           break;
302         }
303         else if (data.indexOf("CLUSTAL") > -1)
304         {
305           reply = FileFormat.Clustal;
306
307           break;
308         }
309
310         else if (data.indexOf("HEADER") == 0 || data.indexOf("ATOM") == 0)
311         {
312           reply = FileFormat.PDB;
313           break;
314         }
315         else if (data.matches("\\s*\\d+\\s+\\d+\\s*"))
316         {
317           reply = FileFormat.Phylip;
318           break;
319         }
320         else
321         {
322           if (!lineswereskipped && looksLikeJnetData(data))
323           {
324             reply = FileFormat.Jnet;
325             break;
326           }
327         }
328
329         lineswereskipped = true; // this means there was some junk before any
330         // key file signature
331       }
332       if (closeSource)
333       {
334         source.close();
335       }
336       else
337       {
338         source.reset(bytesRead); // so the file can be parsed from the mark
339       }
340     } catch (Exception ex)
341     {
342       System.err.println("File Identification failed!\n" + ex);
343       throw new FileFormatException(source.errormessage);
344     }
345     if (trimmedLength == 0)
346     {
347       System.err
348               .println("File Identification failed! - Empty file was read.");
349       throw new FileFormatException("EMPTY DATA FILE");
350     }
351     System.out.println("File format identified as " + reply.toString());
352     return reply;
353   }
354
355   /**
356    * Returns true if the data appears to be Jnet concise annotation format
357    * 
358    * @param data
359    * @return
360    */
361   protected boolean looksLikeJnetData(String data)
362   {
363     char firstChar = data.charAt(0);
364     int colonPos = data.indexOf(":");
365     int commaPos = data.indexOf(",");
366     boolean isJnet = firstChar != '*' && firstChar != ' ' && colonPos > -1
367             && commaPos > -1 && colonPos < commaPos;
368     // && data.indexOf(",")<data.indexOf(",", data.indexOf(","))) / ??
369     return isJnet;
370   }
371
372   /**
373    * Returns true if the data has at least 6 tab-delimited fields _and_ fields 4
374    * and 5 are integer (start/end)
375    * 
376    * @param data
377    * @return
378    */
379   protected boolean looksLikeFeatureData(String data)
380   {
381     if (data == null)
382     {
383       return false;
384     }
385     String[] columns = data.split("\t");
386     if (columns.length < 6)
387     {
388       return false;
389     }
390     for (int col = 3; col < 5; col++)
391     {
392       try
393       {
394         Integer.parseInt(columns[col]);
395       } catch (NumberFormatException e)
396       {
397         return false;
398       }
399     }
400     return true;
401   }
402
403   public static void main(String[] args)
404   {
405     for (int i = 0; args != null && i < args.length; i++)
406     {
407       IdentifyFile ider = new IdentifyFile();
408       FileFormatI type = null;
409       try
410       {
411         type = ider.identify(args[i], DataSourceType.FILE);
412       } catch (FileFormatException e)
413       {
414         System.err.println(String.format(
415                 "Error '%s' identifying file type for %s", args[i],
416                 e.getMessage()));
417       }
418       System.out.println("Type of " + args[i] + " is " + type);
419     }
420     if (args == null || args.length == 0)
421     {
422       System.err.println("Usage: <Filename> [<Filename> ...]");
423     }
424   }
425 }