"rio" work
[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 import java.util.regex.Pattern;
40
41 import org.forester.io.parsers.PhylogenyParser;
42 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
43 import org.forester.io.parsers.nhx.NHXParser;
44 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
45 import org.forester.io.parsers.phyloxml.PhyloXmlParser;
46 import org.forester.io.parsers.tol.TolParser;
47 import org.forester.phylogeny.Phylogeny;
48 import org.forester.phylogeny.PhylogenyMethods;
49 import org.forester.util.ForesterConstants;
50 import org.forester.util.ForesterUtil;
51
52 public final class ParserUtils {
53
54     final private static Pattern TAXOMONY_CODE_PATTERN_1  = Pattern.compile( "[A-Z0-9]{5}|RAT|PIG|PEA|CAP" );
55     final private static Pattern TAXOMONY_CODE_PATTERN_2  = Pattern
56                                                                   .compile( "([A-Z0-9]{5}|RAT|PIG|PEA|CAP)[^A-Za-z].*" );
57     final private static Pattern TAXOMONY_CODE_PATTERN_PF = Pattern.compile( "([A-Z0-9]{5}|RAT|PIG|PEA|CAP)/\\d+-\\d+" );
58
59     final public static PhylogenyParser createParserDependingFileContents( final File file,
60                                                                            final boolean phyloxml_validate_against_xsd )
61             throws FileNotFoundException, IOException {
62         PhylogenyParser parser = null;
63         final String first_line = ForesterUtil.getFirstLine( file ).trim().toLowerCase();
64         if ( first_line.startsWith( "<" ) ) {
65             parser = new PhyloXmlParser();
66             if ( phyloxml_validate_against_xsd ) {
67                 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
68                 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
69                 if ( xsd_url != null ) {
70                     ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
71                 }
72                 else {
73                     if ( ForesterConstants.RELEASE ) {
74                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
75                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
76                     }
77                 }
78             }
79         }
80         else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
81                 || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
82             parser = new NexusPhylogeniesParser();
83         }
84         else {
85             parser = new NHXParser();
86         }
87         return parser;
88     }
89
90     final public static PhylogenyParser createParserDependingOnFileType( final File file,
91                                                                          final boolean phyloxml_validate_against_xsd )
92             throws FileNotFoundException, IOException {
93         PhylogenyParser parser = null;
94         parser = ParserUtils.createParserDependingOnSuffix( file.getName(), phyloxml_validate_against_xsd );
95         if ( parser == null ) {
96             parser = createParserDependingFileContents( file, phyloxml_validate_against_xsd );
97         }
98         return parser;
99     }
100
101     /**
102      * Return null if it can not guess the parser to use based on name suffix.
103      * 
104      * @param filename
105      * @return
106      */
107     final public static PhylogenyParser createParserDependingOnSuffix( final String filename,
108                                                                        final boolean phyloxml_validate_against_xsd ) {
109         PhylogenyParser parser = null;
110         final String filename_lc = filename.toLowerCase();
111         if ( filename_lc.endsWith( ".tol" ) || filename_lc.endsWith( ".tolxml" ) || filename_lc.endsWith( ".tol.zip" ) ) {
112             parser = new TolParser();
113         }
114         else if ( filename_lc.endsWith( ".xml" ) || filename_lc.endsWith( ".px" ) || filename_lc.endsWith( "phyloxml" )
115                 || filename_lc.endsWith( ".zip" ) ) {
116             parser = new PhyloXmlParser();
117             if ( phyloxml_validate_against_xsd ) {
118                 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
119                 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
120                 if ( xsd_url != null ) {
121                     ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
122                 }
123                 else {
124                     if ( ForesterConstants.RELEASE ) {
125                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
126                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
127                     }
128                 }
129             }
130         }
131         else if ( filename_lc.endsWith( ".nexus" ) || filename_lc.endsWith( ".nex" ) || filename_lc.endsWith( ".nx" ) ) {
132             parser = new NexusPhylogeniesParser();
133         }
134         else if ( filename_lc.endsWith( ".nhx" ) || filename_lc.endsWith( ".nh" ) || filename_lc.endsWith( ".newick" )
135                 || filename_lc.endsWith( ".nwk" ) ) {
136             parser = new NHXParser();
137         }
138         return parser;
139     }
140
141     final public static PhylogenyParser createParserDependingOnUrlContents( final URL url,
142                                                                             final boolean phyloxml_validate_against_xsd )
143             throws FileNotFoundException, IOException {
144         final String lc_filename = url.getFile().toString().toLowerCase();
145         PhylogenyParser parser = createParserDependingOnSuffix( lc_filename, phyloxml_validate_against_xsd );
146         if ( ( parser != null ) && lc_filename.endsWith( ".zip" ) ) {
147             if ( parser instanceof PhyloXmlParser ) {
148                 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
149             }
150             else if ( parser instanceof TolParser ) {
151                 ( ( TolParser ) parser ).setZippedInputstream( true );
152             }
153         }
154         if ( parser == null ) {
155             final String first_line = ForesterUtil.getFirstLine( url ).trim().toLowerCase();
156             if ( first_line.startsWith( "<" ) ) {
157                 parser = new PhyloXmlParser();
158                 if ( phyloxml_validate_against_xsd ) {
159                     final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
160                     final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
161                     if ( xsd_url != null ) {
162                         ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
163                     }
164                     else {
165                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
166                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
167                     }
168                 }
169             }
170             else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
171                     || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
172                 parser = new NexusPhylogeniesParser();
173             }
174             else {
175                 parser = new NHXParser();
176             }
177         }
178         return parser;
179     }
180
181     public static BufferedReader createReader( final Object source ) throws IOException, FileNotFoundException {
182         BufferedReader reader = null;
183         if ( ( source instanceof File ) || ( source instanceof String ) ) {
184             File f = null;
185             if ( source instanceof File ) {
186                 f = ( File ) source;
187             }
188             else {
189                 f = new File( ( String ) source );
190             }
191             if ( !f.exists() ) {
192                 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
193             }
194             else if ( !f.isFile() ) {
195                 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
196             }
197             else if ( !f.canRead() ) {
198                 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
199             }
200             reader = new BufferedReader( new FileReader( f ) );
201         }
202         else if ( source instanceof InputStream ) {
203             reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
204         }
205         else if ( ( source instanceof StringBuffer ) || ( source instanceof StringBuilder ) ) {
206             reader = new BufferedReader( new StringReader( source.toString() ) );
207         }
208         else {
209             throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
210                     + "] (can only parse objects of type File/String, InputStream, StringBuffer, or StringBuilder)" );
211         }
212         return reader;
213     }
214
215     public final static String extractTaxonomyCodeFromNodeName( final String name,
216                                                                 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
217         if ( ( name.indexOf( "_" ) > 0 )
218                 && ( ( taxonomy_extraction != TAXONOMY_EXTRACTION.PFAM_STYLE_ONLY ) || ( name.indexOf( "/" ) > 4 ) ) ) {
219             final String[] s = name.split( "[_\\s]" );
220             if ( s.length > 1 ) {
221                 final String str = s[ 1 ];
222                 if ( !ForesterUtil.isEmpty( str ) ) {
223                     if ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_ONLY ) {
224                         final Matcher m = TAXOMONY_CODE_PATTERN_PF.matcher( str );
225                         if ( m.matches() ) {
226                             return m.group( 1 );
227                         }
228                     }
229                     else {
230                         final Matcher m1 = TAXOMONY_CODE_PATTERN_1.matcher( str );
231                         if ( m1.matches() ) {
232                             return m1.group();
233                         }
234                         final Matcher m2 = TAXOMONY_CODE_PATTERN_2.matcher( str );
235                         if ( m2.matches() ) {
236                             return m2.group( 1 );
237                         }
238                     }
239                 }
240             }
241         }
242         else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.YES ) {
243             final Matcher m1 = TAXOMONY_CODE_PATTERN_1.matcher( name );
244             if ( m1.matches() ) {
245                 return name;
246             }
247         }
248         return null;
249     }
250
251     public final static Phylogeny[] readPhylogenies( final File file ) throws FileNotFoundException, IOException {
252         return PhylogenyMethods.readPhylogenies( ParserUtils.createParserDependingOnFileType( file, true ), file );
253     }
254
255     public final static Phylogeny[] readPhylogenies( final String file_name ) throws FileNotFoundException, IOException {
256         return readPhylogenies( new File( file_name ) );
257     }
258 }