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.util.Locale;
24 import jalview.bin.Cache;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.DBRefEntry;
28 import jalview.datamodel.DBRefSource;
29 import jalview.datamodel.PDBEntry;
30 import jalview.datamodel.Sequence;
31 import jalview.datamodel.SequenceFeature;
32 import jalview.datamodel.SequenceI;
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;
44 import java.io.InputStream;
45 import java.net.HttpURLConnection;
47 import java.util.ArrayList;
48 import java.util.List;
49 import java.util.Vector;
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;
59 import com.stevesoft.pat.Regex;
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));
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, dbVersion,
214 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 + ":" + dbVersion;
253 dbr = new DBRefEntry(DBRefSource.EMBLCDS, version, vrs[0]);
257 // from 2.11.2.6 - probably see a conflict here
259 && type.toLowerCase(Locale.ROOT).startsWith("ensembl"))
262 String[] vrs = dbref.getId().split("\\.");
263 String version = vrs.length > 1 ? vrs[1]
264 : DBRefSource.UNIPROT + ":" + dbVersion;
265 dbr.setAccessionId(vrs[0]);
266 dbr.setVersion(version);
268 * e.g. Uniprot accession Q9BXM7 has
269 * <dbReference type="Ensembl" id="ENST00000321556">
270 * <molecule id="Q9BXM7-1"/>
271 * <property type="protein sequence ID" value="ENSP00000364204"/>
272 * <property type="gene ID" value="ENSG00000158828"/>
275 String cdsId = getProperty(dbref.getProperty(),
276 "protein sequence ID");
277 if (cdsId != null && cdsId.trim().length() > 0)
280 String[] cdsVrs = cdsId.split("\\.");
281 String cdsVersion = cdsVrs.length > 1 ? cdsVrs[1]
282 : DBRefSource.UNIPROT + ":" + dbVersion;
283 dbr = new DBRefEntry(DBRefSource.ENSEMBL,
284 DBRefSource.UNIPROT + ":" + cdsVersion, cdsVrs[0]);
291 * create features; they have either begin and end, or position, in XML
293 sequence.setPDBId(pdbRefs);
294 if (entry.getFeature() != null)
296 for (FeatureType uf : entry.getFeature())
298 LocationType location = uf.getLocation();
301 if (location.getPosition() != null)
303 start = location.getPosition().getPosition().intValue();
308 start = location.getBegin().getPosition().intValue();
309 end = location.getEnd().getPosition().intValue();
311 SequenceFeature sf = new SequenceFeature(uf.getType(),
312 getDescription(uf), start, end, "Uniprot");
313 sf.setStatus(uf.getStatus());
314 sequence.addSequenceFeature(sf);
317 for (DBRefEntry dbr : dbRefs)
319 sequence.addDBRef(dbr);
325 * A helper method that builds a sequence feature description
330 static String getDescription(FeatureType feature)
332 String orig = feature.getOriginal();
333 List<String> variants = feature.getVariation();
334 StringBuilder sb = new StringBuilder();
337 * append variant in standard format if present
339 * multiple variants are split over lines using <br>
341 boolean asHtml = false;
342 if (orig != null && !orig.isEmpty() && variants != null
343 && !variants.isEmpty())
346 for (String var : variants)
348 // TODO proper HGVS nomenclature for delins structural variations
349 // http://varnomen.hgvs.org/recommendations/protein/variant/delins/
350 // for now we are pragmatic - any orig/variant sequence longer than
351 // three characters is shown with single-character notation rather than
352 // three-letter notation
354 if (orig.length() < 4)
356 for (int c = 0, clen = orig.length(); c < clen; c++)
358 char origchar = orig.charAt(c);
359 String orig3 = ResidueProperties.aa2Triplet.get("" + origchar);
360 sb.append(orig3 == null ? origchar
361 : StringUtils.toSentenceCase(orig3));
369 LocationType location = feature.getLocation();
370 PositionType start = location.getPosition() == null
371 ? location.getBegin()
372 : location.getPosition();
373 sb.append(Integer.toString(start.getPosition().intValue()));
375 if (var.length() < 4)
377 for (int c = 0, clen = var.length(); c < clen; c++)
379 char varchar = var.charAt(c);
380 String var3 = ResidueProperties.aa2Triplet.get("" + varchar);
382 sb.append(var3 != null ? StringUtils.toSentenceCase(var3)
390 if (++p != variants.size())
392 sb.append("<br/> ");
401 String description = feature.getDescription();
402 if (description != null)
404 sb.append(description);
408 sb.insert(0, "<html>");
409 sb.append("</html>");
412 return sb.toString();
416 * A helper method that searches the list of properties for one with the given
417 * key, and if found returns the property value, else returns null
423 static String getProperty(List<PropertyType> properties, String key)
426 if (properties != null)
428 for (PropertyType prop : properties)
430 if (key.equals(prop.getType()))
432 value = prop.getValue();
441 * Extracts xml element entry/protein/recommendedName/fullName
446 static String getUniprotEntryDescription(Entry entry)
449 if (entry.getProtein() != null
450 && entry.getProtein().getRecommendedName() != null)
452 // fullName is mandatory if recommendedName is present
453 desc = entry.getProtein().getRecommendedName().getFullName()
460 * Constructs a sequence id by concatenating all entry/name elements with '|'
466 static String getUniprotEntryId(Entry entry)
468 StringBuilder name = new StringBuilder(32);
469 for (String n : entry.getName())
471 if (name.length() > 0)
473 name.append(BAR_DELIMITER);
477 return name.toString();
483 * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
486 public boolean isValidReference(String accession)
488 // TODO: make the following a standard validator
489 return (accession == null || accession.length() < 2) ? false
490 : getAccessionValidator().search(accession);
494 * return LDHA_CHICK uniprot entry
497 public String getTestQuery()
503 public String getDbName()
505 return "Uniprot"; // getDbSource();
515 * Reads the reply to the EBI Fetch Uniprot data query, unmarshals it to an
516 * Uniprot object, and returns the enclosed Entry objects, or null on any
522 public List<Entry> getUniprotEntries(InputStream is)
524 List<Entry> entries = null;
527 JAXBContext jc = JAXBContext
528 .newInstance("jalview.xml.binding.uniprot");
529 XMLStreamReader streamReader = XMLInputFactory.newInstance()
530 .createXMLStreamReader(is);
531 javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
532 JAXBElement<jalview.xml.binding.uniprot.Uniprot> uniprotElement = um
533 .unmarshal(streamReader,
534 jalview.xml.binding.uniprot.Uniprot.class);
535 jalview.xml.binding.uniprot.Uniprot uniprot = uniprotElement
538 if (uniprot != null && !uniprot.getEntry().isEmpty())
540 entries = uniprot.getEntry();
542 } catch (JAXBException | XMLStreamException
543 | FactoryConfigurationError e)
545 if (e instanceof javax.xml.bind.UnmarshalException
546 && e.getCause() != null
547 && e.getCause() instanceof XMLStreamException
548 && e.getCause().getMessage().contains("[row,col]:[1,1]"))
550 // trying to parse an empty stream