in progress
[jalview.git] / forester / java / src / org / forester / io / parsers / util / ParserUtils.java
1 // $Id:
2 //
3 // FORESTER -- software libraries and applications
4 // for evolutionary biology research and applications.
5 //
6 // Copyright (C) 2008-2009 Christian M. Zmasek
7 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
8 // All rights reserved
9 //
10 // This library is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU Lesser General Public
12 // License as published by the Free Software Foundation; either
13 // version 2.1 of the License, or (at your option) any later version.
14 //
15 // This library is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // Lesser General Public License for more details.
19 //
20 // You should have received a copy of the GNU Lesser General Public
21 // License along with this library; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 //
24 // Contact: phylosoft @ gmail . com
25 // WWW: www.phylosoft.org/
26
27 package org.forester.io.parsers.util;
28
29 import java.io.BufferedReader;
30 import java.io.File;
31 import java.io.FileNotFoundException;
32 import java.io.FileReader;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.InputStreamReader;
36 import java.io.StringReader;
37 import java.net.URL;
38 import java.util.regex.Matcher;
39
40 import org.forester.io.parsers.PhylogenyParser;
41 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
42 import org.forester.io.parsers.nhx.NHXParser;
43 import org.forester.io.parsers.phyloxml.PhyloXmlParser;
44 import org.forester.io.parsers.tol.TolParser;
45 import org.forester.phylogeny.Phylogeny;
46 import org.forester.phylogeny.PhylogenyMethods;
47 import org.forester.util.ForesterConstants;
48 import org.forester.util.ForesterUtil;
49
50 public final class ParserUtils {
51
52     final public static PhylogenyParser createParserDependingFileContents( final File file,
53                                                                            final boolean phyloxml_validate_against_xsd )
54             throws FileNotFoundException, IOException {
55         PhylogenyParser parser = null;
56         final String first_line = ForesterUtil.getFirstLine( file ).trim().toLowerCase();
57         if ( first_line.startsWith( "<" ) ) {
58             parser = new PhyloXmlParser();
59             if ( phyloxml_validate_against_xsd ) {
60                 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
61                 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
62                 if ( xsd_url != null ) {
63                     ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
64                 }
65                 else {
66                     if ( ForesterConstants.RELEASE ) {
67                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
68                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
69                     }
70                 }
71             }
72         }
73         else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
74                 || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
75             parser = new NexusPhylogeniesParser();
76         }
77         else {
78             parser = new NHXParser();
79         }
80         return parser;
81     }
82
83     final public static PhylogenyParser createParserDependingOnFileType( final File file,
84                                                                          final boolean phyloxml_validate_against_xsd )
85             throws FileNotFoundException, IOException {
86         PhylogenyParser parser = null;
87         parser = ParserUtils.createParserDependingOnSuffix( file.getName(), phyloxml_validate_against_xsd );
88         if ( parser == null ) {
89             parser = createParserDependingFileContents( file, phyloxml_validate_against_xsd );
90         }
91         return parser;
92     }
93
94     /**
95      * Return null if it can not guess the parser to use based on name suffix.
96      * 
97      * @param filename
98      * @return
99      */
100     final public static PhylogenyParser createParserDependingOnSuffix( final String filename,
101                                                                        final boolean phyloxml_validate_against_xsd ) {
102         PhylogenyParser parser = null;
103         final String filename_lc = filename.toLowerCase();
104         if ( filename_lc.endsWith( ".tol" ) || filename_lc.endsWith( ".tolxml" ) || filename_lc.endsWith( ".tol.zip" ) ) {
105             parser = new TolParser();
106         }
107         else if ( filename_lc.endsWith( ".xml" ) || filename_lc.endsWith( ".px" ) || filename_lc.endsWith( "phyloxml" )
108                 || filename_lc.endsWith( ".zip" ) ) {
109             parser = new PhyloXmlParser();
110             if ( phyloxml_validate_against_xsd ) {
111                 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
112                 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
113                 if ( xsd_url != null ) {
114                     ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
115                 }
116                 else {
117                     if ( ForesterConstants.RELEASE ) {
118                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
119                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
120                     }
121                 }
122             }
123         }
124         else if ( filename_lc.endsWith( ".nexus" ) || filename_lc.endsWith( ".nex" ) || filename_lc.endsWith( ".nx" ) ) {
125             parser = new NexusPhylogeniesParser();
126         }
127         else if ( filename_lc.endsWith( ".nhx" ) || filename_lc.endsWith( ".nh" ) || filename_lc.endsWith( ".newick" )
128                 || filename_lc.endsWith( ".nwk" ) ) {
129             parser = new NHXParser();
130         }
131         return parser;
132     }
133
134     final public static PhylogenyParser createParserDependingOnUrlContents( final URL url,
135                                                                             final boolean phyloxml_validate_against_xsd )
136             throws FileNotFoundException, IOException {
137         final String lc_filename = url.getFile().toString().toLowerCase();
138         PhylogenyParser parser = createParserDependingOnSuffix( lc_filename, phyloxml_validate_against_xsd );
139         if ( ( parser != null ) && lc_filename.endsWith( ".zip" ) ) {
140             if ( parser instanceof PhyloXmlParser ) {
141                 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
142             }
143             else if ( parser instanceof TolParser ) {
144                 ( ( TolParser ) parser ).setZippedInputstream( true );
145             }
146         }
147         if ( parser == null ) {
148             final String first_line = ForesterUtil.getFirstLine( url ).trim().toLowerCase();
149             if ( first_line.startsWith( "<" ) ) {
150                 parser = new PhyloXmlParser();
151                 if ( phyloxml_validate_against_xsd ) {
152                     final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
153                     final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
154                     if ( xsd_url != null ) {
155                         ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
156                     }
157                     else {
158                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
159                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
160                     }
161                 }
162             }
163             else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
164                     || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
165                 parser = new NexusPhylogeniesParser();
166             }
167             else {
168                 parser = new NHXParser();
169             }
170         }
171         return parser;
172     }
173
174     public static BufferedReader createReader( final Object source ) throws IOException, FileNotFoundException {
175         BufferedReader reader = null;
176         if ( ( source instanceof File ) || ( source instanceof String ) ) {
177             File f = null;
178             if ( source instanceof File ) {
179                 f = ( File ) source;
180             }
181             else {
182                 f = new File( ( String ) source );
183             }
184             if ( !f.exists() ) {
185                 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
186             }
187             else if ( !f.isFile() ) {
188                 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
189             }
190             else if ( !f.canRead() ) {
191                 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
192             }
193             reader = new BufferedReader( new FileReader( f ) );
194         }
195         else if ( source instanceof InputStream ) {
196             reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
197         }
198         else if ( ( source instanceof StringBuffer ) || ( source instanceof StringBuilder ) ) {
199             reader = new BufferedReader( new StringReader( source.toString() ) );
200         }
201         else {
202             throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
203                     + "] (can only parse objects of type File/String, InputStream, StringBuffer, or StringBuilder)" );
204         }
205         return reader;
206     }
207
208     /**
209      * Extracts a code if and only if:
210      * one and only one _, 
211      * shorter than 25, 
212      * no |, 
213      * no ., 
214      * if / present it has to be after the _, 
215      * if PFAM_STYLE_ONLY: / must be present,
216      * tax code can only contain uppercase letters and numbers,
217      * and must contain at least one uppercase letter.
218      * Return null if no code extractable.
219      * 
220      * @param name
221      * @param limit_to_five
222      * @return
223      */
224     public static String extractTaxonomyCodeFromNodeName( final String name,
225                                                           final boolean limit_to_five,
226                                                           final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction ) {
227         if ( ( name.indexOf( "_" ) > 0 )
228                 && ( name.length() < 31 )
229                 //  && ( name.lastIndexOf( "_" ) == name.indexOf( "_" ) )
230                 && ( name.indexOf( "|" ) < 0 )
231                 && ( name.indexOf( "." ) < 0 )
232                 && ( ( taxonomy_extraction != PhylogenyMethods.TAXONOMY_EXTRACTION.PFAM_STYLE_ONLY ) || ( name
233                         .indexOf( "/" ) >= 0 ) )
234                 && ( ( ( name.indexOf( "/" ) ) < 0 ) || ( name.indexOf( "/" ) > name.indexOf( "_" ) ) ) ) {
235             final String[] s = name.split( "[_/]" );
236             if ( s.length > 1 ) {
237                 String str = s[ 1 ];
238                 if ( ( str.length() < 6 ) || ( !limit_to_five && ( str.length() < 7 ) ) ) {
239                     if ( ( str.length() < 5 ) && ( str.startsWith( "RAT" ) || str.startsWith( "PIG" ) ) ) {
240                         str = str.substring( 0, 3 );
241                     }
242                     final Matcher uc_letters_and_numbers = NHXParser.UC_LETTERS_NUMBERS_PATTERN.matcher( str );
243                     if ( !uc_letters_and_numbers.matches() ) {
244                         return null;
245                     }
246                     final Matcher numbers_only = NHXParser.NUMBERS_ONLY_PATTERN.matcher( str );
247                     if ( numbers_only.matches() ) {
248                         return null;
249                     }
250                     return str;
251                 }
252             }
253         }
254         return null;
255     }
256
257     public final static Phylogeny[] readPhylogenies( final File file ) throws FileNotFoundException, IOException {
258         return PhylogenyMethods.readPhylogenies( ParserUtils.createParserDependingOnFileType( file, true ), file );
259     }
260
261     public final static Phylogeny[] readPhylogenies( final String file_name ) throws FileNotFoundException, IOException {
262         return readPhylogenies( new File( file_name ) );
263     }
264 }