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));
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, dbVersion,
206 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 + ":" + dbVersion;
245 dbr = new DBRefEntry(DBRefSource.EMBLCDS, version, vrs[0]);
250 && type.toLowerCase(Locale.ROOT).startsWith("ensembl"))
253 String[] vrs = dbref.getId().split("\\.");
254 String version = vrs.length > 1 ? vrs[1]
255 : DBRefSource.UNIPROT + ":" + dbVersion;
256 dbr.setAccessionId(vrs[0]);
257 dbr.setVersion(version);
259 * e.g. Uniprot accession Q9BXM7 has
260 * <dbReference type="Ensembl" id="ENST00000321556">
261 * <molecule id="Q9BXM7-1"/>
262 * <property type="protein sequence ID" value="ENSP00000364204"/>
263 * <property type="gene ID" value="ENSG00000158828"/>
266 String cdsId = getProperty(dbref.getProperty(),
267 "protein sequence ID");
268 if (cdsId != null && cdsId.trim().length() > 0)
271 String[] cdsVrs = cdsId.split("\\.");
272 String cdsVersion = cdsVrs.length > 1 ? cdsVrs[1]
273 : DBRefSource.UNIPROT + ":" + dbVersion;
274 dbr = new DBRefEntry(DBRefSource.ENSEMBL,
275 DBRefSource.UNIPROT + ":" + cdsVersion, cdsVrs[0]);
282 * create features; they have either begin and end, or position, in XML
284 sequence.setPDBId(pdbRefs);
285 if (entry.getFeature() != null)
287 for (FeatureType uf : entry.getFeature())
289 LocationType location = uf.getLocation();
292 if (location.getPosition() != null)
294 start = location.getPosition().getPosition().intValue();
299 start = location.getBegin().getPosition().intValue();
300 end = location.getEnd().getPosition().intValue();
302 SequenceFeature sf = new SequenceFeature(uf.getType(),
303 getDescription(uf), start, end, "Uniprot");
304 sf.setStatus(uf.getStatus());
305 sequence.addSequenceFeature(sf);
308 for (DBRefEntry dbr : dbRefs)
310 sequence.addDBRef(dbr);
316 * A helper method that builds a sequence feature description
321 static String getDescription(FeatureType feature)
323 String orig = feature.getOriginal();
324 List<String> variants = feature.getVariation();
325 StringBuilder sb = new StringBuilder();
328 * append variant in standard format if present
330 * multiple variants are split over lines using <br>
332 boolean asHtml = false;
333 if (orig != null && !orig.isEmpty() && variants != null
334 && !variants.isEmpty())
337 for (String var : variants)
339 // TODO proper HGVS nomenclature for delins structural variations
340 // http://varnomen.hgvs.org/recommendations/protein/variant/delins/
341 // for now we are pragmatic - any orig/variant sequence longer than
342 // three characters is shown with single-character notation rather than
343 // three-letter notation
345 if (orig.length() < 4)
347 for (int c = 0, clen = orig.length(); c < clen; c++)
349 char origchar = orig.charAt(c);
350 String orig3 = ResidueProperties.aa2Triplet.get("" + origchar);
351 sb.append(orig3 == null ? origchar
352 : StringUtils.toSentenceCase(orig3));
360 LocationType location = feature.getLocation();
361 PositionType start = location.getPosition() == null
362 ? location.getBegin()
363 : location.getPosition();
364 sb.append(Integer.toString(start.getPosition().intValue()));
366 if (var.length() < 4)
368 for (int c = 0, clen = var.length(); c < clen; c++)
370 char varchar = var.charAt(c);
371 String var3 = ResidueProperties.aa2Triplet.get("" + varchar);
373 sb.append(var3 != null ? StringUtils.toSentenceCase(var3)
381 if (++p != variants.size())
383 sb.append("<br/> ");
392 String description = feature.getDescription();
393 if (description != null)
395 sb.append(description);
399 sb.insert(0, "<html>");
400 sb.append("</html>");
403 return sb.toString();
407 * A helper method that searches the list of properties for one with the given
408 * key, and if found returns the property value, else returns null
414 static String getProperty(List<PropertyType> properties, String key)
417 if (properties != null)
419 for (PropertyType prop : properties)
421 if (key.equals(prop.getType()))
423 value = prop.getValue();
432 * Extracts xml element entry/protein/recommendedName/fullName
437 static String getUniprotEntryDescription(Entry entry)
440 if (entry.getProtein() != null
441 && entry.getProtein().getRecommendedName() != null)
443 // fullName is mandatory if recommendedName is present
444 desc = entry.getProtein().getRecommendedName().getFullName()
451 * Constructs a sequence id by concatenating all entry/name elements with '|'
457 static String getUniprotEntryId(Entry entry)
459 StringBuilder name = new StringBuilder(32);
460 for (String n : entry.getName())
462 if (name.length() > 0)
464 name.append(BAR_DELIMITER);
468 return name.toString();
474 * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
477 public boolean isValidReference(String accession)
479 // TODO: make the following a standard validator
480 return (accession == null || accession.length() < 2) ? false
481 : getAccessionValidator().search(accession);
485 * return LDHA_CHICK uniprot entry
488 public String getTestQuery()
494 public String getDbName()
496 return "Uniprot"; // getDbSource();
506 * Reads the reply to the EBI Fetch Uniprot data query, unmarshals it to an
507 * Uniprot object, and returns the enclosed Entry objects, or null on any
513 public List<Entry> getUniprotEntries(InputStream is)
515 List<Entry> entries = null;
518 JAXBContext jc = JAXBContext
519 .newInstance("jalview.xml.binding.uniprot");
520 XMLStreamReader streamReader = XMLInputFactory.newInstance()
521 .createXMLStreamReader(is);
522 javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
523 JAXBElement<jalview.xml.binding.uniprot.Uniprot> uniprotElement = um
524 .unmarshal(streamReader,
525 jalview.xml.binding.uniprot.Uniprot.class);
526 jalview.xml.binding.uniprot.Uniprot uniprot = uniprotElement
529 if (uniprot != null && !uniprot.getEntry().isEmpty())
531 entries = uniprot.getEntry();
533 } catch (JAXBException | XMLStreamException
534 | FactoryConfigurationError e)
536 if (e instanceof javax.xml.bind.UnmarshalException
537 && e.getCause() != null
538 && e.getCause() instanceof XMLStreamException
539 && e.getCause().getMessage().contains("[row,col]:[1,1]"))
541 // trying to parse an empty stream