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