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.Platform;
52 import jalview.util.StringUtils;
53 import jalview.ws.seqfetcher.DbSourceProxyImpl;
54 import jalview.xml.binding.uniprot.DbReferenceType;
55 import jalview.xml.binding.uniprot.Entry;
56 import jalview.xml.binding.uniprot.FeatureType;
57 import jalview.xml.binding.uniprot.LocationType;
58 import jalview.xml.binding.uniprot.PositionType;
59 import jalview.xml.binding.uniprot.PropertyType;
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)
69 public class Uniprot extends DbSourceProxyImpl
71 private static final String DEFAULT_UNIPROT_DOMAIN = "https://www.uniprot.org";
73 private static final String BAR_DELIMITER = "|";
74 private static Regex ACCESSION_REGEX;
84 private String getDomain()
86 return Cache.getDefault("UNIPROT_DOMAIN", DEFAULT_UNIPROT_DOMAIN);
92 * @see jalview.ws.DbSourceProxy#getAccessionSeparator()
95 public String getAccessionSeparator()
103 * @see jalview.ws.DbSourceProxy#getAccessionValidator()
106 public Regex getAccessionValidator()
108 if (ACCESSION_REGEX == null)
110 ACCESSION_REGEX = Platform
111 .newRegex("([A-Z]+[0-9]+[A-Z0-9]+|[A-Z0-9]+_[A-Z0-9]+)");
113 return ACCESSION_REGEX;
119 * @see jalview.ws.DbSourceProxy#getDbSource()
122 public String getDbSource()
124 return DBRefSource.UNIPROT;
130 * @see jalview.ws.DbSourceProxy#getDbVersion()
133 public String getDbVersion()
135 return "0"; // we really don't know what version we're on.
141 * @see jalview.ws.DbSourceProxy#getSequenceRecords(java.lang.String[])
144 public AlignmentI getSequenceRecords(String queries) throws Exception
149 queries = queries.toUpperCase(Locale.ROOT).replaceAll(
150 "(UNIPROT\\|?|UNIPROT_|UNIREF\\d+_|UNIREF\\d+\\|?)", "");
151 AlignmentI al = null;
153 String downloadstring = getDomain() + "/uniprot/" + queries + ".xml";
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)
162 InputStream istr = urlconn.getInputStream();
163 List<Entry> entries = getUniprotEntries(istr);
166 List<SequenceI> seqs = new ArrayList<>();
167 for (Entry entry : entries)
169 seqs.add(uniprotEntryToSequence(entry));
171 al = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
178 } catch (Exception e)
188 * Converts an Entry object (bound from Uniprot XML) to a Jalview Sequence
193 SequenceI uniprotEntryToSequence(Entry entry)
195 String id = getUniprotEntryId(entry);
197 * Sequence should not include any whitespace, but JAXB leaves these in
199 String seqString = entry.getSequence().getValue().replaceAll("\\s*",
202 SequenceI sequence = new Sequence(id, seqString);
203 sequence.setDescription(getUniprotEntryDescription(entry));
204 final String uniprotRecordVersion = "" + entry.getVersion();
206 * add a 'self' DBRefEntry for each accession
208 final String dbVersion = getDbVersion();
209 List<DBRefEntry> dbRefs = new ArrayList<>();
210 boolean canonical = true;
211 for (String accessionId : entry.getAccession())
213 DBRefEntry dbRef = new DBRefEntry(DBRefSource.UNIPROT,
214 uniprotRecordVersion, accessionId, null, canonical);
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 " " " " " "
225 Vector<PDBEntry> pdbRefs = new Vector<>();
226 for (DbReferenceType dbref : entry.getDbReference())
228 String type = dbref.getType();
229 DBRefEntry dbr = new DBRefEntry(type,
230 DBRefSource.UNIPROT + ":" + dbVersion, dbref.getId());
232 if ("PDB".equals(type))
234 pdbRefs.add(new PDBEntry(dbr));
236 if ("EMBL".equals(type))
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"/>
245 String cdsId = getProperty(dbref.getProperty(),
246 "protein sequence ID");
247 if (cdsId != null && cdsId.trim().length() > 0)
250 String[] vrs = cdsId.split("\\.");
251 String version = vrs.length > 1 ? vrs[1]
252 : DBRefSource.UNIPROT + ":" + uniprotRecordVersion;
253 dbr = new DBRefEntry(DBRefSource.EMBLCDS, version, vrs[0]);
254 // TODO: process VARIANT features to allow EMBLCDS record's product to
256 dbr.setCanonical(true);
260 // from 2.11.2.6 - probably see a conflict here
262 && type.toLowerCase(Locale.ROOT).startsWith("ensembl"))
265 String[] vrs = dbref.getId().split("\\.");
266 String version = vrs.length > 1 ? vrs[1]
267 : DBRefSource.UNIPROT + ":" + uniprotRecordVersion;
268 dbr.setAccessionId(vrs[0]);
269 dbr.setVersion(version);
271 * e.g. Uniprot accession Q9BXM7 has
272 * <dbReference type="Ensembl" id="ENST00000321556">
273 * <molecule id="Q9BXM7-1"/>
274 * <property type="protein sequence ID" value="ENSP00000364204"/>
275 * <property type="gene ID" value="ENSG00000158828"/>
278 String cdsId = getProperty(dbref.getProperty(),
279 "protein sequence ID");
280 if (cdsId != null && cdsId.trim().length() > 0)
283 String[] cdsVrs = cdsId.split("\\.");
284 String cdsVersion = cdsVrs.length > 1 ? cdsVrs[1]
285 : DBRefSource.UNIPROT + ":" + uniprotRecordVersion;
286 dbr = new DBRefEntry(DBRefSource.ENSEMBL,
287 DBRefSource.UNIPROT + ":" + cdsVersion, cdsVrs[0]);
294 * create features; they have either begin and end, or position, in XML
296 sequence.setPDBId(pdbRefs);
297 if (entry.getFeature() != null)
299 for (FeatureType uf : entry.getFeature())
301 LocationType location = uf.getLocation();
304 if (location.getPosition() != null)
306 start = location.getPosition().getPosition().intValue();
311 start = location.getBegin().getPosition().intValue();
312 end = location.getEnd().getPosition().intValue();
314 SequenceFeature sf = new SequenceFeature(uf.getType(),
315 getDescription(uf), start, end, "Uniprot");
316 sf.setStatus(uf.getStatus());
317 sequence.addSequenceFeature(sf);
320 for (DBRefEntry dbr : dbRefs)
322 sequence.addDBRef(dbr);
328 * A helper method that builds a sequence feature description
333 static String getDescription(FeatureType feature)
335 String orig = feature.getOriginal();
336 List<String> variants = feature.getVariation();
337 StringBuilder sb = new StringBuilder();
340 * append variant in standard format if present
342 * multiple variants are split over lines using <br>
344 boolean asHtml = false;
345 if (orig != null && !orig.isEmpty() && variants != null
346 && !variants.isEmpty())
349 for (String var : variants)
351 // TODO proper HGVS nomenclature for delins structural variations
352 // http://varnomen.hgvs.org/recommendations/protein/variant/delins/
353 // for now we are pragmatic - any orig/variant sequence longer than
354 // three characters is shown with single-character notation rather than
355 // three-letter notation
357 if (orig.length() < 4)
359 for (int c = 0, clen = orig.length(); c < clen; c++)
361 char origchar = orig.charAt(c);
362 String orig3 = ResidueProperties.aa2Triplet.get("" + origchar);
363 sb.append(orig3 == null ? origchar
364 : StringUtils.toSentenceCase(orig3));
372 LocationType location = feature.getLocation();
373 PositionType start = location.getPosition() == null
374 ? location.getBegin()
375 : location.getPosition();
376 sb.append(Integer.toString(start.getPosition().intValue()));
378 if (var.length() < 4)
380 for (int c = 0, clen = var.length(); c < clen; c++)
382 char varchar = var.charAt(c);
383 String var3 = ResidueProperties.aa2Triplet.get("" + varchar);
385 sb.append(var3 != null ? StringUtils.toSentenceCase(var3)
393 if (++p != variants.size())
395 sb.append("<br/> ");
404 String description = feature.getDescription();
405 if (description != null)
407 sb.append(description);
411 sb.insert(0, "<html>");
412 sb.append("</html>");
415 return sb.toString();
419 * A helper method that searches the list of properties for one with the given
420 * key, and if found returns the property value, else returns null
426 static String getProperty(List<PropertyType> properties, String key)
429 if (properties != null)
431 for (PropertyType prop : properties)
433 if (key.equals(prop.getType()))
435 value = prop.getValue();
444 * Extracts xml element entry/protein/recommendedName/fullName
449 static String getUniprotEntryDescription(Entry entry)
452 if (entry.getProtein() != null
453 && entry.getProtein().getRecommendedName() != null)
455 // fullName is mandatory if recommendedName is present
456 desc = entry.getProtein().getRecommendedName().getFullName()
463 * Constructs a sequence id by concatenating all entry/name elements with '|'
469 static String getUniprotEntryId(Entry entry)
471 StringBuilder name = new StringBuilder(32);
472 for (String n : entry.getName())
474 if (name.length() > 0)
476 name.append(BAR_DELIMITER);
480 return name.toString();
486 * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
489 public boolean isValidReference(String accession)
491 // TODO: make the following a standard validator
492 return (accession == null || accession.length() < 2) ? false
493 : getAccessionValidator().search(accession);
497 * return LDHA_CHICK uniprot entry
500 public String getTestQuery()
506 public String getDbName()
508 return "Uniprot"; // getDbSource();
518 * Reads the reply to the EBI Fetch Uniprot data query, unmarshals it to an
519 * Uniprot object, and returns the enclosed Entry objects, or null on any
525 public List<Entry> getUniprotEntries(InputStream is)
527 List<Entry> entries = null;
530 JAXBContext jc = JAXBContext
531 .newInstance("jalview.xml.binding.uniprot");
532 XMLStreamReader streamReader = XMLInputFactory.newInstance()
533 .createXMLStreamReader(is);
534 javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
535 JAXBElement<jalview.xml.binding.uniprot.Uniprot> uniprotElement = um
536 .unmarshal(streamReader,
537 jalview.xml.binding.uniprot.Uniprot.class);
538 jalview.xml.binding.uniprot.Uniprot uniprot = uniprotElement
541 if (uniprot != null && !uniprot.getEntry().isEmpty())
543 entries = uniprot.getEntry();
545 } catch (JAXBException | XMLStreamException
546 | FactoryConfigurationError e)
548 if (e instanceof javax.xml.bind.UnmarshalException
549 && e.getCause() != null
550 && e.getCause() instanceof XMLStreamException
551 && e.getCause().getMessage().contains("[row,col]:[1,1]"))
553 // trying to parse an empty stream