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