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