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