JAL-3438 spotless for 2.11.2.0
[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 + ".xml";
148
149       URL url = new URL(downloadstring);
150       HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
151       // anything other than 200 means we don't have data
152       // TODO: JAL-3882 reuse the EnsemblRestClient's fair
153       // use/backoff logic to retry when the server tells us to go away
154       if (urlconn.getResponseCode() == 200)
155       {
156         InputStream istr = urlconn.getInputStream();
157         List<Entry> entries = getUniprotEntries(istr);
158         if (entries != null)
159         {
160           List<SequenceI> seqs = new ArrayList<>();
161           for (Entry entry : entries)
162           {
163             seqs.add(uniprotEntryToSequence(entry));
164           }
165           al = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
166         }
167       }
168       stopQuery();
169       return al;
170
171     } catch (Exception e)
172     {
173       throw (e);
174     } finally
175     {
176       stopQuery();
177     }
178   }
179
180   /**
181    * Converts an Entry object (bound from Uniprot XML) to a Jalview Sequence
182    * 
183    * @param entry
184    * @return
185    */
186   SequenceI uniprotEntryToSequence(Entry entry)
187   {
188     String id = getUniprotEntryId(entry);
189     /*
190      * Sequence should not include any whitespace, but JAXB leaves these in
191      */
192     String seqString = entry.getSequence().getValue().replaceAll("\\s*",
193             "");
194
195     SequenceI sequence = new Sequence(id, seqString);
196     sequence.setDescription(getUniprotEntryDescription(entry));
197
198     /*
199      * add a 'self' DBRefEntry for each accession
200      */
201     final String dbVersion = getDbVersion();
202     List<DBRefEntry> dbRefs = new ArrayList<>();
203     boolean canonical = true;
204     for (String accessionId : entry.getAccession())
205     {
206       DBRefEntry dbRef = new DBRefEntry(DBRefSource.UNIPROT, dbVersion,
207               accessionId, null, canonical);
208       canonical = false;
209       dbRefs.add(dbRef);
210     }
211
212     /*
213      * add a DBRefEntry for each dbReference element in the XML;
214      * also add a PDBEntry if type="PDB";
215      * also add an EMBLCDS dbref if protein sequence id is given
216      * also add an Ensembl dbref " " " " " "
217      */
218     Vector<PDBEntry> pdbRefs = new Vector<>();
219     for (DbReferenceType dbref : entry.getDbReference())
220     {
221       String type = dbref.getType();
222       DBRefEntry dbr = new DBRefEntry(type,
223               DBRefSource.UNIPROT + ":" + dbVersion, dbref.getId());
224       dbRefs.add(dbr);
225       if ("PDB".equals(type))
226       {
227         pdbRefs.add(new PDBEntry(dbr));
228       }
229       if ("EMBL".equals(type))
230       {
231         /*
232          * e.g. Uniprot accession Q9BXM7 has
233          * <dbReference type="EMBL" id="M19359">
234          *   <property type="protein sequence ID" value="AAA40981.1"/>
235          *   <property type="molecule type" value="Genomic_DNA"/>
236          * </dbReference> 
237          */
238         String cdsId = getProperty(dbref.getProperty(),
239                 "protein sequence ID");
240         if (cdsId != null && cdsId.trim().length() > 0)
241         {
242           // remove version
243           String[] vrs = cdsId.split("\\.");
244           String version = vrs.length > 1 ? vrs[1]
245                   : DBRefSource.UNIPROT + ":" + dbVersion;
246           dbr = new DBRefEntry(DBRefSource.EMBLCDS, version, vrs[0]);
247           dbRefs.add(dbr);
248         }
249       }
250       if ("Ensembl".equals(type))
251       {
252         /*
253          * e.g. Uniprot accession Q9BXM7 has
254          * <dbReference type="Ensembl" id="ENST00000321556">
255          *   <molecule id="Q9BXM7-1"/>
256          *   <property type="protein sequence ID" value="ENSP00000364204"/>
257          *   <property type="gene ID" value="ENSG00000158828"/>
258          * </dbReference> 
259          */
260         String cdsId = getProperty(dbref.getProperty(),
261                 "protein sequence ID");
262         if (cdsId != null && cdsId.trim().length() > 0)
263         {
264           dbr = new DBRefEntry(DBRefSource.ENSEMBL,
265                   DBRefSource.UNIPROT + ":" + dbVersion, cdsId.trim());
266           dbRefs.add(dbr);
267         }
268       }
269     }
270
271     /*
272      * create features; they have either begin and end, or position, in XML
273      */
274     sequence.setPDBId(pdbRefs);
275     if (entry.getFeature() != null)
276     {
277       for (FeatureType uf : entry.getFeature())
278       {
279         LocationType location = uf.getLocation();
280         int start = 0;
281         int end = 0;
282         if (location.getPosition() != null)
283         {
284           start = location.getPosition().getPosition().intValue();
285           end = start;
286         }
287         else
288         {
289           start = location.getBegin().getPosition().intValue();
290           end = location.getEnd().getPosition().intValue();
291         }
292         SequenceFeature sf = new SequenceFeature(uf.getType(),
293                 getDescription(uf), start, end, "Uniprot");
294         sf.setStatus(uf.getStatus());
295         sequence.addSequenceFeature(sf);
296       }
297     }
298     for (DBRefEntry dbr : dbRefs)
299     {
300       sequence.addDBRef(dbr);
301     }
302     return sequence;
303   }
304
305   /**
306    * A helper method that builds a sequence feature description
307    * 
308    * @param feature
309    * @return
310    */
311   static String getDescription(FeatureType feature)
312   {
313     String orig = feature.getOriginal();
314     List<String> variants = feature.getVariation();
315     StringBuilder sb = new StringBuilder();
316
317     /*
318      * append variant in standard format if present
319      * e.g. p.Arg59Lys
320      * multiple variants are split over lines using <br>
321      */
322     boolean asHtml = false;
323     if (orig != null && !orig.isEmpty() && variants != null
324             && !variants.isEmpty())
325     {
326       int p = 0;
327       for (String var : variants)
328       {
329         // TODO proper HGVS nomenclature for delins structural variations
330         // http://varnomen.hgvs.org/recommendations/protein/variant/delins/
331         // for now we are pragmatic - any orig/variant sequence longer than
332         // three characters is shown with single-character notation rather than
333         // three-letter notation
334         sb.append("p.");
335         if (orig.length() < 4)
336         {
337           for (int c = 0, clen = orig.length(); c < clen; c++)
338           {
339             char origchar = orig.charAt(c);
340             String orig3 = ResidueProperties.aa2Triplet.get("" + origchar);
341             sb.append(orig3 == null ? origchar
342                     : StringUtils.toSentenceCase(orig3));
343           }
344         }
345         else
346         {
347           sb.append(orig);
348         }
349
350         LocationType location = feature.getLocation();
351         PositionType start = location.getPosition() == null
352                 ? location.getBegin()
353                 : location.getPosition();
354         sb.append(Integer.toString(start.getPosition().intValue()));
355
356         if (var.length() < 4)
357         {
358           for (int c = 0, clen = var.length(); c < clen; c++)
359           {
360             char varchar = var.charAt(c);
361             String var3 = ResidueProperties.aa2Triplet.get("" + varchar);
362
363             sb.append(var3 != null ? StringUtils.toSentenceCase(var3)
364                     : "" + varchar);
365           }
366         }
367         else
368         {
369           sb.append(var);
370         }
371         if (++p != variants.size())
372         {
373           sb.append("<br/>&nbsp;&nbsp;");
374           asHtml = true;
375         }
376         else
377         {
378           sb.append(" ");
379         }
380       }
381     }
382     String description = feature.getDescription();
383     if (description != null)
384     {
385       sb.append(description);
386     }
387     if (asHtml)
388     {
389       sb.insert(0, "<html>");
390       sb.append("</html>");
391     }
392
393     return sb.toString();
394   }
395
396   /**
397    * A helper method that searches the list of properties for one with the given
398    * key, and if found returns the property value, else returns null
399    * 
400    * @param properties
401    * @param key
402    * @return
403    */
404   static String getProperty(List<PropertyType> properties, String key)
405   {
406     String value = null;
407     if (properties != null)
408     {
409       for (PropertyType prop : properties)
410       {
411         if (key.equals(prop.getType()))
412         {
413           value = prop.getValue();
414           break;
415         }
416       }
417     }
418     return value;
419   }
420
421   /**
422    * Extracts xml element entry/protein/recommendedName/fullName
423    * 
424    * @param entry
425    * @return
426    */
427   static String getUniprotEntryDescription(Entry entry)
428   {
429     String desc = "";
430     if (entry.getProtein() != null
431             && entry.getProtein().getRecommendedName() != null)
432     {
433       // fullName is mandatory if recommendedName is present
434       desc = entry.getProtein().getRecommendedName().getFullName()
435               .getValue();
436     }
437     return desc;
438   }
439
440   /**
441    * Constructs a sequence id by concatenating all entry/name elements with '|'
442    * separator
443    * 
444    * @param entry
445    * @return
446    */
447   static String getUniprotEntryId(Entry entry)
448   {
449     StringBuilder name = new StringBuilder(32);
450     for (String n : entry.getName())
451     {
452       if (name.length() > 0)
453       {
454         name.append(BAR_DELIMITER);
455       }
456       name.append(n);
457     }
458     return name.toString();
459   }
460
461   /*
462    * (non-Javadoc)
463    * 
464    * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
465    */
466   @Override
467   public boolean isValidReference(String accession)
468   {
469     // TODO: make the following a standard validator
470     return (accession == null || accession.length() < 2) ? false
471             : getAccessionValidator().search(accession);
472   }
473
474   /**
475    * return LDHA_CHICK uniprot entry
476    */
477   @Override
478   public String getTestQuery()
479   {
480     return "P00340";
481   }
482
483   @Override
484   public String getDbName()
485   {
486     return "Uniprot"; // getDbSource();
487   }
488
489   @Override
490   public int getTier()
491   {
492     return 0;
493   }
494
495   /**
496    * Reads the reply to the EBI Fetch Uniprot data query, unmarshals it to an
497    * Uniprot object, and returns the enclosed Entry objects, or null on any
498    * failure
499    * 
500    * @param is
501    * @return
502    */
503   public List<Entry> getUniprotEntries(InputStream is)
504   {
505     List<Entry> entries = null;
506     try
507     {
508       JAXBContext jc = JAXBContext
509               .newInstance("jalview.xml.binding.uniprot");
510       XMLStreamReader streamReader = XMLInputFactory.newInstance()
511               .createXMLStreamReader(is);
512       javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
513       JAXBElement<jalview.xml.binding.uniprot.Uniprot> uniprotElement = um
514               .unmarshal(streamReader,
515                       jalview.xml.binding.uniprot.Uniprot.class);
516       jalview.xml.binding.uniprot.Uniprot uniprot = uniprotElement
517               .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
527               && e.getCause() != null
528               && e.getCause() instanceof XMLStreamException
529               && e.getCause().getMessage().contains("[row,col]:[1,1]"))
530       {
531         // trying to parse an empty stream
532         return null;
533       }
534       e.printStackTrace();
535     }
536     return entries;
537   }
538 }