3a6fed26a5058b2f01db4d40cb4985704a363fd9
[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.Platform;
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   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
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, dbVersion,
214               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 + ":" + dbVersion;
253           dbr = new DBRefEntry(DBRefSource.EMBLCDS, version, vrs[0]);
254           dbRefs.add(dbr);
255         }
256       }
257       // from 2.11.2.6 - probably see a conflict here
258       if (type != null
259               && type.toLowerCase(Locale.ROOT).startsWith("ensembl"))
260       {
261         // remove version
262         String[] vrs = dbref.getId().split("\\.");
263         String version = vrs.length > 1 ? vrs[1]
264                 : DBRefSource.UNIPROT + ":" + dbVersion;
265         dbr.setAccessionId(vrs[0]);
266         dbr.setVersion(version);
267         /*
268          * e.g. Uniprot accession Q9BXM7 has
269          * <dbReference type="Ensembl" id="ENST00000321556">
270          *   <molecule id="Q9BXM7-1"/>
271          *   <property type="protein sequence ID" value="ENSP00000364204"/>
272          *   <property type="gene ID" value="ENSG00000158828"/>
273          * </dbReference> 
274          */
275         String cdsId = getProperty(dbref.getProperty(),
276                 "protein sequence ID");
277         if (cdsId != null && cdsId.trim().length() > 0)
278         {
279           // remove version
280           String[] cdsVrs = cdsId.split("\\.");
281           String cdsVersion = cdsVrs.length > 1 ? cdsVrs[1]
282                   : DBRefSource.UNIPROT + ":" + dbVersion;
283           dbr = new DBRefEntry(DBRefSource.ENSEMBL,
284                   DBRefSource.UNIPROT + ":" + cdsVersion, cdsVrs[0]);
285           dbRefs.add(dbr);
286         }
287       }
288     }
289
290     /*
291      * create features; they have either begin and end, or position, in XML
292      */
293     sequence.setPDBId(pdbRefs);
294     if (entry.getFeature() != null)
295     {
296       for (FeatureType uf : entry.getFeature())
297       {
298         LocationType location = uf.getLocation();
299         int start = 0;
300         int end = 0;
301         if (location.getPosition() != null)
302         {
303           start = location.getPosition().getPosition().intValue();
304           end = start;
305         }
306         else
307         {
308           start = location.getBegin().getPosition().intValue();
309           end = location.getEnd().getPosition().intValue();
310         }
311         SequenceFeature sf = new SequenceFeature(uf.getType(),
312                 getDescription(uf), start, end, "Uniprot");
313         sf.setStatus(uf.getStatus());
314         sequence.addSequenceFeature(sf);
315       }
316     }
317     for (DBRefEntry dbr : dbRefs)
318     {
319       sequence.addDBRef(dbr);
320     }
321     return sequence;
322   }
323
324   /**
325    * A helper method that builds a sequence feature description
326    * 
327    * @param feature
328    * @return
329    */
330   static String getDescription(FeatureType feature)
331   {
332     String orig = feature.getOriginal();
333     List<String> variants = feature.getVariation();
334     StringBuilder sb = new StringBuilder();
335
336     /*
337      * append variant in standard format if present
338      * e.g. p.Arg59Lys
339      * multiple variants are split over lines using <br>
340      */
341     boolean asHtml = false;
342     if (orig != null && !orig.isEmpty() && variants != null
343             && !variants.isEmpty())
344     {
345       int p = 0;
346       for (String var : variants)
347       {
348         // TODO proper HGVS nomenclature for delins structural variations
349         // http://varnomen.hgvs.org/recommendations/protein/variant/delins/
350         // for now we are pragmatic - any orig/variant sequence longer than
351         // three characters is shown with single-character notation rather than
352         // three-letter notation
353         sb.append("p.");
354         if (orig.length() < 4)
355         {
356           for (int c = 0, clen = orig.length(); c < clen; c++)
357           {
358             char origchar = orig.charAt(c);
359             String orig3 = ResidueProperties.aa2Triplet.get("" + origchar);
360             sb.append(orig3 == null ? origchar
361                     : StringUtils.toSentenceCase(orig3));
362           }
363         }
364         else
365         {
366           sb.append(orig);
367         }
368
369         LocationType location = feature.getLocation();
370         PositionType start = location.getPosition() == null
371                 ? location.getBegin()
372                 : location.getPosition();
373         sb.append(Integer.toString(start.getPosition().intValue()));
374
375         if (var.length() < 4)
376         {
377           for (int c = 0, clen = var.length(); c < clen; c++)
378           {
379             char varchar = var.charAt(c);
380             String var3 = ResidueProperties.aa2Triplet.get("" + varchar);
381
382             sb.append(var3 != null ? StringUtils.toSentenceCase(var3)
383                     : "" + varchar);
384           }
385         }
386         else
387         {
388           sb.append(var);
389         }
390         if (++p != variants.size())
391         {
392           sb.append("<br/>&nbsp;&nbsp;");
393           asHtml = true;
394         }
395         else
396         {
397           sb.append(" ");
398         }
399       }
400     }
401     String description = feature.getDescription();
402     if (description != null)
403     {
404       sb.append(description);
405     }
406     if (asHtml)
407     {
408       sb.insert(0, "<html>");
409       sb.append("</html>");
410     }
411
412     return sb.toString();
413   }
414
415   /**
416    * A helper method that searches the list of properties for one with the given
417    * key, and if found returns the property value, else returns null
418    * 
419    * @param properties
420    * @param key
421    * @return
422    */
423   static String getProperty(List<PropertyType> properties, String key)
424   {
425     String value = null;
426     if (properties != null)
427     {
428       for (PropertyType prop : properties)
429       {
430         if (key.equals(prop.getType()))
431         {
432           value = prop.getValue();
433           break;
434         }
435       }
436     }
437     return value;
438   }
439
440   /**
441    * Extracts xml element entry/protein/recommendedName/fullName
442    * 
443    * @param entry
444    * @return
445    */
446   static String getUniprotEntryDescription(Entry entry)
447   {
448     String desc = "";
449     if (entry.getProtein() != null
450             && entry.getProtein().getRecommendedName() != null)
451     {
452       // fullName is mandatory if recommendedName is present
453       desc = entry.getProtein().getRecommendedName().getFullName()
454               .getValue();
455     }
456     return desc;
457   }
458
459   /**
460    * Constructs a sequence id by concatenating all entry/name elements with '|'
461    * separator
462    * 
463    * @param entry
464    * @return
465    */
466   static String getUniprotEntryId(Entry entry)
467   {
468     StringBuilder name = new StringBuilder(32);
469     for (String n : entry.getName())
470     {
471       if (name.length() > 0)
472       {
473         name.append(BAR_DELIMITER);
474       }
475       name.append(n);
476     }
477     return name.toString();
478   }
479
480   /*
481    * (non-Javadoc)
482    * 
483    * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
484    */
485   @Override
486   public boolean isValidReference(String accession)
487   {
488     // TODO: make the following a standard validator
489     return (accession == null || accession.length() < 2) ? false
490             : getAccessionValidator().search(accession);
491   }
492
493   /**
494    * return LDHA_CHICK uniprot entry
495    */
496   @Override
497   public String getTestQuery()
498   {
499     return "P00340";
500   }
501
502   @Override
503   public String getDbName()
504   {
505     return "Uniprot"; // getDbSource();
506   }
507
508   @Override
509   public int getTier()
510   {
511     return 0;
512   }
513
514   /**
515    * Reads the reply to the EBI Fetch Uniprot data query, unmarshals it to an
516    * Uniprot object, and returns the enclosed Entry objects, or null on any
517    * failure
518    * 
519    * @param is
520    * @return
521    */
522   public List<Entry> getUniprotEntries(InputStream is)
523   {
524     List<Entry> entries = null;
525     try
526     {
527       JAXBContext jc = JAXBContext
528               .newInstance("jalview.xml.binding.uniprot");
529       XMLStreamReader streamReader = XMLInputFactory.newInstance()
530               .createXMLStreamReader(is);
531       javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
532       JAXBElement<jalview.xml.binding.uniprot.Uniprot> uniprotElement = um
533               .unmarshal(streamReader,
534                       jalview.xml.binding.uniprot.Uniprot.class);
535       jalview.xml.binding.uniprot.Uniprot uniprot = uniprotElement
536               .getValue();
537
538       if (uniprot != null && !uniprot.getEntry().isEmpty())
539       {
540         entries = uniprot.getEntry();
541       }
542     } catch (JAXBException | XMLStreamException
543             | FactoryConfigurationError e)
544     {
545       if (e instanceof javax.xml.bind.UnmarshalException
546               && e.getCause() != null
547               && e.getCause() instanceof XMLStreamException
548               && e.getCause().getMessage().contains("[row,col]:[1,1]"))
549       {
550         // trying to parse an empty stream
551         return null;
552       }
553       e.printStackTrace();
554     }
555     return entries;
556   }
557 }