JAL-3691 toUpperCase(Locale.ROOT) for all standard file format operations
[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 /**
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("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(Locale.ROOT);
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 }