(no commit message)
[jalview.git] / forester / java / src / org / forester / io / parsers / tol / TolParser.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
7 // All rights reserved
8 //
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
13 //
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
18 //
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 //
23 // Contact: phylosoft @ gmail . com
24 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
25
26 package org.forester.io.parsers.tol;
27
28 import java.io.File;
29 import java.io.FileReader;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.InputStreamReader;
33 import java.io.Reader;
34 import java.io.StringReader;
35 import java.util.Enumeration;
36 import java.util.zip.ZipEntry;
37 import java.util.zip.ZipFile;
38 import java.util.zip.ZipInputStream;
39
40 import javax.xml.parsers.ParserConfigurationException;
41 import javax.xml.parsers.SAXParser;
42 import javax.xml.parsers.SAXParserFactory;
43
44 import org.forester.io.parsers.PhylogenyParser;
45 import org.forester.io.parsers.util.PhylogenyParserException;
46 import org.forester.phylogeny.Phylogeny;
47 import org.forester.util.ForesterUtil;
48 import org.xml.sax.InputSource;
49 import org.xml.sax.SAXException;
50 import org.xml.sax.SAXNotRecognizedException;
51 import org.xml.sax.SAXNotSupportedException;
52 import org.xml.sax.SAXParseException;
53 import org.xml.sax.XMLReader;
54 import org.xml.sax.helpers.DefaultHandler;
55
56 public class TolParser implements PhylogenyParser {
57
58     final public static String JAXP_SCHEMA_LANGUAGE                       = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
59     final public static String W3C_XML_SCHEMA                             = "http://www.w3.org/2001/XMLSchema";
60     final public static String JAXP_SCHEMA_SOURCE                         = "http://java.sun.com/xml/jaxp/properties/schemaSource";
61     final public static String SAX_FEATURES_VALIDATION                    = "http://xml.org/sax/features/validation";
62     final public static String APACHE_FEATURES_VALIDATION_SCHEMA          = "http://apache.org/xml/features/validation/schema";
63     final public static String APACHE_FEATURES_VALIDATION_SCHEMA_FULL     = "http://apache.org/xml/features/validation/schema-full-checking";
64     final public static String APACHE_PROPERTIES_SCHEMA_EXTERNAL_LOCATION = "http://apache.org/xml/properties/schema/external-schemaLocation";
65     private Object             _source;
66     private boolean            _valid;
67     private boolean            _zipped_inputstream;
68     private int                _error_count;
69     private int                _warning_count;
70     private String             _schema_location;
71     private StringBuffer       _error_messages;
72     private StringBuffer       _warning_messages;
73
74     public TolParser() {
75         init();
76         reset();
77     }
78
79     public int getErrorCount() {
80         return _error_count;
81     }
82
83     public StringBuffer getErrorMessages() {
84         return _error_messages;
85     }
86
87     private Reader getReaderFromZipFile() throws IOException {
88         Reader reader = null;
89         final ZipFile zip_file = new ZipFile( getSource().toString() );
90         final Enumeration<?> zip_file_entries = zip_file.entries();
91         while ( zip_file_entries.hasMoreElements() ) {
92             final ZipEntry zip_file_entry = ( ZipEntry ) zip_file_entries.nextElement();
93             if ( !zip_file_entry.isDirectory() && ( zip_file_entry.getSize() > 0 ) ) {
94                 final InputStream is = zip_file.getInputStream( zip_file_entry );
95                 reader = new InputStreamReader( is );
96                 break;
97             }
98         }
99         return reader;
100     }
101
102     private String getSchemaLocation() {
103         return _schema_location;
104     }
105
106     private Object getSource() {
107         return _source;
108     }
109
110     public int getWarningCount() {
111         return _warning_count;
112     }
113
114     public StringBuffer getWarningMessages() {
115         return _warning_messages;
116     }
117
118     private void init() {
119         setZippedInputstream( false );
120     }
121
122     public boolean isValid() {
123         return _valid;
124     }
125
126     private boolean isZippedInputstream() {
127         return _zipped_inputstream;
128     }
129
130     @Override
131     public Phylogeny[] parse() throws IOException, PhylogenyParserException {
132         reset();
133         final TolXmlHandler handler = new TolXmlHandler();
134         final SAXParserFactory factory = SAXParserFactory.newInstance();
135         factory.setNamespaceAware( true );
136         try {
137             if ( !ForesterUtil.isEmpty( getSchemaLocation() ) ) {
138                 factory.setFeature( SAX_FEATURES_VALIDATION, true );
139                 factory.setFeature( APACHE_FEATURES_VALIDATION_SCHEMA, true );
140                 factory.setFeature( APACHE_FEATURES_VALIDATION_SCHEMA_FULL, true );
141             }
142         }
143         catch ( final SAXNotRecognizedException e ) {
144             e.printStackTrace();
145             throw new PhylogenyParserException( "sax not recognized exception: " + e.getMessage() );
146         }
147         catch ( final SAXNotSupportedException e ) {
148             e.printStackTrace();
149             throw new PhylogenyParserException( "sax not supported exception: " + e.getMessage() );
150         }
151         catch ( final ParserConfigurationException e ) {
152             e.printStackTrace();
153             throw new PhylogenyParserException( "parser _configuration exception: " + e.getMessage() );
154         }
155         catch ( final Exception e ) {
156             e.printStackTrace();
157             throw new PhylogenyParserException( "error while configuring sax parser: " + e.getMessage() );
158         }
159         try {
160             final SAXParser parser = factory.newSAXParser();
161             if ( !ForesterUtil.isEmpty( getSchemaLocation() ) ) {
162                 parser.setProperty( JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA );
163                 parser.setProperty( JAXP_SCHEMA_SOURCE, getSchemaLocation() );
164                 parser.setProperty( APACHE_PROPERTIES_SCHEMA_EXTERNAL_LOCATION, getSchemaLocation() );
165             }
166             final XMLReader xml_reader = parser.getXMLReader();
167             xml_reader.setContentHandler( handler );
168             xml_reader.setErrorHandler( new TolParserErrorHandler() );
169             if ( getSource() instanceof File ) {
170                 if ( !getSource().toString().toLowerCase().endsWith( ".zip" ) ) {
171                     xml_reader.parse( new InputSource( new FileReader( ( File ) getSource() ) ) );
172                 }
173                 else {
174                     final Reader reader = getReaderFromZipFile();
175                     if ( reader == null ) {
176                         throw new PhylogenyParserException( "Zip file \"" + getSource()
177                                                             + "\" appears not to contain any entries" );
178                     }
179                     xml_reader.parse( new InputSource( reader ) );
180                 }
181             }
182             else if ( getSource() instanceof InputSource ) {
183                 xml_reader.parse( ( InputSource ) getSource() );
184             }
185             else if ( getSource() instanceof InputStream ) {
186                 if ( !isZippedInputstream() ) {
187                     final InputStream is = ( InputStream ) getSource();
188                     final Reader reader = new InputStreamReader( is );
189                     xml_reader.parse( new InputSource( reader ) );
190                 }
191                 else {
192                     final ZipInputStream zip_is = new ZipInputStream( ( InputStream ) getSource() );
193                     zip_is.getNextEntry();
194                     final Reader reader = new InputStreamReader( zip_is );
195                     if ( reader == null ) {
196                         throw new PhylogenyParserException( "Zip input stream \"" + getSource()
197                                                             + "\" appears not to contain any data" );
198                     }
199                     xml_reader.parse( new InputSource( reader ) );
200                 }
201             }
202             else if ( getSource() instanceof String ) {
203                 final File file = new File( getSource().toString() );
204                 final Reader reader = new FileReader( file );
205                 xml_reader.parse( new InputSource( reader ) );
206             }
207             else if ( getSource() instanceof StringBuffer ) {
208                 final StringReader string_reader = new StringReader( getSource().toString() );
209                 xml_reader.parse( new InputSource( string_reader ) );
210             }
211             else {
212                 throw new PhylogenyParserException( "attempt to parse object of unsupported type: \""
213                         + getSource().getClass() + "\"" );
214             }
215         }
216         catch ( final SAXException sax_exception ) {
217             throw new PhylogenyParserException( "Failed to parse [" + getSource() + "]: " + sax_exception.getMessage() );
218         }
219         catch ( final ParserConfigurationException parser_config_exception ) {
220             throw new PhylogenyParserException( "Failed to parse [" + getSource()
221                                                 + "] Problem with xml parser _configuration: " + parser_config_exception.getMessage() );
222         }
223         catch ( final IOException e ) {
224             throw new PhylogenyParserException( "Problem with input source [" + getSource() + "]: \n" + e.getMessage() );
225         }
226         catch ( final Exception e ) {
227             e.printStackTrace();
228             throw new PhylogenyParserException( "Failed to parse [" + getSource() + "]: " + e.getMessage() );
229         }
230         catch ( final Error err ) {
231             err.printStackTrace();
232             throw new PhylogenyParserException( "Severe error: " + err.getMessage() );
233         }
234         final Phylogeny[] ps = new Phylogeny[ handler.getPhylogenies().size() ];
235         int i = 0;
236         for( final Phylogeny phylogeny : handler.getPhylogenies() ) {
237             ps[ i++ ] = phylogeny;
238         }
239         return ps;
240     }
241
242     private void reset() {
243         _valid = true;
244         _error_count = 0;
245         _warning_count = 0;
246         _error_messages = new StringBuffer();
247         _warning_messages = new StringBuffer();
248     }
249
250     @Override
251     public void setSource( final Object source ) {
252         _source = source;
253     }
254
255     public void setValidateAgainstSchema( final String schema_location ) {
256         _schema_location = schema_location;
257     }
258
259     public void setZippedInputstream( final boolean zipped_inputstream ) {
260         _zipped_inputstream = zipped_inputstream;
261     }
262
263     private class TolParserErrorHandler extends DefaultHandler {
264
265         @Override
266         public void error( final SAXParseException e ) {
267             ++_error_count;
268             _valid = false;
269             throw new RuntimeException( "XML error at line " + e.getLineNumber() + ": \n" + e.getMessage() );
270         }
271
272         @Override
273         public void fatalError( final SAXParseException e ) {
274             ++_error_count;
275             _valid = false;
276             throw new RuntimeException( "Fatal XML error at line " + e.getLineNumber() + ": \n" + e.getMessage() );
277         }
278
279         @Override
280         public void warning( final SAXParseException e ) {
281             ++_warning_count;
282             if ( _error_messages.length() > 1 ) {
283                 _error_messages.append( ForesterUtil.LINE_SEPARATOR );
284             }
285             _warning_messages.append( "[line: " + e.getLineNumber() + "] " + e.getMessage() );
286         }
287     }
288
289     @Override
290     public String getName() {
291         return "ToL Parser";
292     }
293 }