2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
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.
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.
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
23 // Contact: phylosoft @ gmail . com
24 // WWW: www.phylosoft.org/forester
26 package org.forester.io.parsers.phyloxml;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.HashMap;
31 import java.util.List;
34 import org.forester.io.parsers.phyloxml.data.BinaryCharactersParser;
35 import org.forester.io.parsers.phyloxml.data.BranchWidthParser;
36 import org.forester.io.parsers.phyloxml.data.ColorParser;
37 import org.forester.io.parsers.phyloxml.data.ConfidenceParser;
38 import org.forester.io.parsers.phyloxml.data.DateParser;
39 import org.forester.io.parsers.phyloxml.data.DistributionParser;
40 import org.forester.io.parsers.phyloxml.data.EventParser;
41 import org.forester.io.parsers.phyloxml.data.IdentifierParser;
42 import org.forester.io.parsers.phyloxml.data.PropertyParser;
43 import org.forester.io.parsers.phyloxml.data.ReferenceParser;
44 import org.forester.io.parsers.phyloxml.data.SequenceParser;
45 import org.forester.io.parsers.phyloxml.data.SequenceRelationParser;
46 import org.forester.io.parsers.phyloxml.data.TaxonomyParser;
47 import org.forester.io.parsers.util.PhylogenyParserException;
48 import org.forester.phylogeny.Phylogeny;
49 import org.forester.phylogeny.PhylogenyNode;
50 import org.forester.phylogeny.data.BinaryCharacters;
51 import org.forester.phylogeny.data.BranchColor;
52 import org.forester.phylogeny.data.BranchWidth;
53 import org.forester.phylogeny.data.Confidence;
54 import org.forester.phylogeny.data.Date;
55 import org.forester.phylogeny.data.Distribution;
56 import org.forester.phylogeny.data.Event;
57 import org.forester.phylogeny.data.Identifier;
58 import org.forester.phylogeny.data.PhylogenyDataUtil;
59 import org.forester.phylogeny.data.PropertiesMap;
60 import org.forester.phylogeny.data.Property;
61 import org.forester.phylogeny.data.Reference;
62 import org.forester.phylogeny.data.Sequence;
63 import org.forester.phylogeny.data.SequenceRelation;
64 import org.forester.phylogeny.data.SequenceRelation.SEQUENCE_RELATION_TYPE;
65 import org.forester.phylogeny.data.Taxonomy;
66 import org.forester.util.FailedConditionCheckException;
67 import org.forester.util.ForesterConstants;
68 import org.forester.util.ForesterUtil;
69 import org.xml.sax.Attributes;
70 import org.xml.sax.SAXException;
71 import org.xml.sax.helpers.DefaultHandler;
73 public final class PhyloXmlHandler extends DefaultHandler {
75 private static final String PHYLOXML = "phyloxml";
76 private String _current_element_name;
77 private Phylogeny _current_phylogeny;
78 private List<Phylogeny> _phylogenies;
79 private XmlElement _current_xml_element;
80 private PhylogenyNode _current_node;
81 private static Map<Phylogeny, HashMap<String, Sequence>> phylogenySequencesById = new HashMap<Phylogeny, HashMap<String, Sequence>>();
87 private void addNode() {
88 final PhylogenyNode new_node = new PhylogenyNode();
89 getCurrentNode().addAsChild( new_node );
90 setCurrentNode( new_node );
94 public void characters( final char[] chars, final int start_index, final int end_index ) {
95 if ( ( ( getCurrentXmlElement() != null ) && ( getCurrentElementName() != null ) )
96 && !getCurrentElementName().equals( PhyloXmlMapping.CLADE )
97 && !getCurrentElementName().equals( PhyloXmlMapping.PHYLOGENY ) ) {
98 if ( !ForesterUtil.isEmpty( getCurrentXmlElement().getValueAsString() ) ) {
99 getCurrentXmlElement().appendValue( new String( chars, start_index, end_index ) );
102 getCurrentXmlElement().setValue( new String( chars, start_index, end_index ) );
108 public void endElement( final String namespace_uri, final String local_name, final String qualified_name )
109 throws SAXException {
110 if ( ForesterUtil.isEmpty( namespace_uri ) || namespace_uri.startsWith( ForesterConstants.PHYLO_XML_LOCATION ) ) {
111 if ( local_name.equals( PhyloXmlMapping.CLADE ) ) {
113 mapElementToPhylogenyNode( getCurrentXmlElement(), getCurrentNode() );
114 if ( !getCurrentNode().isRoot() ) {
115 setCurrentNode( getCurrentNode().getParent() );
117 getCurrentXmlElement().setValue( null );
118 setCurrentXmlElement( getCurrentXmlElement().getParent() );
120 catch ( final PhylogenyParserException ex ) {
121 throw new SAXException( ex.getMessage() );
124 else if ( local_name.equals( PhyloXmlMapping.SEQUENCE_RELATION ) ) {
126 if ( getCurrentPhylogeny() != null ) {
127 final SequenceRelation seqRelation = ( SequenceRelation ) SequenceRelationParser
128 .getInstance( getCurrentPhylogeny() ).parse( getCurrentXmlElement() );
129 final Map<String, Sequence> sequencesById = getSequenceMapByIdForPhylogeny( getCurrentPhylogeny() );
130 final Sequence ref0 = sequencesById.get( seqRelation.getRef0().getSourceId() ), ref1 = sequencesById
131 .get( seqRelation.getRef1().getSourceId() );
132 if ( ref0 != null ) {
133 // check for reverse relation
134 boolean fFoundReverse = false;
135 for( final SequenceRelation sr : ref0.getSequenceRelations() ) {
136 if ( sr.getType().equals( seqRelation.getType() )
137 && ( ( sr.getRef0().isEqual( ref1 ) && sr.getRef1().isEqual( ref0 ) ) || ( sr
138 .getRef0().isEqual( ref0 ) && sr.getRef1().isEqual( ref1 ) ) ) ) {
139 // in this case we don't need to re-add it, but we make sure we don't loose the confidence value
140 fFoundReverse = true;
141 if ( ( sr.getConfidence() == null ) && ( seqRelation.getConfidence() != null ) ) {
142 sr.setConfidence( seqRelation.getConfidence() );
146 if ( !fFoundReverse ) {
147 ref0.addSequenceRelation( seqRelation );
150 if ( ref1 != null ) {
151 // check for reverse relation
152 boolean fFoundReverse = false;
153 for( final SequenceRelation sr : ref1.getSequenceRelations() ) {
154 if ( sr.getType().equals( seqRelation.getType() )
155 && ( ( sr.getRef0().isEqual( ref1 ) && sr.getRef1().isEqual( ref0 ) ) || ( sr
156 .getRef0().isEqual( ref0 ) && sr.getRef1().isEqual( ref1 ) ) ) ) {
157 // in this case we don't need to re-add it, but we make sure we don't loose the confidence value
158 fFoundReverse = true;
159 if ( ( sr.getConfidence() == null ) && ( seqRelation.getConfidence() != null ) ) {
160 sr.setConfidence( seqRelation.getConfidence() );
164 if ( !fFoundReverse ) {
165 ref1.addSequenceRelation( seqRelation );
168 // we add the type to the current phylogeny so we can know it needs to be displayed in the combo
169 final Collection<SEQUENCE_RELATION_TYPE> relationTypesForCurrentPhylogeny = getCurrentPhylogeny()
170 .getRelevantSequenceRelationTypes();
171 if ( !relationTypesForCurrentPhylogeny.contains( seqRelation.getType() ) ) {
172 relationTypesForCurrentPhylogeny.add( seqRelation.getType() );
176 catch ( final PhylogenyParserException ex ) {
177 throw new SAXException( ex.getMessage() );
180 else if ( local_name.equals( PhyloXmlMapping.PHYLOGENY ) ) {
182 PhyloXmlHandler.mapElementToPhylogeny( getCurrentXmlElement(), getCurrentPhylogeny() );
184 catch ( final PhylogenyParserException ex ) {
185 throw new SAXException( ex.getMessage() );
190 else if ( local_name.equals( PHYLOXML ) ) {
193 else if ( ( getCurrentPhylogeny() != null ) && ( getCurrentXmlElement().getParent() != null ) ) {
194 setCurrentXmlElement( getCurrentXmlElement().getParent() );
196 setCurrentElementName( null );
200 private void finishPhylogeny() throws SAXException {
201 getCurrentPhylogeny().recalculateNumberOfExternalDescendants( false );
202 getPhylogenies().add( getCurrentPhylogeny() );
203 final HashMap<String, Sequence> phyloSequences = phylogenySequencesById.get( getCurrentPhylogeny() );
204 if ( phyloSequences != null ) {
205 getCurrentPhylogeny().setSequenceRelationQueries( phyloSequences.values() );
206 phylogenySequencesById.remove( getCurrentPhylogeny() );
210 private String getCurrentElementName() {
211 return _current_element_name;
214 private PhylogenyNode getCurrentNode() {
215 return _current_node;
218 private Phylogeny getCurrentPhylogeny() {
219 return _current_phylogeny;
222 private XmlElement getCurrentXmlElement() {
223 return _current_xml_element;
226 List<Phylogeny> getPhylogenies() {
230 private void init() {
232 setPhylogenies( new ArrayList<Phylogeny>() );
235 private void initCurrentNode() {
236 if ( getCurrentNode() != null ) {
237 throw new FailedConditionCheckException( "attempt to create new current node when current node already exists" );
239 if ( getCurrentPhylogeny() == null ) {
240 throw new FailedConditionCheckException( "attempt to create new current node for non-existing phylogeny" );
242 final PhylogenyNode node = new PhylogenyNode();
243 getCurrentPhylogeny().setRoot( node );
244 setCurrentNode( getCurrentPhylogeny().getRoot() );
247 private void mapElementToPhylogenyNode( final XmlElement xml_element, final PhylogenyNode node )
248 throws PhylogenyParserException {
249 if ( xml_element.isHasAttribute( PhyloXmlMapping.BRANCH_LENGTH ) ) {
252 d = Double.parseDouble( xml_element.getAttribute( PhyloXmlMapping.BRANCH_LENGTH ) );
254 catch ( final NumberFormatException e ) {
255 throw new PhylogenyParserException( "ill formatted distance in clade attribute ["
256 + xml_element.getAttribute( PhyloXmlMapping.BRANCH_LENGTH ) + "]: " + e.getMessage() );
258 node.setDistanceToParent( d );
260 if ( xml_element.isHasAttribute( PhyloXmlMapping.NODE_COLLAPSE ) ) {
261 final String collapse_str = xml_element.getAttribute( PhyloXmlMapping.NODE_COLLAPSE );
262 if ( !ForesterUtil.isEmpty( collapse_str ) && collapse_str.trim().equalsIgnoreCase( "true" ) ) {
263 node.setCollapse( true );
266 for( int i = 0; i < xml_element.getNumberOfChildElements(); ++i ) {
267 final XmlElement element = xml_element.getChildElement( i );
268 final String qualified_name = element.getQualifiedName();
269 if ( qualified_name.equals( PhyloXmlMapping.BRANCH_LENGTH ) ) {
270 if ( node.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
271 throw new PhylogenyParserException( "ill advised attempt to set distance twice for the same clade (probably via element and via attribute)" );
273 node.setDistanceToParent( element.getValueAsDouble() );
275 if ( qualified_name.equals( PhyloXmlMapping.NODE_NAME ) ) {
276 node.setName( element.getValueAsString() );
278 // else if ( qualified_name.equals( PhyloXmlMapping.NODE_IDENTIFIER ) ) {
279 // node.getNodeData().setNodeIdentifier( ( Identifier ) IdentifierParser.getInstance().parse( element ) );
281 else if ( qualified_name.equals( PhyloXmlMapping.TAXONOMY ) ) {
282 node.getNodeData().addTaxonomy( ( Taxonomy ) TaxonomyParser.getInstance().parse( element ) );
284 else if ( qualified_name.equals( PhyloXmlMapping.SEQUENCE ) ) {
285 final Sequence sequence = ( Sequence ) SequenceParser.getInstance().parse( element );
286 node.getNodeData().addSequence( sequence );
287 // we temporarily store all sequences that have a source ID so we can access them easily when we need to attach relations to them
288 final String sourceId = sequence.getSourceId();
289 if ( ( getCurrentPhylogeny() != null ) && !ForesterUtil.isEmpty( sourceId ) ) {
290 getSequenceMapByIdForPhylogeny( getCurrentPhylogeny() ).put( sourceId, sequence );
293 else if ( qualified_name.equals( PhyloXmlMapping.DISTRIBUTION ) ) {
294 node.getNodeData().addDistribution( ( Distribution ) DistributionParser.getInstance().parse( element ) );
296 else if ( qualified_name.equals( PhyloXmlMapping.CLADE_DATE ) ) {
297 node.getNodeData().setDate( ( Date ) DateParser.getInstance().parse( element ) );
299 else if ( qualified_name.equals( PhyloXmlMapping.REFERENCE ) ) {
300 node.getNodeData().addReference( ( Reference ) ReferenceParser.getInstance().parse( element ) );
302 else if ( qualified_name.equals( PhyloXmlMapping.BINARY_CHARACTERS ) ) {
303 node.getNodeData().setBinaryCharacters( ( BinaryCharacters ) BinaryCharactersParser.getInstance()
306 else if ( qualified_name.equals( PhyloXmlMapping.COLOR ) ) {
307 node.getBranchData().setBranchColor( ( BranchColor ) ColorParser.getInstance().parse( element ) );
309 else if ( qualified_name.equals( PhyloXmlMapping.CONFIDENCE ) ) {
310 node.getBranchData().addConfidence( ( Confidence ) ConfidenceParser.getInstance().parse( element ) );
312 else if ( qualified_name.equals( PhyloXmlMapping.WIDTH ) ) {
313 node.getBranchData().setBranchWidth( ( BranchWidth ) BranchWidthParser.getInstance().parse( element ) );
315 else if ( qualified_name.equals( PhyloXmlMapping.EVENTS ) ) {
316 node.getNodeData().setEvent( ( Event ) EventParser.getInstance().parse( element ) );
318 else if ( qualified_name.equals( PhyloXmlMapping.PROPERTY ) ) {
319 if ( !node.getNodeData().isHasProperties() ) {
320 node.getNodeData().setProperties( new PropertiesMap() );
322 node.getNodeData().getProperties()
323 .addProperty( ( Property ) PropertyParser.getInstance().parse( element ) );
328 private void newClade() {
329 if ( getCurrentNode() == null ) {
337 private void newPhylogeny() {
338 setCurrentPhylogeny( new Phylogeny() );
341 private void reset() {
342 setCurrentPhylogeny( null );
343 setCurrentNode( null );
344 setCurrentElementName( null );
345 setCurrentXmlElement( null );
348 private void setCurrentElementName( final String element_name ) {
349 _current_element_name = element_name;
352 private void setCurrentNode( final PhylogenyNode current_node ) {
353 _current_node = current_node;
356 private void setCurrentPhylogeny( final Phylogeny phylogeny ) {
357 _current_phylogeny = phylogeny;
360 private void setCurrentXmlElement( final XmlElement element ) {
361 _current_xml_element = element;
364 private void setPhylogenies( final List<Phylogeny> phylogenies ) {
365 _phylogenies = phylogenies;
369 public void startDocument() throws SAXException {
374 public void startElement( final String namespace_uri,
375 final String local_name,
376 final String qualified_name,
377 final Attributes attributes ) throws SAXException {
378 if ( ForesterUtil.isEmpty( namespace_uri ) || namespace_uri.startsWith( ForesterConstants.PHYLO_XML_LOCATION ) ) {
379 setCurrentElementName( local_name );
380 if ( local_name.equals( PhyloXmlMapping.CLADE ) ) {
381 final XmlElement element = new XmlElement( namespace_uri, local_name, local_name, attributes );
382 getCurrentXmlElement().addChildElement( element );
383 setCurrentXmlElement( element );
386 else if ( local_name.equals( PhyloXmlMapping.PHYLOGENY ) ) {
387 setCurrentXmlElement( new XmlElement( "", "", "", null ) );
389 final XmlElement element = new XmlElement( namespace_uri, local_name, local_name, attributes );
390 if ( element.isHasAttribute( PhyloXmlMapping.PHYLOGENY_IS_REROOTABLE_ATTR ) ) {
391 getCurrentPhylogeny().setRerootable( Boolean.parseBoolean( element
392 .getAttribute( PhyloXmlMapping.PHYLOGENY_IS_REROOTABLE_ATTR ) ) );
394 if ( element.isHasAttribute( PhyloXmlMapping.PHYLOGENY_BRANCHLENGTH_UNIT_ATTR ) ) {
395 getCurrentPhylogeny()
396 .setDistanceUnit( element.getAttribute( PhyloXmlMapping.PHYLOGENY_BRANCHLENGTH_UNIT_ATTR ) );
398 if ( element.isHasAttribute( PhyloXmlMapping.PHYLOGENY_IS_ROOTED_ATTR ) ) {
399 getCurrentPhylogeny().setRooted( Boolean.parseBoolean( element
400 .getAttribute( PhyloXmlMapping.PHYLOGENY_IS_ROOTED_ATTR ) ) );
402 if ( element.isHasAttribute( PhyloXmlMapping.PHYLOGENY_TYPE_ATTR ) ) {
403 getCurrentPhylogeny().setType( ( element.getAttribute( PhyloXmlMapping.PHYLOGENY_TYPE_ATTR ) ) );
406 else if ( local_name.equals( PHYLOXML ) ) {
408 else if ( getCurrentPhylogeny() != null ) {
409 final XmlElement element = new XmlElement( namespace_uri, local_name, local_name, attributes );
410 getCurrentXmlElement().addChildElement( element );
411 setCurrentXmlElement( element );
416 public static boolean attributeEqualsValue( final XmlElement element,
417 final String attributeName,
418 final String attributeValue ) {
419 final String attr = element.getAttribute( attributeName );
420 return ( ( attr != null ) && attr.equals( attributeValue ) );
423 public static String getAtttributeValue( final XmlElement element, final String attributeName ) {
424 final String attr = element.getAttribute( attributeName );
425 if ( attr != null ) {
433 static public Map<String, Sequence> getSequenceMapByIdForPhylogeny( final Phylogeny ph ) {
434 HashMap<String, Sequence> seqMap = phylogenySequencesById.get( ph );
435 if ( seqMap == null ) {
436 seqMap = new HashMap<String, Sequence>();
437 phylogenySequencesById.put( ph, seqMap );
442 private static void mapElementToPhylogeny( final XmlElement xml_element, final Phylogeny phylogeny )
443 throws PhylogenyParserException {
444 for( int i = 0; i < xml_element.getNumberOfChildElements(); ++i ) {
445 final XmlElement element = xml_element.getChildElement( i );
446 final String qualified_name = element.getQualifiedName();
447 if ( qualified_name.equals( PhyloXmlMapping.PHYLOGENY_NAME ) ) {
448 phylogeny.setName( element.getValueAsString() );
450 else if ( qualified_name.equals( PhyloXmlMapping.PHYLOGENY_DESCRIPTION ) ) {
451 phylogeny.setDescription( element.getValueAsString() );
453 else if ( qualified_name.equals( PhyloXmlMapping.IDENTIFIER ) ) {
454 phylogeny.setIdentifier( ( Identifier ) IdentifierParser.getInstance().parse( element ) );
456 else if ( qualified_name.equals( PhyloXmlMapping.CONFIDENCE ) ) {
457 phylogeny.setConfidence( ( Confidence ) ConfidenceParser.getInstance().parse( element ) );