JAL-4059 Added some more Platform.addJ2SDirectDatabaseCall web service URLs in static...
[jalview.git] / src / jalview / ws / dbsources / TDBeacons.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ 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;
22
23 import java.io.InputStream;
24 import java.net.URL;
25 import java.net.URLConnection;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Locale;
29 import java.util.Vector;
30
31 import javax.xml.bind.JAXBContext;
32 import javax.xml.bind.JAXBElement;
33 import javax.xml.bind.JAXBException;
34 import javax.xml.stream.FactoryConfigurationError;
35 import javax.xml.stream.XMLInputFactory;
36 import javax.xml.stream.XMLStreamException;
37 import javax.xml.stream.XMLStreamReader;
38
39 import com.stevesoft.pat.Regex;
40
41 import jalview.bin.Cache;
42 import jalview.datamodel.Alignment;
43 import jalview.datamodel.AlignmentI;
44 import jalview.datamodel.DBRefEntry;
45 import jalview.datamodel.DBRefSource;
46 import jalview.datamodel.PDBEntry;
47 import jalview.datamodel.Sequence;
48 import jalview.datamodel.SequenceFeature;
49 import jalview.datamodel.SequenceI;
50 import jalview.schemes.ResidueProperties;
51 import jalview.util.Platform;
52 import jalview.util.StringUtils;
53 import jalview.ws.seqfetcher.DbSourceProxyImpl;
54 import jalview.xml.binding.uniprot.DbReferenceType;
55 import jalview.xml.binding.uniprot.Entry;
56 import jalview.xml.binding.uniprot.FeatureType;
57 import jalview.xml.binding.uniprot.LocationType;
58 import jalview.xml.binding.uniprot.PositionType;
59 import jalview.xml.binding.uniprot.PropertyType;
60
61 /**
62  * This class queries the Uniprot database for sequence data, unmarshals the
63  * returned XML, and converts it to Jalview Sequence records (including attached
64  * database references and sequence features)
65  * 
66  * @author JimP
67  * 
68  */
69 public class TDBeacons extends DbSourceProxyImpl
70 {
71   private static final String DEFAULT_UNIPROT_DOMAIN = "https://www.uniprot.org";
72
73   private static final String BAR_DELIMITER = "|";
74
75   private static final String DEFAULT_THREEDBEACONS_DOMAIN = "https://wwwdev.ebi.ac.uk/pdbe/pdbe-kb/3dbeacons-hub-api/uniprot/summary/";
76
77   static
78   {
79     Platform.addJ2SDirectDatabaseCall(DEFAULT_UNIPROT_DOMAIN);
80     Platform.addJ2SDirectDatabaseCall(DEFAULT_THREEDBEACONS_DOMAIN);
81   }
82
83   /**
84    * Constructor
85    */
86   public TDBeacons()
87   {
88     super();
89   }
90
91   private String getDomain()
92   {
93     return Cache.getDefault("UNIPROT_DOMAIN", DEFAULT_UNIPROT_DOMAIN);
94     // return Cache.getDefault("3DB_DOMAIN", DEFAULT_THREEDBEACONS_DOMAIN );
95   }
96
97   /*
98    * (non-Javadoc)
99    * 
100    * @see jalview.ws.DbSourceProxy#getAccessionSeparator()
101    */
102   @Override
103   public String getAccessionSeparator()
104   {
105     return null;
106   }
107
108   /*
109    * (non-Javadoc)
110    * 
111    * @see jalview.ws.DbSourceProxy#getAccessionValidator()
112    */
113   @Override
114   public Regex getAccessionValidator()
115   {
116     return new Regex("([A-Z]+[0-9]+[A-Z0-9]+|[A-Z0-9]+_[A-Z0-9]+)");
117   }
118
119   /*
120    * (non-Javadoc)
121    * 
122    * @see jalview.ws.DbSourceProxy#getDbSource()
123    */
124   @Override
125   public String getDbSource()
126   {
127     return "3d-beacons";// DBRefSource.UNIPROT;
128   }
129
130   /*
131    * (non-Javadoc)
132    * 
133    * @see jalview.ws.DbSourceProxy#getDbVersion()
134    */
135   @Override
136   public String getDbVersion()
137   {
138     return "0"; // we really don't know what version we're on.
139   }
140
141   /*
142    * (non-Javadoc)
143    * 
144    * @see jalview.ws.DbSourceProxy#getSequenceRecords(java.lang.String[])
145    */
146   @Override
147   public AlignmentI getSequenceRecords(String queries) throws Exception
148   {
149     startQuery();
150     try
151     {
152       queries = queries.toUpperCase(Locale.ROOT).replaceAll(
153               "(UNIPROT\\|?|UNIPROT_|UNIREF\\d+_|UNIREF\\d+\\|?)", "");
154       AlignmentI al = null;
155
156       String downloadstring = getDomain() + "/uniprot/" + queries + ".xml";
157       // String downloadstring = getDomain() + queries + ".json";
158
159       URL url = new URL(downloadstring);
160       URLConnection urlconn = url.openConnection();
161       InputStream istr = urlconn.getInputStream();
162       List<Entry> entries = getUniprotEntries(istr);
163       if (entries != null)
164       {
165         List<SequenceI> seqs = new ArrayList<>();
166         for (Entry entry : entries)
167         {
168           seqs.add(uniprotEntryToSequence(entry));
169         }
170         al = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
171       }
172
173       stopQuery();
174       return al;
175     } catch (Exception e)
176     {
177       throw (e);
178     } finally
179     {
180       stopQuery();
181     }
182   }
183
184   /**
185    * Converts an Entry object (bound from Uniprot XML) to a Jalview Sequence
186    * 
187    * @param entry
188    * @return
189    */
190   SequenceI uniprotEntryToSequence(Entry entry)
191   {
192     String id = getUniprotEntryId(entry);
193     /*
194      * Sequence should not include any whitespace, but JAXB leaves these in
195      */
196     String seqString = entry.getSequence().getValue().replaceAll("\\s*",
197             "");
198
199     SequenceI sequence = new Sequence(id, seqString);
200     sequence.setDescription(getUniprotEntryDescription(entry));
201
202     /*
203      * add a 'self' DBRefEntry for each accession
204      */
205     final String dbVersion = getDbVersion();
206     List<DBRefEntry> dbRefs = new ArrayList<>();
207     for (String accessionId : entry.getAccession())
208     {
209       DBRefEntry dbRef = new DBRefEntry(DBRefSource.UNIPROT, dbVersion,
210               accessionId);
211       dbRefs.add(dbRef);
212     }
213
214     /*
215      * add a DBRefEntry for each dbReference element in the XML;
216      * also add a PDBEntry if type="PDB";
217      * also add an EMBLCDS dbref if protein sequence id is given
218      * also add an Ensembl dbref " " " " " "
219      */
220     Vector<PDBEntry> pdbRefs = new Vector<>();
221     for (DbReferenceType dbref : entry.getDbReference())
222     {
223       String type = dbref.getType();
224       DBRefEntry dbr = new DBRefEntry(type,
225               DBRefSource.UNIPROT + ":" + dbVersion, dbref.getId());
226       dbRefs.add(dbr);
227       if ("PDB".equals(type))
228       {
229         pdbRefs.add(new PDBEntry(dbr));
230       }
231       if ("EMBL".equals(type))
232       {
233         /*
234          * e.g. Uniprot accession Q9BXM7 has
235          * <dbReference type="EMBL" id="M19359">
236          *   <property type="protein sequence ID" value="AAA40981.1"/>
237          *   <property type="molecule type" value="Genomic_DNA"/>
238          * </dbReference> 
239          */
240         String cdsId = getProperty(dbref.getProperty(),
241                 "protein sequence ID");
242         if (cdsId != null && cdsId.trim().length() > 0)
243         {
244           // remove version
245           String[] vrs = cdsId.split("\\.");
246           String version = vrs.length > 1 ? vrs[1]
247                   : DBRefSource.UNIPROT + ":" + dbVersion;
248           dbr = new DBRefEntry(DBRefSource.EMBLCDS, version, vrs[0]);
249           dbRefs.add(dbr);
250         }
251       }
252       if ("Ensembl".equals(type))
253       {
254         /*
255          * e.g. Uniprot accession Q9BXM7 has
256          * <dbReference type="Ensembl" id="ENST00000321556">
257          *   <molecule id="Q9BXM7-1"/>
258          *   <property type="protein sequence ID" value="ENSP00000364204"/>
259          *   <property type="gene ID" value="ENSG00000158828"/>
260          * </dbReference> 
261          */
262         String cdsId = getProperty(dbref.getProperty(),
263                 "protein sequence ID");
264         if (cdsId != null && cdsId.trim().length() > 0)
265         {
266           dbr = new DBRefEntry(DBRefSource.ENSEMBL,
267                   DBRefSource.UNIPROT + ":" + dbVersion, cdsId.trim());
268           dbRefs.add(dbr);
269         }
270       }
271     }
272
273     /*
274      * create features; they have either begin and end, or position, in XML
275      */
276     sequence.setPDBId(pdbRefs);
277     if (entry.getFeature() != null)
278     {
279       for (FeatureType uf : entry.getFeature())
280       {
281         LocationType location = uf.getLocation();
282         int start = 0;
283         int end = 0;
284         if (location.getPosition() != null)
285         {
286           start = location.getPosition().getPosition().intValue();
287           end = start;
288         }
289         else
290         {
291           start = location.getBegin().getPosition().intValue();
292           end = location.getEnd().getPosition().intValue();
293         }
294         SequenceFeature sf = new SequenceFeature(uf.getType(),
295                 getDescription(uf), start, end, "Uniprot");
296         sf.setStatus(uf.getStatus());
297         sequence.addSequenceFeature(sf);
298       }
299     }
300     for (DBRefEntry dbr : dbRefs)
301     {
302       sequence.addDBRef(dbr);
303     }
304     return sequence;
305   }
306
307   /**
308    * A helper method that builds a sequence feature description
309    * 
310    * @param feature
311    * @return
312    */
313   static String getDescription(FeatureType feature)
314   {
315     String orig = feature.getOriginal();
316     List<String> variants = feature.getVariation();
317     StringBuilder sb = new StringBuilder();
318
319     /*
320      * append variant in standard format if present
321      * e.g. p.Arg59Lys
322      * multiple variants are split over lines using <br>
323      */
324     boolean asHtml = false;
325     if (orig != null && !orig.isEmpty() && variants != null
326             && !variants.isEmpty())
327     {
328       int p = 0;
329       for (String var : variants)
330       {
331         // TODO proper HGVS nomenclature for delins structural variations
332         // http://varnomen.hgvs.org/recommendations/protein/variant/delins/
333         // for now we are pragmatic - any orig/variant sequence longer than
334         // three characters is shown with single-character notation rather than
335         // three-letter notation
336         sb.append("p.");
337         if (orig.length() < 4)
338         {
339           for (int c = 0, clen = orig.length(); c < clen; c++)
340           {
341             char origchar = orig.charAt(c);
342             String orig3 = ResidueProperties.aa2Triplet.get("" + origchar);
343             sb.append(orig3 == null ? origchar
344                     : StringUtils.toSentenceCase(orig3));
345           }
346         }
347         else
348         {
349           sb.append(orig);
350         }
351
352         LocationType location = feature.getLocation();
353         PositionType start = location.getPosition() == null
354                 ? location.getBegin()
355                 : location.getPosition();
356         sb.append(Integer.toString(start.getPosition().intValue()));
357
358         if (var.length() < 4)
359         {
360           for (int c = 0, clen = var.length(); c < clen; c++)
361           {
362             char varchar = var.charAt(c);
363             String var3 = ResidueProperties.aa2Triplet.get("" + varchar);
364
365             sb.append(var3 != null ? StringUtils.toSentenceCase(var3)
366                     : "" + varchar);
367           }
368         }
369         else
370         {
371           sb.append(var);
372         }
373         if (++p != variants.size())
374         {
375           sb.append("<br/>&nbsp;&nbsp;");
376           asHtml = true;
377         }
378         else
379         {
380           sb.append(" ");
381         }
382       }
383     }
384     String description = feature.getDescription();
385     if (description != null)
386     {
387       sb.append(description);
388     }
389     if (asHtml)
390     {
391       sb.insert(0, "<html>");
392       sb.append("</html>");
393     }
394
395     return sb.toString();
396   }
397
398   /**
399    * A helper method that searches the list of properties for one with the given
400    * key, and if found returns the property value, else returns null
401    * 
402    * @param properties
403    * @param key
404    * @return
405    */
406   static String getProperty(List<PropertyType> properties, String key)
407   {
408     String value = null;
409     if (properties != null)
410     {
411       for (PropertyType prop : properties)
412       {
413         if (key.equals(prop.getType()))
414         {
415           value = prop.getValue();
416           break;
417         }
418       }
419     }
420     return value;
421   }
422
423   /**
424    * Extracts xml element entry/protein/recommendedName/fullName
425    * 
426    * @param entry
427    * @return
428    */
429   static String getUniprotEntryDescription(Entry entry)
430   {
431     String desc = "";
432     if (entry.getProtein() != null
433             && entry.getProtein().getRecommendedName() != null)
434     {
435       // fullName is mandatory if recommendedName is present
436       desc = entry.getProtein().getRecommendedName().getFullName()
437               .getValue();
438     }
439     return desc;
440   }
441
442   /**
443    * Constructs a sequence id by concatenating all entry/name elements with '|'
444    * separator
445    * 
446    * @param entry
447    * @return
448    */
449   static String getUniprotEntryId(Entry entry)
450   {
451     StringBuilder name = new StringBuilder(32);
452     for (String n : entry.getName())
453     {
454       if (name.length() > 0)
455       {
456         name.append(BAR_DELIMITER);
457       }
458       name.append(n);
459     }
460     return name.toString();
461   }
462
463   /*
464    * (non-Javadoc)
465    * 
466    * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
467    */
468   @Override
469   public boolean isValidReference(String accession)
470   {
471     // TODO: make the following a standard validator
472     return (accession == null || accession.length() < 2) ? false
473             : getAccessionValidator().search(accession);
474   }
475
476   /**
477    * return LDHA_CHICK uniprot entry
478    */
479   @Override
480   public String getTestQuery()
481   {
482     return "P00340";
483   }
484
485   @Override
486   public String getDbName()
487   {
488     return "Uniprot"; // getDbSource();
489   }
490
491   @Override
492   public int getTier()
493   {
494     return 0;
495   }
496
497   /**
498    * Reads the reply to the EBI Fetch Uniprot data query, unmarshals it to an
499    * Uniprot object, and returns the enclosed Entry objects, or null on any
500    * failure
501    * 
502    * @param is
503    * @return
504    */
505   public List<Entry> getUniprotEntries(InputStream is)
506   {
507     List<Entry> entries = null;
508     try
509     {
510       JAXBContext jc = JAXBContext
511               .newInstance("jalview.xml.binding.uniprot");
512       XMLStreamReader streamReader = XMLInputFactory.newInstance()
513               .createXMLStreamReader(is);
514       javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
515       JAXBElement<jalview.xml.binding.uniprot.Uniprot> uniprotElement = um
516               .unmarshal(streamReader,
517                       jalview.xml.binding.uniprot.Uniprot.class);
518       jalview.xml.binding.uniprot.Uniprot uniprot = uniprotElement
519               .getValue();
520
521       if (uniprot != null && !uniprot.getEntry().isEmpty())
522       {
523         entries = uniprot.getEntry();
524       }
525     } catch (JAXBException | XMLStreamException
526             | FactoryConfigurationError e)
527     {
528       e.printStackTrace();
529     }
530     return entries;
531   }
532 }