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