JAL-3746 release notes and what’s new for 2.11.2 - in progress
[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             char 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")
169                     || fileStr.contains(".zip") || fileStr.contains(".jvp"))
170             {
171               // possibly a Jalview archive (but check further)
172               reply = FileFormat.Jalview;
173             }
174           }
175           if (!lineswereskipped && data.startsWith("PK"))
176           {
177             reply = FileFormat.Jalview; // archive
178             break;
179           }
180         }
181         data = data.toUpperCase();
182
183         if (data.startsWith(ScoreMatrixFile.SCOREMATRIX))
184         {
185           reply = FileFormat.ScoreMatrix;
186           break;
187         }
188         if (data.startsWith("LOCUS"))
189         {
190           reply = FileFormat.GenBank;
191           break;
192         }
193         if (data.startsWith("ID "))
194         {
195           if (data.substring(2).trim().split(";").length == 7)
196           {
197             reply = FileFormat.Embl;
198             break;
199           }
200         }
201         if (data.startsWith("H ") && !aaIndexHeaderRead)
202         {
203           aaIndexHeaderRead = true;
204         }
205         if (data.startsWith("D ") && aaIndexHeaderRead)
206         {
207           reply = FileFormat.ScoreMatrix;
208           break;
209         }
210         if (data.startsWith("##GFF-VERSION"))
211         {
212           // GFF - possibly embedded in a Jalview features file!
213           reply = FileFormat.Features;
214           break;
215         }
216         if (looksLikeFeatureData(data))
217         {
218           reply = FileFormat.Features;
219           break;
220         }
221         if (data.indexOf("# STOCKHOLM") > -1)
222         {
223           reply = FileFormat.Stockholm;
224           break;
225         }
226         if (data.indexOf("_ENTRY.ID") > -1
227                 || data.indexOf("_AUDIT_AUTHOR.NAME") > -1
228                 || data.indexOf("_ATOM_SITE.") > -1)
229         {
230           reply = FileFormat.MMCif;
231           break;
232         }
233         // if (data.indexOf(">") > -1)
234         if (data.startsWith(">"))
235         {
236           // FASTA, PIR file or BLC file
237           boolean checkPIR = false, starterm = false;
238           if ((data.indexOf(">P1;") > -1) || (data.indexOf(">DL;") > -1))
239           {
240             // watch for PIR file attributes
241             checkPIR = true;
242             reply = FileFormat.PIR;
243           }
244           // could also be BLC file, read next line to confirm
245           data = source.nextLine();
246
247           if (data.indexOf(">") > -1)
248           {
249             reply = FileFormat.BLC;
250           }
251           else
252           {
253             // Is this a single line BLC file?
254             String data1 = source.nextLine();
255             String data2 = source.nextLine();
256             int c1;
257             if (checkPIR)
258             {
259               starterm = (data1 != null && data1.indexOf("*") > -1)
260                       || (data2 != null && data2.indexOf("*") > -1);
261             }
262             if (data2 != null && (c1 = data.indexOf("*")) > -1)
263             {
264               if (c1 == 0 && c1 == data2.indexOf("*"))
265               {
266                 reply = FileFormat.BLC;
267               }
268               else
269               {
270                 reply = FileFormat.Fasta; // possibly a bad choice - may be
271                                           // recognised as
272                 // PIR
273               }
274               // otherwise can still possibly be a PIR file
275             }
276             else
277             {
278               reply = FileFormat.Fasta;
279               // TODO : AMSA File is indicated if there is annotation in the
280               // FASTA file - but FASTA will automatically generate this at the
281               // mo.
282               if (!checkPIR)
283               {
284                 break;
285               }
286             }
287           }
288           // final check for PIR content. require
289           // >P1;title\n<blah>\nterminated sequence to occur at least once.
290
291           // TODO the PIR/fasta ambiguity may be the use case that is needed to
292           // have
293           // a 'Parse as type XXX' parameter for the applet/application.
294           if (checkPIR)
295           {
296             String dta = null;
297             if (!starterm)
298             {
299               do
300               {
301                 try
302                 {
303                   dta = source.nextLine();
304                 } catch (IOException ex)
305                 {
306                 }
307                 if (dta != null && dta.indexOf("*") > -1)
308                 {
309                   starterm = true;
310                 }
311               } while (dta != null && !starterm);
312             }
313             if (starterm)
314             {
315               reply = FileFormat.PIR;
316               break;
317             }
318             else
319             {
320               reply = FileFormat.Fasta; // probably a bad choice!
321             }
322           }
323           // read as a FASTA (probably)
324           break;
325         }
326         if (data.indexOf("{\"") > -1)
327         {
328           reply = FileFormat.Json;
329           break;
330         }
331         int lessThan = data.indexOf("<");
332         if ((lessThan > -1)) // possible Markup Language data i.e HTML,
333                              // RNAML, XML
334         {
335           String upper = data.toUpperCase();
336           if (upper.substring(lessThan).startsWith("<HTML"))
337           {
338             reply = FileFormat.Html;
339             break;
340           }
341           if (upper.substring(lessThan).startsWith("<RNAML"))
342           {
343             reply = FileFormat.Rnaml;
344             break;
345           }
346         }
347
348         if ((data.length() < 1) || (data.indexOf("#") == 0))
349         {
350           lineswereskipped = true;
351           continue;
352         }
353
354         if (data.indexOf("PILEUP") > -1)
355         {
356           reply = FileFormat.Pileup;
357
358           break;
359         }
360
361         if ((data.indexOf("//") == 0) || ((data.indexOf("!!") > -1) && (data
362                 .indexOf("!!") < data.indexOf("_MULTIPLE_ALIGNMENT "))))
363         {
364           reply = FileFormat.MSF;
365
366           break;
367         }
368         else if (data.indexOf("CLUSTAL") > -1)
369         {
370           reply = FileFormat.Clustal;
371
372           break;
373         }
374
375         else if (data.indexOf("HEADER") == 0 || data.indexOf("ATOM") == 0)
376         {
377           reply = FileFormat.PDB;
378           break;
379         }
380         else if (data.matches("\\s*\\d+\\s+\\d+\\s*"))
381         {
382           reply = FileFormat.Phylip;
383           break;
384         }
385         else
386         {
387           if (!lineswereskipped && looksLikeJnetData(data))
388           {
389             reply = FileFormat.Jnet;
390             break;
391           }
392         }
393
394         lineswereskipped = true; // this means there was some junk before any
395         // key file signature
396       }
397       if (closeSource)
398       {
399         source.close();
400       }
401       else
402       {
403         source.reset(bytesRead); // so the file can be parsed from the mark
404       }
405     } catch (Exception ex)
406     {
407       System.err.println("File Identification failed!\n" + ex);
408       throw new FileFormatException(source.errormessage);
409     }
410     if (trimmedLength == 0)
411     {
412       System.err.println(
413               "File Identification failed! - Empty file was read.");
414       throw new FileFormatException("EMPTY DATA FILE");
415     }
416     System.out.println("File format identified as " + reply.toString());
417     return reply;
418   }
419
420   /**
421    * Returns true if the data appears to be Jnet concise annotation format
422    * 
423    * @param data
424    * @return
425    */
426   protected boolean looksLikeJnetData(String data)
427   {
428     char firstChar = data.charAt(0);
429     int colonPos = data.indexOf(":");
430     int commaPos = data.indexOf(",");
431     boolean isJnet = firstChar != '*' && firstChar != ' ' && colonPos > -1
432             && commaPos > -1 && colonPos < commaPos;
433     // && data.indexOf(",")<data.indexOf(",", data.indexOf(","))) / ??
434     return isJnet;
435   }
436
437   /**
438    * Returns true if the data has at least 6 tab-delimited fields _and_ fields 4
439    * and 5 are integer (start/end)
440    * 
441    * @param data
442    * @return
443    */
444   protected boolean looksLikeFeatureData(String data)
445   {
446     if (data == null)
447     {
448       return false;
449     }
450     String[] columns = data.split("\t");
451     if (columns.length < 6)
452     {
453       return false;
454     }
455     for (int col = 3; col < 5; col++)
456     {
457       try
458       {
459         Integer.parseInt(columns[col]);
460       } catch (NumberFormatException e)
461       {
462         return false;
463       }
464     }
465     return true;
466   }
467
468   /**
469    * 
470    * @param args
471    * @j2sIgnore
472    */
473   public static void main(String[] args)
474   {
475     for (int i = 0; args != null && i < args.length; i++)
476     {
477       IdentifyFile ider = new IdentifyFile();
478       FileFormatI type = null;
479       try
480       {
481         type = ider.identify(args[i], DataSourceType.FILE);
482       } catch (FileFormatException e)
483       {
484         System.err.println(
485                 String.format("Error '%s' identifying file type for %s",
486                         args[i], e.getMessage()));
487       }
488       System.out.println("Type of " + args[i] + " is " + type);
489     }
490     if (args == null || args.length == 0)
491     {
492       System.err.println("Usage: <Filename> [<Filename> ...]");
493     }
494   }
495
496  
497 }