taxonomy extraction changed
[jalview.git] / forester / java / src / org / forester / archaeopteryx / UrlTreeReader.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.archaeopteryx;
27
28 import java.io.File;
29 import java.io.IOException;
30 import java.net.MalformedURLException;
31 import java.net.URL;
32 import java.util.Date;
33
34 import javax.swing.JOptionPane;
35
36 import org.forester.archaeopteryx.webservices.PhylogeniesWebserviceClient;
37 import org.forester.archaeopteryx.webservices.WebserviceUtil;
38 import org.forester.archaeopteryx.webservices.WebservicesManager;
39 import org.forester.io.parsers.PhylogenyParser;
40 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
41 import org.forester.io.parsers.nhx.NHXParser;
42 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
43 import org.forester.io.parsers.phyloxml.PhyloXmlParser;
44 import org.forester.io.parsers.tol.TolParser;
45 import org.forester.phylogeny.Phylogeny;
46 import org.forester.phylogeny.PhylogenyMethods;
47 import org.forester.phylogeny.data.Identifier;
48 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
49 import org.forester.phylogeny.factories.PhylogenyFactory;
50 import org.forester.util.ForesterUtil;
51
52 public class UrlTreeReader implements Runnable {
53
54     private final MainFrame _main_frame;
55     private final int       _webservice_client_index;
56
57     UrlTreeReader( final MainFrame mf, final int webservice_client_index ) {
58         _main_frame = mf;
59         _webservice_client_index = webservice_client_index;
60     }
61
62     @Override
63     public void run() {
64         readPhylogeniesFromWebservice();
65     }
66
67     synchronized void readPhylogeniesFromWebservice() {
68         final long start_time = new Date().getTime();
69         URL url = null;
70         Phylogeny[] trees = null;
71         final WebservicesManager webservices_manager = WebservicesManager.getInstance();
72         final PhylogeniesWebserviceClient client = webservices_manager
73                 .getAvailablePhylogeniesWebserviceClient( _webservice_client_index );
74         String identifier = JOptionPane.showInputDialog( _main_frame, client.getInstructions() + "\n(Reference: "
75                 + client.getReference() + ")", client.getDescription(), JOptionPane.QUESTION_MESSAGE );
76         if ( ( identifier != null ) && ( identifier.trim().length() > 0 ) ) {
77             identifier = identifier.trim();
78             if ( client.isQueryInteger() ) {
79                 identifier = identifier.replaceAll( "^\\D+", "" );
80                 int id = -1;
81                 try {
82                     id = Integer.parseInt( identifier );
83                 }
84                 catch ( final NumberFormatException e ) {
85                     id = -1;
86                 }
87                 if ( id < 1 ) {
88                     JOptionPane.showMessageDialog( _main_frame,
89                                                    "Identifier is expected to be a number",
90                                                    "Can not open URL",
91                                                    JOptionPane.ERROR_MESSAGE );
92                     return;
93                 }
94                 identifier = id + "";
95             }
96             try {
97                 String url_str = client.getUrl();
98                 url_str = url_str.replaceFirst( PhylogeniesWebserviceClient.QUERY_PLACEHOLDER, identifier );
99                 url = new URL( url_str );
100                 PhylogenyParser parser = null;
101                 switch ( client.getReturnFormat() ) {
102                     case TOL_XML_RESPONSE:
103                         parser = new TolParser();
104                         break;
105                     case NEXUS:
106                         parser = new NexusPhylogeniesParser();
107                         ( ( NexusPhylogeniesParser ) parser ).setReplaceUnderscores( true );
108                         break;
109                     case NH:
110                         parser = new NHXParser();
111                         ( ( NHXParser ) parser ).setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.NO );
112                         ( ( NHXParser ) parser ).setReplaceUnderscores( true );
113                         ( ( NHXParser ) parser ).setGuessRootedness( true );
114                         break;
115                     case NH_EXTRACT_TAXONOMY:
116                         parser = new NHXParser();
117                         ( ( NHXParser ) parser ).setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.AGGRESSIVE );
118                         ( ( NHXParser ) parser ).setReplaceUnderscores( false );
119                         ( ( NHXParser ) parser ).setGuessRootedness( true );
120                         break;
121                     case PFAM:
122                         parser = new NHXParser();
123                         ( ( NHXParser ) parser )
124                                 .setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.PFAM_STYLE_STRICT );
125                         ( ( NHXParser ) parser ).setReplaceUnderscores( false );
126                         ( ( NHXParser ) parser ).setGuessRootedness( true );
127                         break;
128                     case NHX:
129                         parser = new NHXParser();
130                         ( ( NHXParser ) parser ).setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.NO );
131                         ( ( NHXParser ) parser ).setReplaceUnderscores( false );
132                         ( ( NHXParser ) parser ).setGuessRootedness( true );
133                         break;
134                     case PHYLOXML:
135                         parser = new PhyloXmlParser();
136                         break;
137                     default:
138                         throw new IllegalArgumentException( "unknown format: " + client.getReturnFormat() );
139                 }
140                 if ( _main_frame.getMainPanel().getCurrentTreePanel() != null ) {
141                     _main_frame.getMainPanel().getCurrentTreePanel().setWaitCursor();
142                 }
143                 else {
144                     _main_frame.getMainPanel().setWaitCursor();
145                 }
146                 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
147                 trees = factory.create( url.openStream(), parser );
148             }
149             catch ( final MalformedURLException e ) {
150                 JOptionPane.showMessageDialog( _main_frame,
151                                                "Malformed URL: " + url + "\n" + e.getLocalizedMessage(),
152                                                "Malformed URL",
153                                                JOptionPane.ERROR_MESSAGE );
154             }
155             catch ( final IOException e ) {
156                 JOptionPane.showMessageDialog( _main_frame,
157                                                "Could not read from " + url + "\n" + e.getLocalizedMessage(),
158                                                "Failed to read tree from " + client.getName() + " for " + identifier,
159                                                JOptionPane.ERROR_MESSAGE );
160             }
161             catch ( final NumberFormatException e ) {
162                 JOptionPane.showMessageDialog( _main_frame,
163                                                "Could not read from " + url + "\n" + e.getLocalizedMessage(),
164                                                "Failed to read tree from " + client.getName() + " for " + identifier,
165                                                JOptionPane.ERROR_MESSAGE );
166             }
167             catch ( final Exception e ) {
168                 e.printStackTrace();
169                 JOptionPane.showMessageDialog( _main_frame,
170                                                e.getLocalizedMessage(),
171                                                "Unexpected Exception",
172                                                JOptionPane.ERROR_MESSAGE );
173             }
174             finally {
175                 if ( _main_frame.getCurrentTreePanel() != null ) {
176                     _main_frame.getCurrentTreePanel().setArrowCursor();
177                 }
178                 else {
179                     _main_frame.getMainPanel().setArrowCursor();
180                 }
181             }
182             if ( ( trees != null ) && ( trees.length > 0 ) ) {
183                 for( final Phylogeny phylogeny : trees ) {
184                     if ( !phylogeny.isEmpty() ) {
185                         if ( client.getName().equals( WebserviceUtil.TREE_FAM_NAME ) ) {
186                             phylogeny.setRerootable( false );
187                             phylogeny.setRooted( true );
188                         }
189                         if ( client.getName().equals( WebserviceUtil.PFAM_NAME ) ) {
190                             phylogeny.setRerootable( false );
191                             phylogeny.setRooted( true );
192                             PhylogenyMethods.transferInternalNodeNamesToConfidence( phylogeny );
193                         }
194                         if ( client.getProcessingInstructions() != null ) {
195                             try {
196                                 WebserviceUtil.processInstructions( client, phylogeny );
197                             }
198                             catch ( final PhyloXmlDataFormatException e ) {
199                                 JOptionPane.showMessageDialog( _main_frame,
200                                                                "Error:\n" + e.getLocalizedMessage(),
201                                                                "Error",
202                                                                JOptionPane.ERROR_MESSAGE );
203                             }
204                         }
205                         if ( client.getNodeField() != null ) {
206                             try {
207                                 PhylogenyMethods.transferNodeNameToField( phylogeny, client.getNodeField(), false );
208                             }
209                             catch ( final PhyloXmlDataFormatException e ) {
210                                 JOptionPane.showMessageDialog( _main_frame,
211                                                                "Error:\n" + e.getLocalizedMessage(),
212                                                                "Error",
213                                                                JOptionPane.ERROR_MESSAGE );
214                             }
215                         }
216                         phylogeny.setIdentifier( new Identifier( identifier, client.getName() ) );
217                         _main_frame.getJMenuBar().remove( _main_frame.getHelpMenu() );
218                         _main_frame.getMenuBarOfMainFrame().add( _main_frame.getHelpMenu() );
219                         _main_frame.getMainPanel().addPhylogenyInNewTab( phylogeny,
220                                                                          _main_frame.getConfiguration(),
221                                                                          new File( url.getFile() ).getName(),
222                                                                          url.toString() );
223                         String my_name_for_file = "";
224                         if ( !ForesterUtil.isEmpty( phylogeny.getName() ) ) {
225                             my_name_for_file = new String( phylogeny.getName() ).replaceAll( " ", "_" );
226                         }
227                         else if ( phylogeny.getIdentifier() != null ) {
228                             final StringBuffer sb = new StringBuffer();
229                             if ( !ForesterUtil.isEmpty( phylogeny.getIdentifier().getProvider() ) ) {
230                                 sb.append( phylogeny.getIdentifier().getProvider() );
231                                 sb.append( "_" );
232                             }
233                             sb.append( phylogeny.getIdentifier().getValue() );
234                             my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
235                         }
236                         _main_frame.getMainPanel().getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
237                         AptxUtil.lookAtSomeTreePropertiesForAptxControlSettings( phylogeny, _main_frame.getMainPanel()
238                                 .getControlPanel(), _main_frame.getConfiguration() );
239                         _main_frame.getMainPanel().getControlPanel().showWhole();
240                     }
241                 }
242             }
243             _main_frame.getContentPane().repaint();
244             if ( ( ( trees != null ) && ( trees.length > 0 ) ) && ( ( new Date().getTime() - start_time ) > 20000 ) ) {
245                 try {
246                     JOptionPane.showMessageDialog( null,
247                                                    ForesterUtil.wordWrap( "Successfully read in " + trees.length
248                                                            + " evolutionry tree(s) from [" + url + "]", 80 ),
249                                                    "Success",
250                                                    JOptionPane.INFORMATION_MESSAGE );
251                 }
252                 catch ( final Exception e ) {
253                     // Not important if this fails, do nothing.
254                 }
255                 _main_frame.getContentPane().repaint();
256             }
257         }
258         _main_frame.activateSaveAllIfNeeded();
259         System.gc();
260     }
261 }