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