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