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