inprogress
[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             boolean exception = false;
97             try {
98                 String url_str = client.getUrl();
99                 url_str = url_str.replaceFirst( PhylogeniesWebserviceClient.QUERY_PLACEHOLDER, identifier );
100                 url = new URL( url_str );
101                 PhylogenyParser parser = null;
102                 switch ( client.getReturnFormat() ) {
103                     case TOL_XML_RESPONSE:
104                         parser = new TolParser();
105                         break;
106                     case NEXUS:
107                         parser = new NexusPhylogeniesParser();
108                         ( ( NexusPhylogeniesParser ) parser ).setReplaceUnderscores( true );
109                         break;
110                     case TREEBASE:
111                         parser = new NexusPhylogeniesParser();
112                         ( ( NexusPhylogeniesParser ) parser ).setReplaceUnderscores( true );
113                         ( ( NexusPhylogeniesParser ) parser ).setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.NO );
114                         break;
115                     case NH:
116                         parser = new NHXParser();
117                         ( ( NHXParser ) parser ).setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.NO );
118                         ( ( NHXParser ) parser ).setReplaceUnderscores( true );
119                         ( ( NHXParser ) parser ).setGuessRootedness( true );
120                         break;
121                     case NH_EXTRACT_TAXONOMY:
122                         parser = new NHXParser();
123                         ( ( NHXParser ) parser ).setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.AGGRESSIVE );
124                         ( ( NHXParser ) parser ).setReplaceUnderscores( false );
125                         ( ( NHXParser ) parser ).setGuessRootedness( true );
126                         break;
127                     case PFAM:
128                         parser = new NHXParser();
129                         ( ( NHXParser ) parser )
130                                 .setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.PFAM_STYLE_STRICT );
131                         ( ( NHXParser ) parser ).setReplaceUnderscores( false );
132                         ( ( NHXParser ) parser ).setGuessRootedness( true );
133                         break;
134                     case NHX:
135                         parser = new NHXParser();
136                         ( ( NHXParser ) parser ).setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.NO );
137                         ( ( NHXParser ) parser ).setReplaceUnderscores( false );
138                         ( ( NHXParser ) parser ).setGuessRootedness( true );
139                         break;
140                     case PHYLOXML:
141                         parser = PhyloXmlParser.createPhyloXmlParserXsdValidating();
142                         break;
143                     default:
144                         throw new IllegalArgumentException( "unknown format: " + client.getReturnFormat() );
145                 }
146                 if ( _main_frame.getMainPanel().getCurrentTreePanel() != null ) {
147                     _main_frame.getMainPanel().getCurrentTreePanel().setWaitCursor();
148                 }
149                 else {
150                     _main_frame.getMainPanel().setWaitCursor();
151                 }
152                 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
153                 trees = factory.create( url.openStream(), parser );
154             }
155             catch ( final MalformedURLException e ) {
156                 exception = true;
157                 JOptionPane.showMessageDialog( _main_frame,
158                                                "Malformed URL: " + url + "\n" + e.getLocalizedMessage(),
159                                                "Malformed URL",
160                                                JOptionPane.ERROR_MESSAGE );
161             }
162             catch ( final IOException e ) {
163                 exception = true;
164                 JOptionPane.showMessageDialog( _main_frame,
165                                                "Could not read from " + url + "\n" + e.getLocalizedMessage(),
166                                                "Failed to read tree from " + client.getName() + " for " + identifier,
167                                                JOptionPane.ERROR_MESSAGE );
168             }
169             catch ( final NumberFormatException e ) {
170                 exception = true;
171                 JOptionPane.showMessageDialog( _main_frame,
172                                                "Could not read from " + url + "\n" + e.getLocalizedMessage(),
173                                                "Failed to read tree from " + client.getName() + " for " + identifier,
174                                                JOptionPane.ERROR_MESSAGE );
175             }
176             catch ( final Exception e ) {
177                 exception = true;
178                 e.printStackTrace();
179                 JOptionPane.showMessageDialog( _main_frame,
180                                                e.getLocalizedMessage(),
181                                                "Unexpected Exception",
182                                                JOptionPane.ERROR_MESSAGE );
183             }
184             finally {
185                 if ( _main_frame.getCurrentTreePanel() != null ) {
186                     _main_frame.getCurrentTreePanel().setArrowCursor();
187                 }
188                 else {
189                     _main_frame.getMainPanel().setArrowCursor();
190                 }
191             }
192             if ( ( trees != null ) && ( trees.length > 0 ) ) {
193                 for( final Phylogeny phylogeny : trees ) {
194                     if ( !phylogeny.isEmpty() ) {
195                         if ( client.getName().equals( WebserviceUtil.TREE_FAM_NAME ) ) {
196                             phylogeny.setRerootable( false );
197                             phylogeny.setRooted( true );
198                         }
199                         if ( client.getProcessingInstructions() != null ) {
200                             try {
201                                 WebserviceUtil.processInstructions( client, phylogeny );
202                             }
203                             catch ( final PhyloXmlDataFormatException e ) {
204                                 JOptionPane.showMessageDialog( _main_frame,
205                                                                "Error:\n" + e.getLocalizedMessage(),
206                                                                "Error",
207                                                                JOptionPane.ERROR_MESSAGE );
208                             }
209                         }
210                         if ( client.getNodeField() != null ) {
211                             try {
212                                 PhylogenyMethods.transferNodeNameToField( phylogeny, client.getNodeField(), false );
213                             }
214                             catch ( final PhyloXmlDataFormatException e ) {
215                                 JOptionPane.showMessageDialog( _main_frame,
216                                                                "Error:\n" + e.getLocalizedMessage(),
217                                                                "Error",
218                                                                JOptionPane.ERROR_MESSAGE );
219                             }
220                         }
221                         phylogeny.setIdentifier( new Identifier( identifier, client.getName() ) );
222                         _main_frame.getJMenuBar().remove( _main_frame.getHelpMenu() );
223                         _main_frame.getMenuBarOfMainFrame().add( _main_frame.getHelpMenu() );
224                         _main_frame.getMainPanel().addPhylogenyInNewTab( phylogeny,
225                                                                          _main_frame.getConfiguration(),
226                                                                          new File( url.getFile() ).getName(),
227                                                                          url.toString() );
228                         String my_name_for_file = "";
229                         if ( !ForesterUtil.isEmpty( phylogeny.getName() ) ) {
230                             my_name_for_file = new String( phylogeny.getName() ).replaceAll( " ", "_" );
231                         }
232                         else if ( phylogeny.getIdentifier() != null ) {
233                             final StringBuffer sb = new StringBuffer();
234                             if ( !ForesterUtil.isEmpty( phylogeny.getIdentifier().getProvider() ) ) {
235                                 sb.append( phylogeny.getIdentifier().getProvider() );
236                                 sb.append( "_" );
237                             }
238                             sb.append( phylogeny.getIdentifier().getValue() );
239                             my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
240                         }
241                         _main_frame.getMainPanel().getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
242                         AptxUtil.lookAtSomeTreePropertiesForAptxControlSettings( phylogeny, _main_frame.getMainPanel()
243                                 .getControlPanel(), _main_frame.getConfiguration() );
244                         _main_frame.getMainPanel().getControlPanel().showWhole();
245                     }
246                 }
247             }
248             else if ( !exception ) {
249                 JOptionPane.showMessageDialog( null, ForesterUtil.wordWrap( "Failed to read in tree(s) from [" + url
250                         + "]", 80 ), "Error", JOptionPane.ERROR_MESSAGE );
251             }
252             _main_frame.getContentPane().repaint();
253             if ( ( ( trees != null ) && ( trees.length > 0 ) ) && ( ( new Date().getTime() - start_time ) > 20000 ) ) {
254                 try {
255                     JOptionPane.showMessageDialog( null,
256                                                    ForesterUtil.wordWrap( "Successfully read in " + trees.length
257                                                            + " tree(s) from [" + url + "]", 80 ),
258                                                    "Success",
259                                                    JOptionPane.INFORMATION_MESSAGE );
260                 }
261                 catch ( final Exception e ) {
262                     // Not important if this fails, do nothing.
263                 }
264                 _main_frame.getContentPane().repaint();
265             }
266         }
267         _main_frame.activateSaveAllIfNeeded();
268         System.gc();
269     }
270 }