2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
21 package jalview.ws.dbsources;
23 import java.io.InputStream;
24 import java.net.HttpURLConnection;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Locale;
29 import java.util.Vector;
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;
39 import com.stevesoft.pat.Regex;
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;
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)
68 public class Uniprot extends DbSourceProxyImpl
70 private static final String DEFAULT_UNIPROT_DOMAIN = "https://www.uniprot.org";
72 private static final String BAR_DELIMITER = "|";
82 private String getDomain()
84 return Cache.getDefault("UNIPROT_DOMAIN", DEFAULT_UNIPROT_DOMAIN);
90 * @see jalview.ws.DbSourceProxy#getAccessionSeparator()
93 public String getAccessionSeparator()
101 * @see jalview.ws.DbSourceProxy#getAccessionValidator()
104 public Regex getAccessionValidator()
106 return new Regex("([A-Z]+[0-9]+[A-Z0-9]+|[A-Z0-9]+_[A-Z0-9]+)");
112 * @see jalview.ws.DbSourceProxy#getDbSource()
115 public String getDbSource()
117 return DBRefSource.UNIPROT;
123 * @see jalview.ws.DbSourceProxy#getDbVersion()
126 public String getDbVersion()
128 return "0"; // we really don't know what version we're on.
134 * @see jalview.ws.DbSourceProxy#getSequenceRecords(java.lang.String[])
137 public AlignmentI getSequenceRecords(String queries) throws Exception
142 queries = queries.toUpperCase(Locale.ROOT).replaceAll(
143 "(UNIPROT\\|?|UNIPROT_|UNIREF\\d+_|UNIREF\\d+\\|?)", "");
144 AlignmentI al = null;
146 String downloadstring = getDomain() + "/uniprot/" + queries + ".xml";
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)
155 InputStream istr = urlconn.getInputStream();
156 List<Entry> entries = getUniprotEntries(istr);
159 List<SequenceI> seqs = new ArrayList<>();
160 for (Entry entry : entries)
162 seqs.add(uniprotEntryToSequence(entry));
164 al = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
170 } catch (Exception e)
180 * Converts an Entry object (bound from Uniprot XML) to a Jalview Sequence
185 SequenceI uniprotEntryToSequence(Entry entry)
187 String id = getUniprotEntryId(entry);
189 * Sequence should not include any whitespace, but JAXB leaves these in
191 String seqString = entry.getSequence().getValue().replaceAll("\\s*",
194 SequenceI sequence = new Sequence(id, seqString);
195 sequence.setDescription(getUniprotEntryDescription(entry));
196 final String uniprotRecordVersion = "" + entry.getVersion();
198 * add a 'self' DBRefEntry for each accession
200 final String dbVersion = getDbVersion();
201 List<DBRefEntry> dbRefs = new ArrayList<>();
202 boolean canonical = true;
203 for (String accessionId : entry.getAccession())
205 DBRefEntry dbRef = new DBRefEntry(DBRefSource.UNIPROT,
206 uniprotRecordVersion, accessionId, null, canonical);
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 " " " " " "
217 Vector<PDBEntry> pdbRefs = new Vector<>();
218 for (DbReferenceType dbref : entry.getDbReference())
220 String type = dbref.getType();
221 DBRefEntry dbr = new DBRefEntry(type,
222 DBRefSource.UNIPROT + ":" + dbVersion, dbref.getId());
224 if ("PDB".equals(type))
226 pdbRefs.add(new PDBEntry(dbr));
228 if ("EMBL".equals(type))
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"/>
237 String cdsId = getProperty(dbref.getProperty(),
238 "protein sequence ID");
239 if (cdsId != null && cdsId.trim().length() > 0)
242 String[] vrs = cdsId.split("\\.");
243 String version = vrs.length > 1 ? vrs[1]
244 : DBRefSource.UNIPROT + ":" + uniprotRecordVersion;
245 dbr = new DBRefEntry(DBRefSource.EMBLCDS, version, vrs[0]);
246 // TODO: process VARIANT features to allow EMBLCDS record's product to
248 dbr.setCanonical(true);
253 && type.toLowerCase(Locale.ROOT).startsWith("ensembl"))
256 String[] vrs = dbref.getId().split("\\.");
257 String version = vrs.length > 1 ? vrs[1]
258 : DBRefSource.UNIPROT + ":" + uniprotRecordVersion;
259 dbr.setAccessionId(vrs[0]);
260 dbr.setVersion(version);
262 * e.g. Uniprot accession Q9BXM7 has
263 * <dbReference type="Ensembl" id="ENST00000321556">
264 * <molecule id="Q9BXM7-1"/>
265 * <property type="protein sequence ID" value="ENSP00000364204"/>
266 * <property type="gene ID" value="ENSG00000158828"/>
269 String cdsId = getProperty(dbref.getProperty(),
270 "protein sequence ID");
271 if (cdsId != null && cdsId.trim().length() > 0)
274 String[] cdsVrs = cdsId.split("\\.");
275 String cdsVersion = cdsVrs.length > 1 ? cdsVrs[1]
276 : DBRefSource.UNIPROT + ":" + uniprotRecordVersion;
277 dbr = new DBRefEntry(DBRefSource.ENSEMBL,
278 DBRefSource.UNIPROT + ":" + cdsVersion, cdsVrs[0]);
285 * create features; they have either begin and end, or position, in XML
287 sequence.setPDBId(pdbRefs);
288 if (entry.getFeature() != null)
290 for (FeatureType uf : entry.getFeature())
292 LocationType location = uf.getLocation();
295 if (location.getPosition() != null)
297 start = location.getPosition().getPosition().intValue();
302 start = location.getBegin().getPosition().intValue();
303 end = location.getEnd().getPosition().intValue();
305 SequenceFeature sf = new SequenceFeature(uf.getType(),
306 getDescription(uf), start, end, "Uniprot");
307 sf.setStatus(uf.getStatus());
308 sequence.addSequenceFeature(sf);
311 for (DBRefEntry dbr : dbRefs)
313 sequence.addDBRef(dbr);
319 * A helper method that builds a sequence feature description
324 static String getDescription(FeatureType feature)
326 String orig = feature.getOriginal();
327 List<String> variants = feature.getVariation();
328 StringBuilder sb = new StringBuilder();
331 * append variant in standard format if present
333 * multiple variants are split over lines using <br>
335 boolean asHtml = false;
336 if (orig != null && !orig.isEmpty() && variants != null
337 && !variants.isEmpty())
340 for (String var : variants)
342 // TODO proper HGVS nomenclature for delins structural variations
343 // http://varnomen.hgvs.org/recommendations/protein/variant/delins/
344 // for now we are pragmatic - any orig/variant sequence longer than
345 // three characters is shown with single-character notation rather than
346 // three-letter notation
348 if (orig.length() < 4)
350 for (int c = 0, clen = orig.length(); c < clen; c++)
352 char origchar = orig.charAt(c);
353 String orig3 = ResidueProperties.aa2Triplet.get("" + origchar);
354 sb.append(orig3 == null ? origchar
355 : StringUtils.toSentenceCase(orig3));
363 LocationType location = feature.getLocation();
364 PositionType start = location.getPosition() == null
365 ? location.getBegin()
366 : location.getPosition();
367 sb.append(Integer.toString(start.getPosition().intValue()));
369 if (var.length() < 4)
371 for (int c = 0, clen = var.length(); c < clen; c++)
373 char varchar = var.charAt(c);
374 String var3 = ResidueProperties.aa2Triplet.get("" + varchar);
376 sb.append(var3 != null ? StringUtils.toSentenceCase(var3)
384 if (++p != variants.size())
386 sb.append("<br/> ");
395 String description = feature.getDescription();
396 if (description != null)
398 sb.append(description);
402 sb.insert(0, "<html>");
403 sb.append("</html>");
406 return sb.toString();
410 * A helper method that searches the list of properties for one with the given
411 * key, and if found returns the property value, else returns null
417 static String getProperty(List<PropertyType> properties, String key)
420 if (properties != null)
422 for (PropertyType prop : properties)
424 if (key.equals(prop.getType()))
426 value = prop.getValue();
435 * Extracts xml element entry/protein/recommendedName/fullName
440 static String getUniprotEntryDescription(Entry entry)
443 if (entry.getProtein() != null
444 && entry.getProtein().getRecommendedName() != null)
446 // fullName is mandatory if recommendedName is present
447 desc = entry.getProtein().getRecommendedName().getFullName()
454 * Constructs a sequence id by concatenating all entry/name elements with '|'
460 static String getUniprotEntryId(Entry entry)
462 StringBuilder name = new StringBuilder(32);
463 for (String n : entry.getName())
465 if (name.length() > 0)
467 name.append(BAR_DELIMITER);
471 return name.toString();
477 * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
480 public boolean isValidReference(String accession)
482 // TODO: make the following a standard validator
483 return (accession == null || accession.length() < 2) ? false
484 : getAccessionValidator().search(accession);
488 * return LDHA_CHICK uniprot entry
491 public String getTestQuery()
497 public String getDbName()
499 return "Uniprot"; // getDbSource();
509 * Reads the reply to the EBI Fetch Uniprot data query, unmarshals it to an
510 * Uniprot object, and returns the enclosed Entry objects, or null on any
516 public List<Entry> getUniprotEntries(InputStream is)
518 List<Entry> entries = null;
521 JAXBContext jc = JAXBContext
522 .newInstance("jalview.xml.binding.uniprot");
523 XMLStreamReader streamReader = XMLInputFactory.newInstance()
524 .createXMLStreamReader(is);
525 javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
526 JAXBElement<jalview.xml.binding.uniprot.Uniprot> uniprotElement = um
527 .unmarshal(streamReader,
528 jalview.xml.binding.uniprot.Uniprot.class);
529 jalview.xml.binding.uniprot.Uniprot uniprot = uniprotElement
532 if (uniprot != null && !uniprot.getEntry().isEmpty())
534 entries = uniprot.getEntry();
536 } catch (JAXBException | XMLStreamException
537 | FactoryConfigurationError e)
539 if (e instanceof javax.xml.bind.UnmarshalException
540 && e.getCause() != null
541 && e.getCause() instanceof XMLStreamException
542 && e.getCause().getMessage().contains("[row,col]:[1,1]"))
544 // trying to parse an empty stream