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