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.bin.Console;
43 import jalview.datamodel.Alignment;
44 import jalview.datamodel.AlignmentI;
45 import jalview.datamodel.DBRefEntry;
46 import jalview.datamodel.DBRefSource;
47 import jalview.datamodel.PDBEntry;
48 import jalview.datamodel.Sequence;
49 import jalview.datamodel.SequenceFeature;
50 import jalview.datamodel.SequenceI;
51 import jalview.schemes.ResidueProperties;
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://rest.uniprot.org";
73 private static final String BAR_DELIMITER = "|";
83 private String getDomain()
85 return Cache.getDefault("UNIPROT_DOMAIN", DEFAULT_UNIPROT_DOMAIN);
91 * @see jalview.ws.DbSourceProxy#getAccessionSeparator()
94 public String getAccessionSeparator()
102 * @see jalview.ws.DbSourceProxy#getAccessionValidator()
105 public Regex getAccessionValidator()
107 return new Regex("([A-Z]+[0-9]+[A-Z0-9]+|[A-Z0-9]+_[A-Z0-9]+)");
113 * @see jalview.ws.DbSourceProxy#getDbSource()
116 public String getDbSource()
118 return DBRefSource.UNIPROT;
124 * @see jalview.ws.DbSourceProxy#getDbVersion()
127 public String getDbVersion()
129 return "0"; // we really don't know what version we're on.
135 * @see jalview.ws.DbSourceProxy#getSequenceRecords(java.lang.String[])
138 public AlignmentI getSequenceRecords(String queries) throws Exception
143 queries = queries.toUpperCase(Locale.ROOT).replaceAll(
144 "(UNIPROT\\|?|UNIPROT_|UNIREF\\d+_|UNIREF\\d+\\|?)", "");
145 AlignmentI al = null;
147 String downloadstring = getDomain() + "/uniprotkb/" + queries + ".xml";
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)
156 InputStream istr = urlconn.getInputStream();
157 List<Entry> entries = getUniprotEntries(istr);
160 List<SequenceI> seqs = new ArrayList<>();
161 for (Entry entry : entries)
163 seqs.add(uniprotEntryToSequence(entry));
165 al = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
171 } catch (Exception e)
181 * Converts an Entry object (bound from Uniprot XML) to a Jalview Sequence
186 SequenceI uniprotEntryToSequence(Entry entry)
188 String id = getUniprotEntryId(entry);
190 * Sequence should not include any whitespace, but JAXB leaves these in
192 String seqString = entry.getSequence().getValue().replaceAll("\\s*",
195 SequenceI sequence = new Sequence(id, seqString);
196 sequence.setDescription(getUniprotEntryDescription(entry));
197 final String uniprotRecordVersion = "" + entry.getVersion();
199 * add a 'self' DBRefEntry for each accession
201 final String dbVersion = getDbVersion();
202 List<DBRefEntry> dbRefs = new ArrayList<>();
203 boolean canonical = true;
204 for (String accessionId : entry.getAccession())
206 DBRefEntry dbRef = new DBRefEntry(DBRefSource.UNIPROT,
207 uniprotRecordVersion, accessionId, null, canonical);
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 " " " " " "
218 Vector<PDBEntry> pdbRefs = new Vector<>();
219 for (DbReferenceType dbref : entry.getDbReference())
221 String type = dbref.getType();
222 DBRefEntry dbr = new DBRefEntry(type,
223 DBRefSource.UNIPROT + ":" + dbVersion, dbref.getId());
225 if ("PDB".equals(type))
227 pdbRefs.add(new PDBEntry(dbr));
229 if ("EMBL".equals(type))
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"/>
238 String cdsId = getProperty(dbref.getProperty(),
239 "protein sequence ID");
240 if (cdsId != null && cdsId.trim().length() > 0)
243 String[] vrs = cdsId.split("\\.");
244 String version = vrs.length > 1 ? vrs[1]
245 : DBRefSource.UNIPROT + ":" + uniprotRecordVersion;
246 dbr = new DBRefEntry(DBRefSource.EMBLCDS, version, vrs[0]);
247 // TODO: process VARIANT features to allow EMBLCDS record's product to
249 dbr.setCanonical(true);
254 && type.toLowerCase(Locale.ROOT).startsWith("ensembl"))
257 String[] vrs = dbref.getId().split("\\.");
258 String version = vrs.length > 1 ? vrs[1]
259 : DBRefSource.UNIPROT + ":" + uniprotRecordVersion;
260 dbr.setAccessionId(vrs[0]);
261 dbr.setVersion(version);
263 * e.g. Uniprot accession Q9BXM7 has
264 * <dbReference type="Ensembl" id="ENST00000321556">
265 * <molecule id="Q9BXM7-1"/>
266 * <property type="protein sequence ID" value="ENSP00000364204"/>
267 * <property type="gene ID" value="ENSG00000158828"/>
270 String cdsId = getProperty(dbref.getProperty(),
271 "protein sequence ID");
272 if (cdsId != null && cdsId.trim().length() > 0)
275 String[] cdsVrs = cdsId.split("\\.");
276 String cdsVersion = cdsVrs.length > 1 ? cdsVrs[1]
277 : DBRefSource.UNIPROT + ":" + uniprotRecordVersion;
278 dbr = new DBRefEntry(DBRefSource.ENSEMBL,
279 DBRefSource.UNIPROT + ":" + cdsVersion, cdsVrs[0]);
286 * create features; they have either begin and end, or position, in XML
288 sequence.setPDBId(pdbRefs);
289 if (entry.getFeature() != null)
291 for (FeatureType uf : entry.getFeature())
293 LocationType location = uf.getLocation();
296 String uncertain_start = null, uncertain_end = null,
297 uncertain_pos = null;
298 if (location.getPosition() != null)
300 if (location.getPosition().getPosition() == null
301 || "unknown".equals(location.getPosition().getStatus()))
304 "Ignoring single position feature with uncertain location "
305 + uf.getType() + ":" + getDescription(uf));
306 uncertain_pos = location.getPosition().getStatus() == null
308 : location.getPosition().getStatus();
312 start = location.getPosition().getPosition().intValue();
318 if (location.getBegin().getPosition() == null)
321 "Setting start position of feature with uncertain start to 1: "
322 + uf.getType() + ":" + getDescription(uf));
323 start = sequence.getStart();
324 uncertain_start = location.getBegin().getStatus();
328 start = location.getBegin().getPosition().intValue();
330 if (location.getEnd().getPosition() == null)
333 "Setting start position of feature with uncertain start to 1: "
334 + uf.getType() + ":" + getDescription(uf));
335 end = sequence.getEnd();
336 uncertain_end = location.getEnd().getStatus();
340 end = location.getEnd().getPosition().intValue();
343 SequenceFeature sf = new SequenceFeature(uf.getType(),
344 getDescription(uf), start, end, "Uniprot");
345 sf.setStatus(uf.getStatus());
346 if (uncertain_end != null)
348 sf.setValue("end_status", uncertain_end);
350 if (uncertain_start != null)
352 sf.setValue("start_status", uncertain_start);
354 if (uncertain_pos != null)
356 sf.setValue("pos_status", uncertain_pos);
358 sequence.addSequenceFeature(sf);
361 for (DBRefEntry dbr : dbRefs)
363 sequence.addDBRef(dbr);
369 * A helper method that builds a sequence feature description
374 static String getDescription(FeatureType feature)
376 String orig = feature.getOriginal();
377 List<String> variants = feature.getVariation();
378 StringBuilder sb = new StringBuilder();
381 * append variant in standard format if present
383 * multiple variants are split over lines using <br>
385 boolean asHtml = false;
386 if (orig != null && !orig.isEmpty() && variants != null
387 && !variants.isEmpty())
390 for (String var : variants)
392 // TODO proper HGVS nomenclature for delins structural variations
393 // http://varnomen.hgvs.org/recommendations/protein/variant/delins/
394 // for now we are pragmatic - any orig/variant sequence longer than
395 // three characters is shown with single-character notation rather than
396 // three-letter notation
398 if (orig.length() < 4)
400 for (int c = 0, clen = orig.length(); c < clen; c++)
402 char origchar = orig.charAt(c);
403 String orig3 = ResidueProperties.aa2Triplet.get("" + origchar);
404 sb.append(orig3 == null ? origchar
405 : StringUtils.toSentenceCase(orig3));
413 LocationType location = feature.getLocation();
414 PositionType start = location.getPosition() == null
415 ? location.getBegin()
416 : location.getPosition();
417 sb.append(Integer.toString(start.getPosition().intValue()));
419 if (var.length() < 4)
421 for (int c = 0, clen = var.length(); c < clen; c++)
423 char varchar = var.charAt(c);
424 String var3 = ResidueProperties.aa2Triplet.get("" + varchar);
426 sb.append(var3 != null ? StringUtils.toSentenceCase(var3)
434 if (++p != variants.size())
436 sb.append("<br/> ");
445 String description = feature.getDescription();
446 if (description != null)
448 sb.append(description);
452 sb.insert(0, "<html>");
453 sb.append("</html>");
456 return sb.toString();
460 * A helper method that searches the list of properties for one with the given
461 * key, and if found returns the property value, else returns null
467 static String getProperty(List<PropertyType> properties, String key)
470 if (properties != null)
472 for (PropertyType prop : properties)
474 if (key.equals(prop.getType()))
476 value = prop.getValue();
485 * Extracts xml element entry/protein/recommendedName/fullName
490 static String getUniprotEntryDescription(Entry entry)
493 if (entry.getProtein() != null
494 && entry.getProtein().getRecommendedName() != null)
496 // fullName is mandatory if recommendedName is present
497 desc = entry.getProtein().getRecommendedName().getFullName()
504 * Constructs a sequence id by concatenating all entry/name elements with '|'
510 static String getUniprotEntryId(Entry entry)
512 StringBuilder name = new StringBuilder(32);
513 for (String n : entry.getName())
515 if (name.length() > 0)
517 name.append(BAR_DELIMITER);
521 return name.toString();
527 * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
530 public boolean isValidReference(String accession)
532 // TODO: make the following a standard validator
533 return (accession == null || accession.length() < 2) ? false
534 : getAccessionValidator().search(accession);
538 * return LDHA_CHICK uniprot entry
541 public String getTestQuery()
547 public String getDbName()
549 return "Uniprot"; // getDbSource();
559 * Reads the reply to the EBI Fetch Uniprot data query, unmarshals it to an
560 * Uniprot object, and returns the enclosed Entry objects, or null on any
566 public List<Entry> getUniprotEntries(InputStream is)
568 List<Entry> entries = null;
571 JAXBContext jc = JAXBContext
572 .newInstance("jalview.xml.binding.uniprot");
573 XMLStreamReader streamReader = XMLInputFactory.newInstance()
574 .createXMLStreamReader(is);
575 javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
576 JAXBElement<jalview.xml.binding.uniprot.Uniprot> uniprotElement = um
577 .unmarshal(streamReader,
578 jalview.xml.binding.uniprot.Uniprot.class);
579 jalview.xml.binding.uniprot.Uniprot uniprot = uniprotElement
582 if (uniprot != null && !uniprot.getEntry().isEmpty())
584 entries = uniprot.getEntry();
586 } catch (JAXBException | XMLStreamException
587 | FactoryConfigurationError e)
589 if (e instanceof javax.xml.bind.UnmarshalException
590 && e.getCause() != null
591 && e.getCause() instanceof XMLStreamException
592 && e.getCause().getMessage().contains("[row,col]:[1,1]"))
594 // trying to parse an empty stream