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