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