Merge branch 'develop' of https://source.jalview.org/git/jalview.git into develop
[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    *          DOCUMENT ME!
41    * @param protocol
42    *          DOCUMENT ME!
43    * @return ID String
44    */
45   public String Identify(String file, String protocol)
46   {
47     String emessage = "UNIDENTIFIED FILE PARSING ERROR";
48     FileParse parser = null;
49     try
50     {
51       parser = new FileParse(file, protocol);
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       return parser.errormessage;
65     }
66     return emessage;
67   }
68
69   public String Identify(FileParse source)
70   {
71     return Identify(source, true); // preserves original behaviour prior to
72     // version 2.3
73   }
74
75   /**
76    * Identify contents of source, closing it or resetting source to start
77    * afterwards.
78    *
79    * @param source
80    * @param closeSource
81    * @return filetype string
82    */
83   public String Identify(FileParse source, boolean closeSource)
84   {
85     String reply = "PFAM";
86     String data;
87     int length = 0;
88     boolean lineswereskipped = false;
89     boolean isBinary = false; // true if length is non-zero and non-printable
90     // characters are encountered
91     try
92     {
93       if (!closeSource)
94       {
95         source.mark();
96       }
97       while ((data = source.nextLine()) != null)
98       {
99         length += data.length();
100         if (!lineswereskipped)
101         {
102           for (int i = 0; !isBinary && i < data.length(); i++)
103           {
104             char c = data.charAt(i);
105             isBinary = (c < 32 && c != '\t' && c != '\n' && c != '\r'
106                     && c != 5 && c != 27); // nominal binary character filter
107             // excluding CR, LF, tab,DEL and ^E
108             // for certain blast ids
109           }
110         }
111         if (isBinary)
112         {
113           // jar files are special - since they contain all sorts of random
114           // characters.
115           if (source.inFile != null)
116           {
117             String fileStr = source.inFile.getName();
118             // possibly a Jalview archive.
119             if (fileStr.lastIndexOf(".jar") > -1
120                     || fileStr.lastIndexOf(".zip") > -1)
121             {
122               reply = "Jalview";
123             }
124           }
125           if (!lineswereskipped && data.startsWith("PK"))
126           {
127             reply = "Jalview"; // archive.
128             break;
129           }
130         }
131         data = data.toUpperCase();
132
133         if ((data.indexOf("# STOCKHOLM") > -1))
134         {
135           reply = "STH";
136           break;
137         }
138         // if (data.matches("<(\"[^\"]*\"|'[^']*'|[^'\">])*>"))
139         if (data.matches("<(?i)html(\"[^\"]*\"|'[^']*'|[^'\">])*>"))
140         {
141           reply = HtmlFile.FILE_DESC;
142           break;
143         }
144
145         if (data.matches("<(?i)rnaml (\"[^\"]*\"|'[^']*'|[^'\">])*>"))
146         {
147           reply = "RNAML";
148           break;
149         }
150
151          if (data.indexOf("{\"") > -1)
152          {
153          reply = JSONFile.FILE_DESC;
154          break;
155          }
156         if ((data.length() < 1) || (data.indexOf("#") == 0))
157         {
158           lineswereskipped = true;
159           continue;
160         }
161
162         if (data.indexOf("PILEUP") > -1)
163         {
164           reply = "PileUp";
165
166           break;
167         }
168
169         if ((data.indexOf("//") == 0)
170                 || ((data.indexOf("!!") > -1) && (data.indexOf("!!") < data
171                         .indexOf("_MULTIPLE_ALIGNMENT "))))
172         {
173           reply = "MSF";
174
175           break;
176         }
177         else if (data.indexOf("CLUSTAL") > -1)
178         {
179           reply = "CLUSTAL";
180
181           break;
182         }
183
184         else if (data.indexOf(">") > -1)
185         {
186           // FASTA, PIR file or BLC file
187           boolean checkPIR = false, starterm = false;
188           if ((data.indexOf(">P1;") > -1) || (data.indexOf(">DL;") > -1))
189           {
190             // watch for PIR file attributes
191             checkPIR = true;
192             reply = "PIR";
193           }
194           // could also be BLC file, read next line to confirm
195           data = source.nextLine();
196
197           if (data.indexOf(">") > -1)
198           {
199             reply = "BLC";
200           }
201           else
202           {
203             // Is this a single line BLC file?
204             String data1 = source.nextLine();
205             String data2 = source.nextLine();
206             int c1;
207             if (checkPIR)
208             {
209               starterm = (data1 != null && data1.indexOf("*") > -1)
210                       || (data2 != null && data2.indexOf("*") > -1);
211             }
212             if (data2 != null && (c1 = data.indexOf("*")) > -1)
213             {
214               if (c1 == 0 && c1 == data2.indexOf("*"))
215               {
216                 reply = "BLC";
217               }
218               else
219               {
220                 reply = "FASTA"; // possibly a bad choice - may be recognised as
221                 // PIR
222               }
223               // otherwise can still possibly be a PIR file
224             }
225             else
226             {
227               reply = "FASTA";
228               // TODO : AMSA File is indicated if there is annotation in the
229               // FASTA file - but FASTA will automatically generate this at the
230               // mo.
231               if (!checkPIR)
232               {
233                 break;
234               }
235             }
236           }
237           // final check for PIR content. require
238           // >P1;title\n<blah>\nterminated sequence to occur at least once.
239
240           // TODO the PIR/fasta ambiguity may be the use case that is needed to
241           // have
242           // a 'Parse as type XXX' parameter for the applet/application.
243           if (checkPIR)
244           {
245             String dta = null;
246             if (!starterm)
247             {
248               do
249               {
250                 try
251                 {
252                   dta = source.nextLine();
253                 } catch (IOException ex)
254                 {
255                 }
256                 ;
257                 if (dta != null && dta.indexOf("*") > -1)
258                 {
259                   starterm = true;
260                 }
261               } while (dta != null && !starterm);
262             }
263             if (starterm)
264             {
265               reply = "PIR";
266               break;
267             }
268             else
269             {
270               reply = "FASTA"; // probably a bad choice!
271             }
272           }
273           // read as a FASTA (probably)
274           break;
275         }
276         else if (data.indexOf("HEADER") == 0 || data.indexOf("ATOM") == 0)
277         {
278           reply = "PDB";
279           break;
280         }
281         else if (data.matches("\\s*\\d+\\s+\\d+\\s*"))
282         {
283           reply = PhylipFile.FILE_DESC;
284           break;
285         }
286
287
288         /*
289          * // TODO comment out SimpleBLAST identification for Jalview 2.4.1 else
290          * if (!lineswereskipped && data.indexOf("BLAST")<4) { reply =
291          * "SimpleBLAST"; break;
292          *
293          * } // end comments for Jalview 2.4.1
294          */
295         else if (!lineswereskipped && data.charAt(0) != '*'
296                 && data.charAt(0) != ' '
297                 && data.indexOf(":") < data.indexOf(",")) // &&
298           // data.indexOf(",")<data.indexOf(",",
299           // data.indexOf(",")))
300         {
301           // file looks like a concise JNet file
302           reply = "JnetFile";
303           break;
304         }
305
306         lineswereskipped = true; // this means there was some junk before any
307         // key file signature
308       }
309       if (closeSource)
310       {
311         source.close();
312       }
313       else
314       {
315         source.reset(); // so the file can be parsed from the beginning again.
316       }
317     } catch (Exception ex)
318     {
319       System.err.println("File Identification failed!\n" + ex);
320       return source.errormessage;
321     }
322     if (length == 0)
323     {
324       System.err
325       .println("File Identification failed! - Empty file was read.");
326       return "EMPTY DATA FILE";
327     }
328     return reply;
329   }
330
331   public static void main(String[] args)
332   {
333
334     for (int i = 0; args != null && i < args.length; i++)
335     {
336       IdentifyFile ider = new IdentifyFile();
337       String type = ider.Identify(args[i], AppletFormatAdapter.FILE);
338       System.out.println("Type of " + args[i] + " is " + type);
339     }
340     if (args == null || args.length == 0)
341     {
342       System.err.println("Usage: <Filename> [<Filename> ...]");
343     }
344   }
345 }