b9fe52f607fa5d970405292dcb40478d3821d537
[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
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.uniprot.DbReferenceType;
38 import jalview.xml.binding.uniprot.Entry;
39 import jalview.xml.binding.uniprot.FeatureType;
40 import jalview.xml.binding.uniprot.LocationType;
41 import jalview.xml.binding.uniprot.PositionType;
42 import jalview.xml.binding.uniprot.PropertyType;
43
44 import java.io.InputStream;
45 import java.net.HttpURLConnection;
46 import java.net.URL;
47 import java.util.ArrayList;
48 import java.util.List;
49 import java.util.Vector;
50
51 import javax.xml.bind.JAXBContext;
52 import javax.xml.bind.JAXBElement;
53 import javax.xml.bind.JAXBException;
54 import javax.xml.stream.FactoryConfigurationError;
55 import javax.xml.stream.XMLInputFactory;
56 import javax.xml.stream.XMLStreamException;
57 import javax.xml.stream.XMLStreamReader;
58
59 import com.stevesoft.pat.Regex;
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
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     return new Regex("([A-Z]+[0-9]+[A-Z0-9]+|[A-Z0-9]+_[A-Z0-9]+)");
108   }
109
110   /*
111    * (non-Javadoc)
112    * 
113    * @see jalview.ws.DbSourceProxy#getDbSource()
114    */
115   @Override
116   public String getDbSource()
117   {
118     return DBRefSource.UNIPROT;
119   }
120
121   /*
122    * (non-Javadoc)
123    * 
124    * @see jalview.ws.DbSourceProxy#getDbVersion()
125    */
126   @Override
127   public String getDbVersion()
128   {
129     return "0"; // we really don't know what version we're on.
130   }
131
132   /*
133    * (non-Javadoc)
134    * 
135    * @see jalview.ws.DbSourceProxy#getSequenceRecords(java.lang.String[])
136    */
137   @Override
138   public AlignmentI getSequenceRecords(String queries) throws Exception
139   {
140     startQuery();
141     try
142     {
143       queries = queries.toUpperCase(Locale.ROOT).replaceAll(
144               "(UNIPROT\\|?|UNIPROT_|UNIREF\\d+_|UNIREF\\d+\\|?)", "");
145       AlignmentI al = null;
146
147       String downloadstring = getDomain() + "/uniprot/" + queries
148               + ".xml";
149
150       URL url = new URL(downloadstring);
151       HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
152       // anything other than 200 means we don't have data
153       // TODO: JAL-3882 reuse the EnsemblRestClient's fair 
154       // use/backoff logic to retry when the server tells us to go away
155       if (urlconn.getResponseCode() == 200)
156       {
157         InputStream istr = urlconn.getInputStream();
158         List<Entry> entries = getUniprotEntries(istr);
159         if (entries != null)
160         {
161           List<SequenceI> seqs = new ArrayList<>();
162           for (Entry entry : entries)
163           {
164             seqs.add(uniprotEntryToSequence(entry));
165           }
166           al = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
167         }
168       }
169       stopQuery();
170       return al;
171       
172     } catch (Exception e)
173     {
174       throw (e);
175     } finally
176     {
177       stopQuery();
178     }
179   }
180
181   /**
182    * Converts an Entry object (bound from Uniprot XML) to a Jalview Sequence
183    * 
184    * @param entry
185    * @return
186    */
187   SequenceI uniprotEntryToSequence(Entry entry)
188   {
189     String id = getUniprotEntryId(entry);
190     /*
191      * Sequence should not include any whitespace, but JAXB leaves these in
192      */
193     String seqString = entry.getSequence().getValue().replaceAll("\\s*",
194             "");
195
196     SequenceI sequence = new Sequence(id,
197             seqString);
198     sequence.setDescription(getUniprotEntryDescription(entry));
199
200     /*
201      * add a 'self' DBRefEntry for each accession
202      */
203     final String dbVersion = getDbVersion();
204     List<DBRefEntry> dbRefs = new ArrayList<>();
205     boolean canonical=true;
206     for (String accessionId : entry.getAccession())
207     {
208       DBRefEntry dbRef = new DBRefEntry(DBRefSource.UNIPROT, dbVersion,
209               accessionId,null,canonical);
210       canonical=false;
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 = 
516                   um.unmarshal(streamReader, jalview.xml.binding.uniprot.Uniprot.class);
517       jalview.xml.binding.uniprot.Uniprot uniprot = uniprotElement.getValue();
518       
519       if (uniprot != null && !uniprot.getEntry().isEmpty())
520       {
521         entries = uniprot.getEntry();
522       }
523     } catch (JAXBException | XMLStreamException
524             | FactoryConfigurationError e)
525     {
526       if (e instanceof javax.xml.bind.UnmarshalException && e.getCause()!=null && e.getCause() instanceof XMLStreamException && e.getCause().getMessage().contains("[row,col]:[1,1]"))
527       {
528         // trying to parse an empty stream
529         return null;
530       }
531       e.printStackTrace();
532     }
533     return entries;
534   }
535 }