b8dd42e7dd97cfe539bf8aa34416e80198d20226
[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.PhylogenyMethods;
46 import org.forester.util.ForesterConstants;
47 import org.forester.util.ForesterUtil;
48
49 public final class ParserUtils {
50
51     final public static PhylogenyParser createParserDependingOnUrlContents( final URL url,
52                                                                             final boolean phyloxml_validate_against_xsd )
53             throws FileNotFoundException, IOException {
54         final String lc_filename = url.getFile().toString().toLowerCase();
55         PhylogenyParser parser = createParserDependingOnSuffix( lc_filename, phyloxml_validate_against_xsd );
56         if ( ( parser != null ) && lc_filename.endsWith( ".zip" ) ) {
57             if ( parser instanceof PhyloXmlParser ) {
58                 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
59             }
60             else if ( parser instanceof TolParser ) {
61                 ( ( TolParser ) parser ).setZippedInputstream( true );
62             }
63         }
64         if ( parser == null ) {
65             final String first_line = ForesterUtil.getFirstLine( url ).trim().toLowerCase();
66             if ( first_line.startsWith( "<" ) ) {
67                 parser = new PhyloXmlParser();
68                 if ( phyloxml_validate_against_xsd ) {
69                     final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
70                     final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
71                     if ( xsd_url != null ) {
72                         ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
73                     }
74                     else {
75                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
76                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
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         }
88         return parser;
89     }
90
91     /**
92      * Return null if it can not guess the parser to use based on name suffix.
93      * 
94      * @param filename
95      * @return
96      */
97     final public static PhylogenyParser createParserDependingOnSuffix( final String filename,
98                                                                        final boolean phyloxml_validate_against_xsd ) {
99         PhylogenyParser parser = null;
100         final String filename_lc = filename.toLowerCase();
101         if ( filename_lc.endsWith( ".tol" ) || filename_lc.endsWith( ".tolxml" ) || filename_lc.endsWith( ".tol.zip" ) ) {
102             parser = new TolParser();
103         }
104         else if ( filename_lc.endsWith( ".xml" ) || filename_lc.endsWith( ".px" ) || filename_lc.endsWith( "phyloxml" )
105                 || filename_lc.endsWith( ".zip" ) ) {
106             parser = new PhyloXmlParser();
107             if ( phyloxml_validate_against_xsd ) {
108                 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
109                 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
110                 if ( xsd_url != null ) {
111                     ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
112                 }
113                 else {
114                     if ( ForesterConstants.RELEASE ) {
115                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
116                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
117                     }
118                 }
119             }
120         }
121         else if ( filename_lc.endsWith( ".nexus" ) || filename_lc.endsWith( ".nex" ) || filename_lc.endsWith( ".nx" ) ) {
122             parser = new NexusPhylogeniesParser();
123         }
124         else if ( filename_lc.endsWith( ".nhx" ) || filename_lc.endsWith( ".nh" ) || filename_lc.endsWith( ".newick" ) ) {
125             parser = new NHXParser();
126         }
127         return parser;
128     }
129
130     final public static PhylogenyParser createParserDependingOnFileType( final File file,
131                                                                          final boolean phyloxml_validate_against_xsd )
132             throws FileNotFoundException, IOException {
133         PhylogenyParser parser = null;
134         parser = ParserUtils.createParserDependingOnSuffix( file.getName(), phyloxml_validate_against_xsd );
135         if ( parser == null ) {
136             parser = createParserDependingFileContents( file, phyloxml_validate_against_xsd );
137         }
138         return parser;
139     }
140
141     final public static PhylogenyParser createParserDependingFileContents( final File file,
142                                                                            final boolean phyloxml_validate_against_xsd )
143             throws FileNotFoundException, IOException {
144         PhylogenyParser parser = null;
145         final String first_line = ForesterUtil.getFirstLine( file ).trim().toLowerCase();
146         if ( first_line.startsWith( "<" ) ) {
147             parser = new PhyloXmlParser();
148             if ( phyloxml_validate_against_xsd ) {
149                 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
150                 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
151                 if ( xsd_url != null ) {
152                     ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
153                 }
154                 else {
155                     if ( ForesterConstants.RELEASE ) {
156                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
157                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
158                     }
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         return parser;
170     }
171
172     /**
173      * Extracts a code if and only if:
174      * one and only one _, 
175      * shorter than 25, 
176      * no |, 
177      * no ., 
178      * if / present it has to be after the _, 
179      * if PFAM_STYLE_ONLY: / must be present,
180      * tax code can only contain uppercase letters and numbers,
181      * and must contain at least one uppercase letter.
182      * Return null if no code extractable.
183      * 
184      * @param name
185      * @param limit_to_five
186      * @return
187      */
188     public static String extractTaxonomyCodeFromNodeName( final String name,
189                                                           final boolean limit_to_five,
190                                                           final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction ) {
191         if ( ( name.indexOf( "_" ) > 0 )
192                 && ( name.length() < 25 )
193                 && ( name.lastIndexOf( "_" ) == name.indexOf( "_" ) )
194                 && ( name.indexOf( "|" ) < 0 )
195                 && ( name.indexOf( "." ) < 0 )
196                 && ( ( taxonomy_extraction != PhylogenyMethods.TAXONOMY_EXTRACTION.PFAM_STYLE_ONLY ) || ( name
197                         .indexOf( "/" ) >= 0 ) )
198                 && ( ( ( name.indexOf( "/" ) ) < 0 ) || ( name.indexOf( "/" ) > name.indexOf( "_" ) ) ) ) {
199             final String[] s = name.split( "[_/]" );
200             if ( s.length > 1 ) {
201                 String str = s[ 1 ];
202                 if ( limit_to_five ) {
203                     if ( str.length() > 5 ) {
204                         str = str.substring( 0, 5 );
205                     }
206                     else if ( ( str.length() < 5 ) && ( str.startsWith( "RAT" ) || str.startsWith( "PIG" ) ) ) {
207                         str = str.substring( 0, 3 );
208                     }
209                 }
210                 final Matcher letters_and_numbers = NHXParser.UC_LETTERS_NUMBERS_PATTERN.matcher( str );
211                 if ( !letters_and_numbers.matches() ) {
212                     return null;
213                 }
214                 final Matcher numbers_only = NHXParser.NUMBERS_ONLY_PATTERN.matcher( str );
215                 if ( numbers_only.matches() ) {
216                     return null;
217                 }
218                 return str;
219             }
220         }
221         return null;
222     }
223
224     public static BufferedReader createReader( final Object source ) throws IOException, FileNotFoundException {
225         BufferedReader reader = null;
226         if ( ( source instanceof File ) || ( source instanceof String ) ) {
227             File f = null;
228             if ( source instanceof File ) {
229                 f = ( File ) source;
230             }
231             else {
232                 f = new File( ( String ) source );
233             }
234             if ( !f.exists() ) {
235                 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
236             }
237             else if ( !f.isFile() ) {
238                 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
239             }
240             else if ( !f.canRead() ) {
241                 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
242             }
243             reader = new BufferedReader( new FileReader( f ) );
244         }
245         else if ( source instanceof InputStream ) {
246             reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
247         }
248         else if ( ( source instanceof StringBuffer ) || ( source instanceof StringBuilder ) ) {
249             reader = new BufferedReader( new StringReader( source.toString() ) );
250         }
251         else {
252             throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
253                     + "] (can only parse objects of type File/String, InputStream, StringBuffer, or StringBuilder)" );
254         }
255         return reader;
256     }
257 }