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