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