phylotastic hackathon at NESCENT 120608
[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" ) || filename_lc.endsWith( ".nwk" ) ) {
128             parser = new NHXParser();
129         }
130         return parser;
131     }
132
133     final public static PhylogenyParser createParserDependingOnUrlContents( final URL url,
134                                                                             final boolean phyloxml_validate_against_xsd )
135             throws FileNotFoundException, IOException {
136         final String lc_filename = url.getFile().toString().toLowerCase();
137         PhylogenyParser parser = createParserDependingOnSuffix( lc_filename, phyloxml_validate_against_xsd );
138         if ( ( parser != null ) && lc_filename.endsWith( ".zip" ) ) {
139             if ( parser instanceof PhyloXmlParser ) {
140                 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
141             }
142             else if ( parser instanceof TolParser ) {
143                 ( ( TolParser ) parser ).setZippedInputstream( true );
144             }
145         }
146         if ( parser == null ) {
147             final String first_line = ForesterUtil.getFirstLine( url ).trim().toLowerCase();
148             if ( first_line.startsWith( "<" ) ) {
149                 parser = new PhyloXmlParser();
150                 if ( phyloxml_validate_against_xsd ) {
151                     final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
152                     final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
153                     if ( xsd_url != null ) {
154                         ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
155                     }
156                     else {
157                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
158                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
159                     }
160                 }
161             }
162             else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
163                     || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
164                 parser = new NexusPhylogeniesParser();
165             }
166             else {
167                 parser = new NHXParser();
168             }
169         }
170         return parser;
171     }
172
173     public static BufferedReader createReader( final Object source ) throws IOException, FileNotFoundException {
174         BufferedReader reader = null;
175         if ( ( source instanceof File ) || ( source instanceof String ) ) {
176             File f = null;
177             if ( source instanceof File ) {
178                 f = ( File ) source;
179             }
180             else {
181                 f = new File( ( String ) source );
182             }
183             if ( !f.exists() ) {
184                 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
185             }
186             else if ( !f.isFile() ) {
187                 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
188             }
189             else if ( !f.canRead() ) {
190                 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
191             }
192             reader = new BufferedReader( new FileReader( f ) );
193         }
194         else if ( source instanceof InputStream ) {
195             reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
196         }
197         else if ( ( source instanceof StringBuffer ) || ( source instanceof StringBuilder ) ) {
198             reader = new BufferedReader( new StringReader( source.toString() ) );
199         }
200         else {
201             throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
202                     + "] (can only parse objects of type File/String, InputStream, StringBuffer, or StringBuilder)" );
203         }
204         return reader;
205     }
206
207     /**
208      * Extracts a code if and only if:
209      * one and only one _, 
210      * shorter than 25, 
211      * no |, 
212      * no ., 
213      * if / present it has to be after the _, 
214      * if PFAM_STYLE_ONLY: / must be present,
215      * tax code can only contain uppercase letters and numbers,
216      * and must contain at least one uppercase letter.
217      * Return null if no code extractable.
218      * 
219      * @param name
220      * @param limit_to_five
221      * @return
222      */
223     public static String extractTaxonomyCodeFromNodeName( final String name,
224                                                           final boolean limit_to_five,
225                                                           final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction ) {
226         if ( ( name.indexOf( "_" ) > 0 )
227                 && ( name.length() < 31 )
228                 //  && ( name.lastIndexOf( "_" ) == name.indexOf( "_" ) )
229                 && ( name.indexOf( "|" ) < 0 )
230                 && ( name.indexOf( "." ) < 0 )
231                 && ( ( taxonomy_extraction != PhylogenyMethods.TAXONOMY_EXTRACTION.PFAM_STYLE_ONLY ) || ( name
232                         .indexOf( "/" ) >= 0 ) )
233                 && ( ( ( name.indexOf( "/" ) ) < 0 ) || ( name.indexOf( "/" ) > name.indexOf( "_" ) ) ) ) {
234             final String[] s = name.split( "[_/]" );
235             if ( s.length > 1 ) {
236                 String str = s[ 1 ];
237                 if ( ( str.length() < 6 ) || ( !limit_to_five && ( str.length() < 7 ) ) ) {
238                     if ( ( str.length() < 5 ) && ( str.startsWith( "RAT" ) || str.startsWith( "PIG" ) ) ) {
239                         str = str.substring( 0, 3 );
240                     }
241                     final Matcher uc_letters_and_numbers = NHXParser.UC_LETTERS_NUMBERS_PATTERN.matcher( str );
242                     if ( !uc_letters_and_numbers.matches() ) {
243                         return null;
244                     }
245                     final Matcher numbers_only = NHXParser.NUMBERS_ONLY_PATTERN.matcher( str );
246                     if ( numbers_only.matches() ) {
247                         return null;
248                     }
249                     return str;
250                 }
251             }
252         }
253         return null;
254     }
255
256     public final static Phylogeny[] readPhylogenies( final File file ) throws FileNotFoundException, IOException {
257         return PhylogenyMethods.readPhylogenies( ParserUtils.createParserDependingOnFileType( file, true ), file );
258     }
259
260     public final static Phylogeny[] readPhylogenies( final String file_name ) throws FileNotFoundException, IOException {
261         return readPhylogenies( new File( file_name ) );
262     }
263 }