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