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