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