tidy imports
[jalview.git] / src / jalview / ws / dbsources / das / datamodel / DasSourceRegistry.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3  * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
10  *  
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.ws.dbsources.das.datamodel;
19
20 import java.net.HttpURLConnection;
21 import java.net.MalformedURLException;
22 import java.net.URL;
23 import java.util.ArrayList;
24 import java.util.Enumeration;
25 import java.util.HashMap;
26 import java.util.Hashtable;
27 import java.util.List;
28 import java.util.StringTokenizer;
29
30 import org.biodas.jdas.client.ConnectionPropertyProviderI;
31 import org.biodas.jdas.client.SourcesClient;
32 import org.biodas.jdas.client.threads.MultipleConnectionPropertyProviderI;
33 import org.biodas.jdas.dassources.Capabilities;
34 import org.biodas.jdas.schema.sources.CAPABILITY;
35 import org.biodas.jdas.schema.sources.SOURCE;
36 import org.biodas.jdas.schema.sources.SOURCES;
37 import org.biodas.jdas.schema.sources.VERSION;
38
39 import jalview.bin.Cache;
40 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
41 import jalview.ws.dbsources.das.api.jalviewSourceI;
42
43 /**
44  *
45  */
46 public class DasSourceRegistry implements DasSourceRegistryI,
47         MultipleConnectionPropertyProviderI
48 {
49   // private org.biodas.jdas.schema.sources.SOURCE[] dasSources = null;
50   private List<jalviewSourceI> dasSources = null;
51
52   private Hashtable<String, jalviewSourceI> sourceNames = null;
53
54   private Hashtable<String, jalviewSourceI> localSources = null;
55
56   public static String DEFAULT_REGISTRY = "http://www.dasregistry.org/das/";
57
58   /**
59    * true if thread is running and we are talking to DAS registry service
60    */
61   private boolean loadingDasSources = false;
62
63   public boolean isLoadingDasSources()
64   {
65     return loadingDasSources;
66   }
67
68   public String getDasRegistryURL()
69   {
70     String registry = jalview.bin.Cache.getDefault("DAS_REGISTRY_URL",
71             DEFAULT_REGISTRY);
72
73     if (registry.indexOf("/registry/das1/sources/") > -1)
74     {
75       jalview.bin.Cache.setProperty(jalview.bin.Cache.DAS_REGISTRY_URL,
76               DEFAULT_REGISTRY);
77       registry = DEFAULT_REGISTRY;
78     }
79     if (registry.lastIndexOf("sources.xml") == registry.length() - 11)
80     {
81       // no trailing sources.xml document for registry in JDAS
82       jalview.bin.Cache.setProperty(
83               jalview.bin.Cache.DAS_REGISTRY_URL,
84               registry = registry.substring(0,
85                       registry.lastIndexOf("sources.xml")));
86     }
87     return registry;
88   }
89
90   /**
91    * query the default DAS Source Registry for sources. Uses value of jalview
92    * property DAS_REGISTRY_URL and the DasSourceBrowser.DEFAULT_REGISTRY if that
93    * doesn't exist.
94    * 
95    * @return list of sources
96    */
97   private List<jalviewSourceI> getDASSources()
98   {
99
100     return getDASSources(getDasRegistryURL(), this);
101   }
102
103   /**
104    * query the given URL for DasSources.
105    * 
106    * @param registryURL
107    *          return sources from registryURL
108    */
109   private static List<jalviewSourceI> getDASSources(String registryURL,
110           MultipleConnectionPropertyProviderI registry)
111   {
112     try
113     {
114       URL url = new URL(registryURL);
115       org.biodas.jdas.client.SourcesClientInterface client = new SourcesClient();
116
117       SOURCES sources = client.fetchDataRegistry(registryURL, null, null,
118               null, null, null, null);
119
120       List<SOURCE> dassources = sources.getSOURCE();
121       ArrayList<jalviewSourceI> dsrc = new ArrayList<jalviewSourceI>();
122       HashMap<String, Integer> latests = new HashMap<String, Integer>();
123       Integer latest;
124       for (SOURCE src : dassources)
125       {
126         JalviewSource jsrc = new JalviewSource(src, registry, false);
127         latest = latests.get(jsrc.getSourceURL());
128         if (latest != null)
129         {
130           if (jsrc.isNewerThan(dsrc.get(latest.intValue())))
131           {
132             dsrc.set(latest.intValue(), jsrc);
133           }
134           else
135           {
136             System.out.println("Debug: Ignored older source "
137                     + jsrc.getTitle());
138           }
139         }
140         else
141         {
142           latests.put(jsrc.getSourceURL(), Integer.valueOf(dsrc.size()));
143           dsrc.add(jsrc);
144         }
145       }
146       return dsrc;
147     } catch (Exception ex)
148     {
149       System.err.println("Failed to contact DAS1 registry at "
150               + registryURL);
151       ex.printStackTrace();
152       return new ArrayList<jalviewSourceI>();
153     }
154   }
155
156   public void run()
157   {
158     getSources();
159   }
160
161   @Override
162   public List<jalviewSourceI> getSources()
163   {
164     if (dasSources == null)
165     {
166       dasSources = getDASSources();
167     }
168     return appendLocalSources();
169   }
170
171   /**
172    * generate Sources from the local das source list
173    * 
174    */
175   private void addLocalDasSources()
176   {
177     if (localSources == null)
178     {
179       // get local sources from properties and initialise the local source list
180       String local = jalview.bin.Cache.getProperty("DAS_LOCAL_SOURCE");
181       if (local != null)
182       {
183         StringTokenizer st = new StringTokenizer(local, "\t");
184         while (st.hasMoreTokens())
185         {
186           String token = st.nextToken();
187           int bar = token.indexOf("|");
188           String url = token.substring(bar + 1);
189           boolean features = true, sequence = false;
190           if (url.startsWith("sequence:"))
191           {
192             url = url.substring(9);
193             // this source also serves sequences as well as features
194             sequence = true;
195           }
196           createLocalSource(url, token.substring(0, bar), sequence,
197                   features);
198         }
199       }
200     }
201   }
202
203   private List<jalviewSourceI> appendLocalSources()
204   {
205     List<jalviewSourceI> srclist = new ArrayList<jalviewSourceI>();
206     addLocalDasSources();
207     sourceNames = new Hashtable<String, jalviewSourceI>();
208     if (dasSources != null)
209     {
210       for (jalviewSourceI src : dasSources)
211       {
212         sourceNames.put(src.getTitle(), src);
213         srclist.add(src);
214       }
215     }
216
217     if (localSources == null)
218     {
219       return srclist;
220     }
221     Enumeration en = localSources.keys();
222     while (en.hasMoreElements())
223     {
224       String key = en.nextElement().toString();
225       jalviewSourceI jvsrc = localSources.get(key);
226       sourceNames.put(key, jvsrc);
227       srclist.add(jvsrc);
228     }
229     return srclist;
230   }
231
232   /*
233  * 
234  */
235
236   @Override
237   public jalviewSourceI createLocalSource(String url, String name,
238           boolean sequence, boolean features)
239   {
240     SOURCE local = _createLocalSource(url, name, sequence, features);
241
242     if (localSources == null)
243     {
244       localSources = new Hashtable<String, jalviewSourceI>();
245     }
246     jalviewSourceI src = new JalviewSource(local, this, true);
247     localSources.put(local.getTitle(), src);
248     return src;
249   }
250
251   private SOURCE _createLocalSource(String url, String name,
252           boolean sequence, boolean features)
253   {
254     SOURCE local = new SOURCE();
255
256     local.setUri(url);
257     local.setTitle(name);
258     local.setVERSION(new ArrayList<VERSION>());
259     VERSION v = new VERSION();
260     List<CAPABILITY> cp = new ArrayList<CAPABILITY>();
261     if (sequence)
262     {
263       /*
264        * Could try and synthesize a coordinate system for the source if needbe
265        * COORDINATES coord = new COORDINATES(); coord.setAuthority("NCBI");
266        * coord.setSource("Chromosome"); coord.setTaxid("9606");
267        * coord.setVersion("35"); version.getCOORDINATES().add(coord);
268        */
269       CAPABILITY cap = new CAPABILITY();
270       cap.setType("das1:" + Capabilities.SEQUENCE.getName());
271       cap.setQueryUri(url + "/sequence");
272       cp.add(cap);
273     }
274     if (features)
275     {
276       CAPABILITY cap = new CAPABILITY();
277       cap.setType("das1:" + Capabilities.FEATURES.getName());
278       cap.setQueryUri(url + "/features");
279       cp.add(cap);
280     }
281
282     v.getCAPABILITY().addAll(cp);
283     local.getVERSION().add(v);
284
285     return local;
286   }
287
288   @Override
289   public jalviewSourceI getSource(String nickname)
290   {
291     return sourceNames.get(nickname);
292   }
293
294   @Override
295   public boolean removeLocalSource(jalviewSourceI source)
296   {
297     if (localSources.containsValue(source))
298     {
299       localSources.remove(source.getTitle());
300       sourceNames.remove(source.getTitle());
301       dasSources.remove(source);
302       jalview.bin.Cache.setProperty("DAS_LOCAL_SOURCE",
303               getLocalSourceString());
304
305       return true;
306     }
307     return false;
308   }
309
310   @Override
311   public void refreshSources()
312   {
313     dasSources = null;
314     sourceNames = null;
315     run();
316   }
317
318   @Override
319   public List<jalviewSourceI> resolveSourceNicknames(List<String> sources)
320   {
321     ArrayList<jalviewSourceI> resolved = new ArrayList<jalviewSourceI>();
322     if (sourceNames != null)
323     {
324       for (String src : sources)
325       {
326         jalviewSourceI dsrc = sourceNames.get(src);
327         if (dsrc != null)
328         {
329           resolved.add(dsrc);
330         }
331       }
332     }
333     return resolved;
334   }
335
336   @Override
337   public String getLocalSourceString()
338   {
339     if (localSources != null)
340     {
341       StringBuffer sb = new StringBuffer();
342       Enumeration en = localSources.keys();
343       while (en.hasMoreElements())
344       {
345         String token = en.nextElement().toString();
346         jalviewSourceI srco = localSources.get(token);
347         sb.append(token + "|"
348                 + (srco.isSequenceSource() ? "sequence:" : "")
349                 + srco.getUri() + "\t");
350       }
351       return sb.toString();
352     }
353     return "";
354   }
355
356   private static final Hashtable<URL, String> authStash;
357   static
358   {
359     authStash = new Hashtable<URL, String>();
360
361     try
362     {
363       // TODO: allow same credentials for https and http
364       authStash.put(new URL(
365               "http://www.compbio.dundee.ac.uk/geneweb/das/myseq/"),
366               "Basic SmltOm1pSg==");
367     } catch (MalformedURLException e)
368     {
369       // TODO Auto-generated catch block
370       e.printStackTrace();
371     }
372   }
373
374   @Override
375   public MultipleConnectionPropertyProviderI getSessionHandler()
376   {
377     return this;
378   }
379
380   @Override
381   public ConnectionPropertyProviderI getConnectionPropertyProviderFor(
382           String arg0)
383   {
384
385     final ConnectionPropertyProviderI conprov = new ConnectionPropertyProviderI()
386     {
387       boolean authed = false;
388
389       @Override
390       public void setConnectionProperties(HttpURLConnection connection)
391       {
392         String auth = authStash.get(connection.getURL());
393         if (auth != null && auth.length() > 0)
394         {
395           connection.setRequestProperty("Authorisation", auth);
396           authed = true;
397         }
398         else
399         {
400           authed = false;
401         }
402       }
403
404       @Override
405       public boolean getResponseProperties(HttpURLConnection connection)
406       {
407         String auth = authStash.get(connection.getURL());
408         if (auth != null && auth.length() == 0)
409         {
410           // don't attempt to check if we authed or not - user entered empty
411           // password
412           return false;
413         }
414         if (!authed)
415         {
416           if (auth != null)
417           {
418             // try and pass credentials.
419             return true;
420           }
421           // see if we should try and create a new auth record.
422           String ameth = connection.getHeaderField("X-DAS-AuthMethods");
423           Cache.log.debug("Could authenticate to " + connection.getURL()
424                   + " with : " + ameth);
425           // TODO: search auth string and raise login box - return if auth was
426           // provided
427           return false;
428         }
429         else
430         {
431           // check to see if auth was successful
432           String asuc = connection
433                   .getHeaderField("X-DAS_AuthenticatedUser");
434           if (asuc != null && asuc.trim().length() > 0)
435           {
436             // authentication was successful
437             Cache.log.debug("Authenticated successfully to "
438                     + connection.getURL().toString());
439             return false;
440           }
441           // it wasn't - so we should tell the user it failed and ask if they
442           // want to attempt authentication again.
443           authStash.remove(connection.getURL());
444           // open a new login/password dialog with cancel button
445           // set new authStash content with password and return true
446           return true; //
447           // User cancelled auth - so put empty string in stash to indicate we
448           // don't want to auth with this server.
449           // authStash.put(connection.getURL(), "");
450           // return false;
451         }
452       }
453     };
454     return conprov;
455   }
456
457 }