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