diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiriamConnector.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiriamConnector.java index f90874d5d3da486df6dce2f6513da87be67b5e9d..6cf4f1819003508f194c5b31dd5d6d2311df6c78 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiriamConnector.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiriamConnector.java @@ -21,261 +21,262 @@ import uk.ac.ebi.miriam.lib.MiriamLink; /** * Class responsible for connection to Miriam DB. It allows to update URI of - * database being used and retreive urls for miriam uri. + * database being used and retrieve urls for miriam uri. * * @author Piotr Gawron * */ public final class MiriamConnector extends CachableInterface implements IExternalService { - /** - * String used to distinguish cached data for links. - */ - static final String LINK_DB_PREFIX = "Link: "; + /** + * String used to distinguish cached data for links. + */ + static final String LINK_DB_PREFIX = "Link: "; - /** - * String used to distinguish cached data for checking if uri is valid. - */ - protected static final String VALID_URI_PREFIX = "Validity: "; + /** + * String used to distinguish cached data for checking if uri is valid. + */ + protected static final String VALID_URI_PREFIX = "Validity: "; - /** - * String describing invalid miriam entries that will be put into db (instead - * of null). - */ - private static final String INVALID_LINK = "INVALID"; + /** + * String describing invalid miriam entries that will be put into db (instead of + * null). + */ + private static final String INVALID_LINK = "INVALID"; - /** - * Default class logger. - */ - private Logger logger = Logger.getLogger(MiriamConnector.class.getName()); + /** + * Default class logger. + */ + private Logger logger = Logger.getLogger(MiriamConnector.class.getName()); - /** - * Miriam Registry API. - */ - private MiriamLink link; + /** + * Miriam Registry API. + */ + private MiriamLink link; - /** - * Default class constructor. Prevent initialization. - */ - public MiriamConnector() { - super(MiriamConnector.class); - link = new MiriamLink(); - } + /** + * Default class constructor. Prevent initialization. + */ + public MiriamConnector() { + super(MiriamConnector.class); + link = new MiriamLink(); + link.setAddress("https://www.ebi.ac.uk/miriamws/main/MiriamWebServices"); + } - /** - * Returns url to the webpage represented by {@link MiriamData} param. - * - * @param miriamData - * miriam data - * @return url to resource pointed by miriam data - */ - public String getUrlString(MiriamData miriamData) { - if (miriamData.getDataType() == null) { - throw new InvalidArgumentException("Data type cannot be empty."); - } else if (miriamData.getDataType().getUris().size() == 0) { - throw new InvalidArgumentException("Url for " + miriamData.getDataType() + " cannot be retreived."); - } - String query = LINK_DB_PREFIX + miriamData.getDataType().getUris().get(0) + "\n" + miriamData.getResource(); - String result = getCacheValue(query); - if (result != null) { - if (INVALID_LINK.equals(result)) { - return null; - } - return result; - } - // hardcoded specific treatment for mesh - if (MiriamType.MESH_2012.equals(miriamData.getDataType())) { - result = "http://bioportal.bioontology.org/ontologies/1351?p=terms&conceptid=" + miriamData.getResource(); - } else { - String uri = miriamData.getDataType().getUris().get(0) + ":" + miriamData.getResource(); - String[] urls = getLink().getLocations(uri); - if (urls == null) { - result = null; - } else if (urls.length > 0) { - result = urls[0]; - } - } - if (result != null) { - setCacheValue(query, result); - return result; - } else { - logger.warn("Cannot find url for miriam: " + miriamData); - setCacheValue(query, INVALID_LINK); - return null; - } - } + /** + * Returns url to the web page represented by {@link MiriamData} parameter. + * + * @param miriamData + * miriam data + * @return url to resource pointed by miriam data + */ + public String getUrlString(MiriamData miriamData) { + if (miriamData.getDataType() == null) { + throw new InvalidArgumentException("Data type cannot be empty."); + } else if (miriamData.getDataType().getUris().size() == 0) { + throw new InvalidArgumentException("Url for " + miriamData.getDataType() + " cannot be retreived."); + } + String query = LINK_DB_PREFIX + miriamData.getDataType().getUris().get(0) + "\n" + miriamData.getResource(); + String result = getCacheValue(query); + if (result != null) { + if (INVALID_LINK.equals(result)) { + return null; + } + return result; + } + // hard-coded specific treatment for mesh + if (MiriamType.MESH_2012.equals(miriamData.getDataType())) { + result = "http://bioportal.bioontology.org/ontologies/1351?p=terms&conceptid=" + miriamData.getResource(); + } else { + String uri = miriamData.getDataType().getUris().get(0) + ":" + miriamData.getResource(); + String[] urls = getLink().getLocations(uri); + if (urls == null) { + result = null; + } else if (urls.length > 0) { + result = urls[0]; + } + } + if (result != null) { + setCacheValue(query, result); + return result; + } else { + logger.warn("Cannot find url for miriam: " + miriamData); + setCacheValue(query, INVALID_LINK); + return null; + } + } - @Override - public ExternalServiceStatus getServiceStatus() { - ExternalServiceStatus status = new ExternalServiceStatus("MIRIAM Registry", "http://www.ebi.ac.uk/miriam/main/"); - GeneralCacheInterface cacheCopy = getCache(); - this.setCache(null); + @Override + public ExternalServiceStatus getServiceStatus() { + ExternalServiceStatus status = new ExternalServiceStatus("MIRIAM Registry", "https://www.ebi.ac.uk/miriam/main/"); + GeneralCacheInterface cacheCopy = getCache(); + this.setCache(null); - try { - String url = getUrlString(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.PUBMED, "3453")); - status.setStatus(ExternalServiceStatusType.OK); - if (url == null) { - status.setStatus(ExternalServiceStatusType.DOWN); - } - } catch (Exception e) { - logger.error(status.getName() + " is down", e); - status.setStatus(ExternalServiceStatusType.DOWN); - } - this.setCache(cacheCopy); - return status; - } + try { + String url = getUrlString(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.PUBMED, "3453")); + status.setStatus(ExternalServiceStatusType.OK); + if (url == null) { + status.setStatus(ExternalServiceStatusType.DOWN); + } + } catch (Exception e) { + logger.error(status.getName() + " is down", e); + status.setStatus(ExternalServiceStatusType.DOWN); + } + this.setCache(cacheCopy); + return status; + } - /** - * Check if identifier can be transformed into {@link MiriamData}. - * - * @param string - * identifier in the format NAME:IDENTIFIER. Where NAME is the name - * from {@link MiriamType#commonName} and IDENTIFIER is resource - * identifier. - * @return <code>true</code> if identifier can be transformed into - * {@link MiriamData} - */ - public boolean isValidIdentifier(String string) { - try { - MiriamType.getMiriamDataFromIdentifier(string); - return true; - } catch (InvalidArgumentException e) { - return false; - } - } + /** + * Check if identifier can be transformed into {@link MiriamData}. + * + * @param string + * identifier in the format NAME:IDENTIFIER. Where NAME is the name + * from {@link MiriamType#commonName} and IDENTIFIER is resource + * identifier. + * @return <code>true</code> if identifier can be transformed into + * {@link MiriamData} + */ + public boolean isValidIdentifier(String string) { + try { + MiriamType.getMiriamDataFromIdentifier(string); + return true; + } catch (InvalidArgumentException e) { + return false; + } + } - @Override - public String refreshCacheQuery(Object query) throws SourceNotAvailable { - String result = null; - if (query instanceof String) { - String name = (String) query; - if (name.startsWith(LINK_DB_PREFIX)) { - String tmp = name.substring(LINK_DB_PREFIX.length()); - String[] rows = tmp.split("\n"); - if (rows.length != 2) { - throw new InvalidArgumentException("Miriam link query is invalid: " + query); - } - MiriamType dataType = MiriamType.getTypeByUri(rows[0]); - String resource = rows[1]; - result = getUrlString(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, dataType, resource)); - } else if (name.startsWith(VALID_URI_PREFIX)) { - String tmp = name.substring(VALID_URI_PREFIX.length()); - result = "" + isValid(tmp); - } else if (name.startsWith("http")) { - try { - result = getWebPageContent(name); - } catch (IOException e) { - throw new SourceNotAvailable(e); - } - } else { - throw new InvalidArgumentException("Don't know what to do with string \"" + query + "\""); - } - } else { - throw new InvalidArgumentException("Don't know what to do with class: " + query.getClass()); - } + @Override + public String refreshCacheQuery(Object query) throws SourceNotAvailable { + String result = null; + if (query instanceof String) { + String name = (String) query; + if (name.startsWith(LINK_DB_PREFIX)) { + String tmp = name.substring(LINK_DB_PREFIX.length()); + String[] rows = tmp.split("\n"); + if (rows.length != 2) { + throw new InvalidArgumentException("Miriam link query is invalid: " + query); + } + MiriamType dataType = MiriamType.getTypeByUri(rows[0]); + String resource = rows[1]; + result = getUrlString(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, dataType, resource)); + } else if (name.startsWith(VALID_URI_PREFIX)) { + String tmp = name.substring(VALID_URI_PREFIX.length()); + result = "" + isValid(tmp); + } else if (name.startsWith("http")) { + try { + result = getWebPageContent(name); + } catch (IOException e) { + throw new SourceNotAvailable(e); + } + } else { + throw new InvalidArgumentException("Don't know what to do with string \"" + query + "\""); + } + } else { + throw new InvalidArgumentException("Don't know what to do with class: " + query.getClass()); + } - return result; - } + return result; + } - /** - * Checks if uri (like the one defined in {@link MiriamType#uris}) is valid. - * - * @param uri - * uri to check - * @return <code>true</code> if uri in parameter is valid, <code>false</code> - * otherwise - */ - public boolean isValid(String uri) { - String query = VALID_URI_PREFIX + uri; - String val = getCacheValue(query); - if (val != null) { - return "true".equalsIgnoreCase(val); - } + /** + * Checks if uri (like the one defined in {@link MiriamType#uris}) is valid. + * + * @param uri + * uri to check + * @return <code>true</code> if uri in parameter is valid, <code>false</code> + * otherwise + */ + public boolean isValid(String uri) { + String query = VALID_URI_PREFIX + uri; + String val = getCacheValue(query); + if (val != null) { + return "true".equalsIgnoreCase(val); + } - boolean result = false; - String name = getLink().getName(uri); - if (name == null) { - result = false; - } else { - result = !name.isEmpty(); - } - setCacheValue(query, "" + result); - return result; - } + boolean result = false; + String name = getLink().getName(uri); + if (name == null) { + result = false; + } else { + result = !name.isEmpty(); + } + setCacheValue(query, "" + result); + return result; + } - /** - * This is alternative versopm od {@link #getUrlString(MiriamData)} method - * that is around 30% fatsre. But it refers to beta version of - * <a href="http://www.ebi.ac.uk/miriamws/main/rest/">miriam Rest API</a>. - * - * @param md - * miriam data for which access url will be returned - * @return url to resource pointed by miriam data - * @throws AnnotationException - * thrown when there is a problem with accessing miriam REST API - */ - protected String getUrlString2(MiriamData md) throws AnnotationException { - try { - String result = null; - String uri = md.getDataType().getUris().get(0) + ":" + md.getResource(); - String query = "http://www.ebi.ac.uk/miriamws/main/rest/resolve/" + uri; - String page; - page = getWebPageContent(query); - Document document = getXmlDocumentFromString(page); - Node uris = document.getFirstChild(); - NodeList nodes = uris.getChildNodes(); - for (int i = 0; i < nodes.getLength(); i++) { - Node node = nodes.item(i); - if (Node.ELEMENT_NODE == node.getNodeType()) { - if (getNodeAttr("deprecated", node).equals("")) { - result = node.getTextContent(); - } - } - } - return result; - } catch (IOException e) { - throw new AnnotationException("Problem with accessing miriam REST API", e); - } catch (InvalidXmlSchemaException e) { - throw new AnnotationException("Problem with parsing miriam REST API response", e); - } - } + /** + * This is alternative version of {@link #getUrlString(MiriamData)} method that + * is around 30% faster. But it refers to beta version of + * <a href="https://www.ebi.ac.uk/miriamws/main/rest/">miriam Rest API</a>. + * + * @param md + * miriam data for which access url will be returned + * @return url to resource pointed by miriam data + * @throws AnnotationException + * thrown when there is a problem with accessing miriam REST API + */ + protected String getUrlString2(MiriamData md) throws AnnotationException { + try { + String result = null; + String uri = md.getDataType().getUris().get(0) + ":" + md.getResource(); + String query = "https://www.ebi.ac.uk/miriamws/main/rest/resolve/" + uri; + String page; + page = getWebPageContent(query); + Document document = getXmlDocumentFromString(page); + Node uris = document.getFirstChild(); + NodeList nodes = uris.getChildNodes(); + for (int i = 0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (Node.ELEMENT_NODE == node.getNodeType()) { + if (getNodeAttr("deprecated", node).equals("")) { + result = node.getTextContent(); + } + } + } + return result; + } catch (IOException e) { + throw new AnnotationException("Problem with accessing miriam REST API", e); + } catch (InvalidXmlSchemaException e) { + throw new AnnotationException("Problem with parsing miriam REST API response", e); + } + } - /** - * Returns uri to miriam resource. - * - * @param md - * {@link MiriamData} object for which uri should be returned - * @return uri to miriam resource - */ - public String miriamDataToUri(MiriamData md) { - return md.getDataType().getUris().get(0) + ":" + md.getResource(); - } + /** + * Returns uri to miriam resource. + * + * @param md + * {@link MiriamData} object for which uri should be returned + * @return uri to miriam resource + */ + public String miriamDataToUri(MiriamData md) { + return md.getDataType().getUris().get(0) + ":" + md.getResource(); + } - @Override - protected WebPageDownloader getWebPageDownloader() { - return super.getWebPageDownloader(); - } + @Override + protected WebPageDownloader getWebPageDownloader() { + return super.getWebPageDownloader(); + } - @Override - protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { - super.setWebPageDownloader(webPageDownloader); - } + @Override + protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { + super.setWebPageDownloader(webPageDownloader); + } - /** - * @return the link - * @see #link - */ - MiriamLink getLink() { - return link; - } + /** + * @return the link + * @see #link + */ + MiriamLink getLink() { + return link; + } - /** - * @param link - * the link to set - * @see #link - */ - void setLink(MiriamLink link) { - this.link = link; - } + /** + * @param link + * the link to set + * @see #link + */ + void setLink(MiriamLink link) { + this.link = link; + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotator.java index a95985e33938f17feadd1366c4d683bb82a491dd..99b71fdd1085e3955d2fd206b883390e3f8cd96a 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotator.java @@ -1,5 +1,7 @@ package lcsb.mapviewer.annotation.services.annotators; +import java.net.MalformedURLException; +import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; @@ -7,6 +9,7 @@ import java.util.List; import java.util.Queue; import java.util.Set; +import javax.xml.namespace.QName; import javax.xml.ws.WebServiceException; import org.apache.log4j.Logger; @@ -44,464 +47,466 @@ import uk.ac.ebi.chebi.webapps.chebiWS.model.StarsCategory; */ public class ChebiAnnotator extends ElementAnnotator implements IExternalService { - /** - * What is the maximum number of results that should be retrieved from chebi - * API. - */ - static final int MAX_SEARCH_RESULTS_FROM_CHEBI_API = 50; - - /** - * Prefix used for entries identified by chebi id. - */ - public static final String ID_PREFIX = "id: "; - - /** - * Prefix used for ontology list for single chebi id. - */ - static final String ONTOLOGY_PREFIX = "ontology: "; - - /** - * Length of the prefix used for entries identified by chebi id. - */ - private static final int ID_PREFIX_LENGTH = ID_PREFIX.length(); - - /** - * Prefix used for entries identified by name. - */ - private static final String NAME_PREFIX = "name: "; - - /** - * Length of the prefix used for entries identified by name. - */ - private static final int NAME_PREFIX_LENGTH = NAME_PREFIX.length(); - - /** - * Class used for some simple operations on {@link BioEntity} elements. - */ - private ElementUtils elementUtils = new ElementUtils(); - - @Override - public String refreshCacheQuery(Object query) throws SourceNotAvailable { - String result = null; - try { - if (query instanceof String) { - String name = (String) query; - if (name.startsWith(ID_PREFIX)) { - String id = name.substring(ID_PREFIX_LENGTH); - result = chebiSerializer.objectToString(getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, id))); - } else if (name.startsWith(ONTOLOGY_PREFIX)) { - String id = name.substring(ONTOLOGY_PREFIX.length()); - result = miriamListToStringList(getOntologyChebiIdsForChebi(new MiriamData(MiriamType.CHEBI, id))); - } else if (name.startsWith(NAME_PREFIX)) { - name = name.substring(NAME_PREFIX_LENGTH); - MiriamData md = getChebiForChebiName(name); - if (md != null) { - result = md.getResource(); - } - } else { - throw new InvalidArgumentException("Don't know what to do with string \"" + query + "\""); - } - } else { - throw new InvalidArgumentException("Don't know what to do with class: " + query.getClass()); - } - } catch (ChebiSearchException e) { - throw new SourceNotAvailable(e); - } - - return result; - } - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(ChebiAnnotator.class); - - /** - * Client to chebi API. - */ - private ChebiWebServiceClient client = null; - - /** - * Object that allows to serialize {@link Chebi} elements into xml string and - * deserialize xml into {@link Chebi} objects. - */ - private XmlSerializer<Chebi> chebiSerializer; - - /** - * Default constructor. Initializes structures used for transforming - * {@link Chebi} from/to xml. - */ - public ChebiAnnotator() { - super(ChebiAnnotator.class, new Class[] { Chemical.class }, true); - chebiSerializer = new XmlSerializer<>(Chebi.class); - } - - /** - * Returns {@link MiriamData} for given chebi name. - * - * @param name - * name of the entry in chebi database. - * @return {@link MiriamData} entry for given chebi name - * @throws ChebiSearchException - * thrown when there is aproblem with accessing data from external - * chebi database - */ - public MiriamData getChebiForChebiName(String name) throws ChebiSearchException { - if (name == null) { - return null; - } - // Japanese people use strange dash symbol - name = name.replace("−", "-").toLowerCase().trim(); - - String id = getCacheValue("name: " + name); - if (id != null) { - return new MiriamData(MiriamType.CHEBI, id); - } - try { - ChebiWebServiceClient client = getClient(); - - LiteEntityList entities = client.getLiteEntity(name, SearchCategory.CHEBI_NAME, MAX_SEARCH_RESULTS_FROM_CHEBI_API, StarsCategory.ALL); - List<LiteEntity> resultList = entities.getListElement(); - - for (LiteEntity liteEntity : resultList) { - Entity entity = client.getCompleteEntity(liteEntity.getChebiId()); - String chebiName = entity.getChebiAsciiName(); - if (chebiName.trim().equalsIgnoreCase(name)) { - setCacheValue("name: " + name, entity.getChebiId()); - return new MiriamData(MiriamType.CHEBI, entity.getChebiId()); - } - for (DataItem dataItem : entity.getFormulae()) { - String synonym = dataItem.getData(); - if (synonym.trim().equalsIgnoreCase(name)) { - setCacheValue("name: " + name, entity.getChebiId()); - return new MiriamData(MiriamType.CHEBI, entity.getChebiId()); - } - } - for (DataItem dataItem : entity.getSynonyms()) { - String synonym = dataItem.getData(); - if (synonym.trim().equalsIgnoreCase(name)) { - setCacheValue("name: " + name, entity.getChebiId()); - return new MiriamData(MiriamType.CHEBI, entity.getChebiId()); - } - } - } - entities = client.getLiteEntity(name, SearchCategory.ALL, MAX_SEARCH_RESULTS_FROM_CHEBI_API, StarsCategory.ALL); - resultList = entities.getListElement(); - for (LiteEntity liteEntity : resultList) { - Entity entity = client.getCompleteEntity(liteEntity.getChebiId()); - for (DataItem dataItem : entity.getFormulae()) { - String formula = dataItem.getData(); - if (formula.trim().equalsIgnoreCase(name)) { - setCacheValue("name: " + name, entity.getChebiId()); - return new MiriamData(MiriamType.CHEBI, entity.getChebiId()); - } - } - for (DataItem dataItem : entity.getSynonyms()) { - String synonym = dataItem.getData(); - if (synonym.trim().equalsIgnoreCase(name)) { - setCacheValue("name: " + name, entity.getChebiId()); - return new MiriamData(MiriamType.CHEBI, entity.getChebiId()); - } - } - } - } catch (ChebiWebServiceFault_Exception e) { - throw new ChebiSearchException("Problem with chebi connection", e); - } - return null; - } - - /** - * This method returns list of ChEBI identifiers that correspond to the whole - * chebi tree for a given chemical name. - * - * @param name - * - name of chemical - * @return - list of ChEBI identifiers - * @throws ChebiSearchException - * thrown when there is aproblem with accessing data from external - * chebi database - */ - public List<MiriamData> getOntologyChebiIdsForChebiName(String name) throws ChebiSearchException { - // Japanese people use strange dash symbol - name = name.replace("−", "-").toLowerCase().trim(); - - MiriamData md = getChebiForChebiName(name); - return getOntologyChebiIdsForChebi(md); - } - - /** - * This method returns list of ChEBI identifiers that correspond to the whole - * chebi tree for a given chebi identifier. - * - * @param md - * - chebi identifier - * @return - list of ChEBI identifiers - * @throws ChebiSearchException - * thrown when there is a problemw ith accessing information from - * external chebi database - */ - public List<MiriamData> getOntologyChebiIdsForChebi(MiriamData md) throws ChebiSearchException { - if (md == null) { - return new ArrayList<>(); - } - String query = ONTOLOGY_PREFIX + md.getResource(); - - String res = getCacheValue(query); - if (res != null) { - return chebiStringListToMiriam(res); - } - - List<MiriamData> result = new ArrayList<MiriamData>(); - try { - ChebiWebServiceClient client = getClient(); - - Set<String> children = new HashSet<String>(); - children.add(md.getResource()); - Queue<String> queue = new LinkedList<String>(); - queue.add(md.getResource()); - while (!queue.isEmpty()) { - String element = queue.poll(); - result.add(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, element)); - Entity entity = client.getCompleteEntity(element); - for (OntologyDataItem di : entity.getOntologyChildren()) { - if (!children.contains(di.getChebiId()) && "is a".equals(di.getType())) { - children.add(di.getChebiId()); - queue.add(di.getChebiId()); - } - } - } - - Set<String> parents = new HashSet<String>(); - parents.add(md.getResource()); - queue = new LinkedList<String>(); - queue.add(md.getResource()); - while (!queue.isEmpty()) { - String element = queue.poll(); - Entity entity = client.getCompleteEntity(element); - for (OntologyDataItem di : entity.getOntologyParents()) { - if (!parents.contains(di.getChebiId()) && "is a".equals(di.getType())) { - result.add(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, di.getChebiId())); - parents.add(di.getChebiId()); - queue.add(di.getChebiId()); - } - } - } - String value = miriamListToStringList(result); - - setCacheValue(query, value); - } catch (ChebiWebServiceFault_Exception e) { - throw new ChebiSearchException("Problem with chebi", e); - } - return result; - } - - /** - * Serialize list of chebi identifiers. - * - * @param list - * list of chebi identfiers - * @return string with identifiers - */ - private String miriamListToStringList(List<MiriamData> list) { - StringBuilder result = new StringBuilder(""); - boolean first = true; - for (MiriamData miriamData : list) { - if (!first) { - result.append(","); - } - first = false; - result.append(miriamData.getResource()); - } - - return result.toString(); - } - - /** - * Deserialize list of chebi identifiers. - * - * @param res - * text with list of chebi identifeirs - * @return list with chebi identifiers - */ - private List<MiriamData> chebiStringListToMiriam(String res) { - String[] tmp = res.split(","); - List<MiriamData> result = new ArrayList<MiriamData>(); - for (String string : tmp) { - result.add(new MiriamData(MiriamType.CHEBI, string)); - } - return result; - } - - /** - * This method returns ChEBI structure for identifier given as a parameter. - * - * @param md - * {@link MiriamData} with ChEBI identifier - * @return - ChEBI structure - * @throws ChebiSearchException - * thrown when there is a problemw ith accessing information from - * external chebi database - */ - public Chebi getChebiElementForChebiId(MiriamData md) throws ChebiSearchException { - if (!MiriamType.CHEBI.equals(md.getDataType())) { - throw new InvalidArgumentException(MiriamType.CHEBI + " expected"); - } - String id = md.getResource().toLowerCase().trim(); - if (!id.contains("chebi")) { - id = "chebi:" + id; - } - Chebi result = chebiSerializer.xmlToObject(getCacheNode("id: " + id)); - if (result != null) { - return result; - } - try { - ChebiWebServiceClient client = getClient(); - - LiteEntityList entities = client.getLiteEntity(id, SearchCategory.CHEBI_ID, MAX_SEARCH_RESULTS_FROM_CHEBI_API, StarsCategory.ALL); - List<LiteEntity> resultList = entities.getListElement(); - - for (LiteEntity liteEntity : resultList) { - Entity entity = client.getCompleteEntity(liteEntity.getChebiId()); - - if (entity.getChebiId().trim().equalsIgnoreCase(id)) { - result = new Chebi(entity); - } - } - - if (result != null) { - setCacheValue("id: " + id, chebiSerializer.objectToString(result)); - } - return result; - } catch (ChebiWebServiceFault_Exception e) { - throw new ChebiSearchException("Problem with chebi", e); - } - } - - /** - * This method returns common name for chemical identified by chebi id. - * - * @param id - * - chebi identifier in format (XXXXX represents numerical - * identifier): "CHEBI:XXXXX" or "XXXXX" - * @return common name of chemical - * @throws ChebiSearchException - * thrown when there is a problemw ith accessing information from - * external chebi database - */ - protected String getChebiNameForChebiId(MiriamData id) throws ChebiSearchException { - if (id == null) { - return null; - } - Chebi chebi = getChebiElementForChebiId(id); - if (chebi == null) { - return null; - } - return chebi.getName(); - } - - @Override - public ExternalServiceStatus getServiceStatus() { - ExternalServiceStatus status = new ExternalServiceStatus(getCommonName(), getUrl()); - - GeneralCacheInterface cacheCopy = getCache(); - this.setCache(null); - try { - MiriamData data = getChebiForChebiName("water"); - status.setStatus(ExternalServiceStatusType.OK); - if (data == null || !data.getResource().equals("CHEBI:15377")) { - status.setStatus(ExternalServiceStatusType.CHANGED); - } - } catch (Exception e) { - logger.error(status.getName() + " is down", e); - status.setStatus(ExternalServiceStatusType.DOWN); - } - this.setCache(cacheCopy); - return status; - } - - /** - * - * @return {@link #client} - * @throws ChebiSearchException - * thrown when there is a problemw ith accessing information from - * external chebi database - */ - private ChebiWebServiceClient getClient() throws ChebiSearchException { - if (client == null) { - try { - client = new ChebiWebServiceClient(); - } catch (WebServiceException exception) { - throw new ChebiSearchException("Cannot initialize chebi connector", exception); - } - } - return client; - } - - @Override - public void annotateElement(BioEntity element) throws AnnotatorException { - if (isAnnotatable(element)) { - try { - String warnPrefix = elementUtils.getElementTag(element, this); - if (element.getMiriamData().size() == 0) { - - MiriamData chebi = getChebiForChebiName(element.getName()); - if (chebi != null) { - element.addMiriamData(chebi); - } else { - logger.warn(warnPrefix + "Chemical name cannot be found in chebi: " + element.getName()); - } - } - Chebi chebi = null; - for (MiriamData md : element.getMiriamData()) { - if (MiriamType.CHEBI.equals(md.getDataType())) { - chebi = getChebiElementForChebiId(md); - } - } - Chemical species = (Chemical) element; - if (chebi != null) { - super.setFullName(species, chebi.getName(), warnPrefix); - - setInchi(species, chebi.getInchi(), warnPrefix); - setInchiKey(species, chebi.getInchiKey(), warnPrefix); - setSmile(species, chebi.getSmiles(), warnPrefix); - - if (species.getSynonyms().size() == 0) { - species.addSynonyms(chebi.getSynonyms()); - } else { - StringSetComparator stringSetComparator = new StringSetComparator(); - Set<String> set1 = new HashSet<String>(); - Set<String> set2 = new HashSet<String>(); - - set1.addAll(species.getSynonyms()); - set2.addAll(chebi.getSynonyms()); - - if (stringSetComparator.compare(set1, set2) != 0) { - logger.warn(warnPrefix + "Different set of synonyms: " + species.getFullName() + ", " + chebi.getName()); - } - } - } - } catch (ChebiSearchException e) { - throw new AnnotatorException("Problem with getting information about chebi", e); - } - } - } - - @Override - public String getCommonName() { - return MiriamType.CHEBI.getCommonName(); - } - - @Override - public String getUrl() { - return MiriamType.CHEBI.getDbHomepage(); - } - - /** - * @param client - * the client to set - * @see #client - */ - void setClient(ChebiWebServiceClient client) { - this.client = client; - } + /** + * What is the maximum number of results that should be retrieved from chebi + * API. + */ + static final int MAX_SEARCH_RESULTS_FROM_CHEBI_API = 50; + + /** + * Prefix used for entries identified by chebi id. + */ + public static final String ID_PREFIX = "id: "; + + /** + * Prefix used for ontology list for single chebi id. + */ + static final String ONTOLOGY_PREFIX = "ontology: "; + + /** + * Length of the prefix used for entries identified by chebi id. + */ + private static final int ID_PREFIX_LENGTH = ID_PREFIX.length(); + + /** + * Prefix used for entries identified by name. + */ + private static final String NAME_PREFIX = "name: "; + + /** + * Length of the prefix used for entries identified by name. + */ + private static final int NAME_PREFIX_LENGTH = NAME_PREFIX.length(); + + /** + * Class used for some simple operations on {@link BioEntity} elements. + */ + private ElementUtils elementUtils = new ElementUtils(); + + @Override + public String refreshCacheQuery(Object query) throws SourceNotAvailable { + String result = null; + try { + if (query instanceof String) { + String name = (String) query; + if (name.startsWith(ID_PREFIX)) { + String id = name.substring(ID_PREFIX_LENGTH); + result = chebiSerializer.objectToString(getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, id))); + } else if (name.startsWith(ONTOLOGY_PREFIX)) { + String id = name.substring(ONTOLOGY_PREFIX.length()); + result = miriamListToStringList(getOntologyChebiIdsForChebi(new MiriamData(MiriamType.CHEBI, id))); + } else if (name.startsWith(NAME_PREFIX)) { + name = name.substring(NAME_PREFIX_LENGTH); + MiriamData md = getChebiForChebiName(name); + if (md != null) { + result = md.getResource(); + } + } else { + throw new InvalidArgumentException("Don't know what to do with string \"" + query + "\""); + } + } else { + throw new InvalidArgumentException("Don't know what to do with class: " + query.getClass()); + } + } catch (ChebiSearchException e) { + throw new SourceNotAvailable(e); + } + + return result; + } + + /** + * Default class logger. + */ + private static Logger logger = Logger.getLogger(ChebiAnnotator.class); + + /** + * Client to chebi API. + */ + private ChebiWebServiceClient client = null; + + /** + * Object that allows to serialize {@link Chebi} elements into xml string and + * deserialize xml into {@link Chebi} objects. + */ + private XmlSerializer<Chebi> chebiSerializer; + + /** + * Default constructor. Initializes structures used for transforming + * {@link Chebi} from/to xml. + */ + public ChebiAnnotator() { + super(ChebiAnnotator.class, new Class[] { Chemical.class }, true); + chebiSerializer = new XmlSerializer<>(Chebi.class); + } + + /** + * Returns {@link MiriamData} for given chebi name. + * + * @param name + * name of the entry in chebi database. + * @return {@link MiriamData} entry for given chebi name + * @throws ChebiSearchException + * thrown when there is aproblem with accessing data from external + * chebi database + */ + public MiriamData getChebiForChebiName(String name) throws ChebiSearchException { + if (name == null) { + return null; + } + // Japanese people use strange dash symbol + name = name.replace("−", "-").toLowerCase().trim(); + + String id = getCacheValue("name: " + name); + if (id != null) { + return new MiriamData(MiriamType.CHEBI, id); + } + try { + ChebiWebServiceClient client = getClient(); + + LiteEntityList entities = client.getLiteEntity(name, SearchCategory.CHEBI_NAME, MAX_SEARCH_RESULTS_FROM_CHEBI_API, + StarsCategory.ALL); + List<LiteEntity> resultList = entities.getListElement(); + + for (LiteEntity liteEntity : resultList) { + Entity entity = client.getCompleteEntity(liteEntity.getChebiId()); + String chebiName = entity.getChebiAsciiName(); + if (chebiName.trim().equalsIgnoreCase(name)) { + setCacheValue("name: " + name, entity.getChebiId()); + return new MiriamData(MiriamType.CHEBI, entity.getChebiId()); + } + for (DataItem dataItem : entity.getFormulae()) { + String synonym = dataItem.getData(); + if (synonym.trim().equalsIgnoreCase(name)) { + setCacheValue("name: " + name, entity.getChebiId()); + return new MiriamData(MiriamType.CHEBI, entity.getChebiId()); + } + } + for (DataItem dataItem : entity.getSynonyms()) { + String synonym = dataItem.getData(); + if (synonym.trim().equalsIgnoreCase(name)) { + setCacheValue("name: " + name, entity.getChebiId()); + return new MiriamData(MiriamType.CHEBI, entity.getChebiId()); + } + } + } + entities = client.getLiteEntity(name, SearchCategory.ALL, MAX_SEARCH_RESULTS_FROM_CHEBI_API, StarsCategory.ALL); + resultList = entities.getListElement(); + for (LiteEntity liteEntity : resultList) { + Entity entity = client.getCompleteEntity(liteEntity.getChebiId()); + for (DataItem dataItem : entity.getFormulae()) { + String formula = dataItem.getData(); + if (formula.trim().equalsIgnoreCase(name)) { + setCacheValue("name: " + name, entity.getChebiId()); + return new MiriamData(MiriamType.CHEBI, entity.getChebiId()); + } + } + for (DataItem dataItem : entity.getSynonyms()) { + String synonym = dataItem.getData(); + if (synonym.trim().equalsIgnoreCase(name)) { + setCacheValue("name: " + name, entity.getChebiId()); + return new MiriamData(MiriamType.CHEBI, entity.getChebiId()); + } + } + } + } catch (ChebiWebServiceFault_Exception e) { + throw new ChebiSearchException("Problem with chebi connection", e); + } + return null; + } + + /** + * This method returns list of ChEBI identifiers that correspond to the whole + * chebi tree for a given chemical name. + * + * @param name + * - name of chemical + * @return - list of ChEBI identifiers + * @throws ChebiSearchException + * thrown when there is aproblem with accessing data from external + * chebi database + */ + public List<MiriamData> getOntologyChebiIdsForChebiName(String name) throws ChebiSearchException { + // Japanese people use strange dash symbol + name = name.replace("−", "-").toLowerCase().trim(); + + MiriamData md = getChebiForChebiName(name); + return getOntologyChebiIdsForChebi(md); + } + + /** + * This method returns list of ChEBI identifiers that correspond to the whole + * chebi tree for a given chebi identifier. + * + * @param md + * - chebi identifier + * @return - list of ChEBI identifiers + * @throws ChebiSearchException + * thrown when there is a problemw ith accessing information from + * external chebi database + */ + public List<MiriamData> getOntologyChebiIdsForChebi(MiriamData md) throws ChebiSearchException { + if (md == null) { + return new ArrayList<>(); + } + String query = ONTOLOGY_PREFIX + md.getResource(); + + String res = getCacheValue(query); + if (res != null) { + return chebiStringListToMiriam(res); + } + + List<MiriamData> result = new ArrayList<MiriamData>(); + try { + ChebiWebServiceClient client = getClient(); + + Set<String> children = new HashSet<String>(); + children.add(md.getResource()); + Queue<String> queue = new LinkedList<String>(); + queue.add(md.getResource()); + while (!queue.isEmpty()) { + String element = queue.poll(); + result.add(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, element)); + Entity entity = client.getCompleteEntity(element); + for (OntologyDataItem di : entity.getOntologyChildren()) { + if (!children.contains(di.getChebiId()) && "is a".equals(di.getType())) { + children.add(di.getChebiId()); + queue.add(di.getChebiId()); + } + } + } + + Set<String> parents = new HashSet<String>(); + parents.add(md.getResource()); + queue = new LinkedList<String>(); + queue.add(md.getResource()); + while (!queue.isEmpty()) { + String element = queue.poll(); + Entity entity = client.getCompleteEntity(element); + for (OntologyDataItem di : entity.getOntologyParents()) { + if (!parents.contains(di.getChebiId()) && "is a".equals(di.getType())) { + result.add(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, di.getChebiId())); + parents.add(di.getChebiId()); + queue.add(di.getChebiId()); + } + } + } + String value = miriamListToStringList(result); + + setCacheValue(query, value); + } catch (ChebiWebServiceFault_Exception e) { + throw new ChebiSearchException("Problem with chebi", e); + } + return result; + } + + /** + * Serialize list of chebi identifiers. + * + * @param list + * list of chebi identfiers + * @return string with identifiers + */ + private String miriamListToStringList(List<MiriamData> list) { + StringBuilder result = new StringBuilder(""); + boolean first = true; + for (MiriamData miriamData : list) { + if (!first) { + result.append(","); + } + first = false; + result.append(miriamData.getResource()); + } + + return result.toString(); + } + + /** + * Deserialize list of chebi identifiers. + * + * @param res + * text with list of chebi identifeirs + * @return list with chebi identifiers + */ + private List<MiriamData> chebiStringListToMiriam(String res) { + String[] tmp = res.split(","); + List<MiriamData> result = new ArrayList<MiriamData>(); + for (String string : tmp) { + result.add(new MiriamData(MiriamType.CHEBI, string)); + } + return result; + } + + /** + * This method returns ChEBI structure for identifier given as a parameter. + * + * @param md + * {@link MiriamData} with ChEBI identifier + * @return - ChEBI structure + * @throws ChebiSearchException + * thrown when there is a problemw ith accessing information from + * external chebi database + */ + public Chebi getChebiElementForChebiId(MiriamData md) throws ChebiSearchException { + if (!MiriamType.CHEBI.equals(md.getDataType())) { + throw new InvalidArgumentException(MiriamType.CHEBI + " expected"); + } + String id = md.getResource().toLowerCase().trim(); + if (!id.contains("chebi")) { + id = "chebi:" + id; + } + Chebi result = chebiSerializer.xmlToObject(getCacheNode("id: " + id)); + if (result != null) { + return result; + } + try { + ChebiWebServiceClient client = getClient(); + + LiteEntityList entities = client.getLiteEntity(id, SearchCategory.CHEBI_ID, MAX_SEARCH_RESULTS_FROM_CHEBI_API, + StarsCategory.ALL); + List<LiteEntity> resultList = entities.getListElement(); + + for (LiteEntity liteEntity : resultList) { + Entity entity = client.getCompleteEntity(liteEntity.getChebiId()); + + if (entity.getChebiId().trim().equalsIgnoreCase(id)) { + result = new Chebi(entity); + } + } + + if (result != null) { + setCacheValue("id: " + id, chebiSerializer.objectToString(result)); + } + return result; + } catch (ChebiWebServiceFault_Exception e) { + throw new ChebiSearchException("Problem with chebi", e); + } + } + + /** + * This method returns common name for chemical identified by chebi id. + * + * @param id + * - chebi identifier in format (XXXXX represents numerical + * identifier): "CHEBI:XXXXX" or "XXXXX" + * @return common name of chemical + * @throws ChebiSearchException + * thrown when there is a problemw ith accessing information from + * external chebi database + */ + protected String getChebiNameForChebiId(MiriamData id) throws ChebiSearchException { + if (id == null) { + return null; + } + Chebi chebi = getChebiElementForChebiId(id); + if (chebi == null) { + return null; + } + return chebi.getName(); + } + + @Override + public ExternalServiceStatus getServiceStatus() { + ExternalServiceStatus status = new ExternalServiceStatus(getCommonName(), getUrl()); + + GeneralCacheInterface cacheCopy = getCache(); + this.setCache(null); + try { + MiriamData data = getChebiForChebiName("water"); + status.setStatus(ExternalServiceStatusType.OK); + if (data == null || !data.getResource().equals("CHEBI:15377")) { + status.setStatus(ExternalServiceStatusType.CHANGED); + } + } catch (Exception e) { + logger.error(status.getName() + " is down", e); + status.setStatus(ExternalServiceStatusType.DOWN); + } + this.setCache(cacheCopy); + return status; + } + + /** + * + * @return {@link #client} + * @throws ChebiSearchException + * thrown when there is a problem with accessing information from + * external chebi database + */ + private ChebiWebServiceClient getClient() throws ChebiSearchException { + if (client == null) { + try { + client = new ChebiWebServiceClient(); + } catch (WebServiceException exception) { + throw new ChebiSearchException("Cannot initialize chebi connector", exception); + } + } + return client; + } + + @Override + public void annotateElement(BioEntity element) throws AnnotatorException { + if (isAnnotatable(element)) { + try { + String warnPrefix = elementUtils.getElementTag(element, this); + if (element.getMiriamData().size() == 0) { + + MiriamData chebi = getChebiForChebiName(element.getName()); + if (chebi != null) { + element.addMiriamData(chebi); + } else { + logger.warn(warnPrefix + "Chemical name cannot be found in chebi: " + element.getName()); + } + } + Chebi chebi = null; + for (MiriamData md : element.getMiriamData()) { + if (MiriamType.CHEBI.equals(md.getDataType())) { + chebi = getChebiElementForChebiId(md); + } + } + Chemical species = (Chemical) element; + if (chebi != null) { + super.setFullName(species, chebi.getName(), warnPrefix); + + setInchi(species, chebi.getInchi(), warnPrefix); + setInchiKey(species, chebi.getInchiKey(), warnPrefix); + setSmile(species, chebi.getSmiles(), warnPrefix); + + if (species.getSynonyms().size() == 0) { + species.addSynonyms(chebi.getSynonyms()); + } else { + StringSetComparator stringSetComparator = new StringSetComparator(); + Set<String> set1 = new HashSet<String>(); + Set<String> set2 = new HashSet<String>(); + + set1.addAll(species.getSynonyms()); + set2.addAll(chebi.getSynonyms()); + + if (stringSetComparator.compare(set1, set2) != 0) { + logger.warn(warnPrefix + "Different set of synonyms: " + species.getFullName() + ", " + chebi.getName()); + } + } + } + } catch (ChebiSearchException e) { + throw new AnnotatorException("Problem with getting information about chebi", e); + } + } + } + + @Override + public String getCommonName() { + return MiriamType.CHEBI.getCommonName(); + } + + @Override + public String getUrl() { + return MiriamType.CHEBI.getDbHomepage(); + } + + /** + * @param client + * the client to set + * @see #client + */ + void setClient(ChebiWebServiceClient client) { + this.client = client; + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiriamConnectorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiriamConnectorTest.java index 86d950eeae2c6e0e99f4326ae8a688b830a49046..a8b145d6cf2e48606c049f7fb7842f0f469ae1be 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiriamConnectorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiriamConnectorTest.java @@ -33,191 +33,191 @@ import lcsb.mapviewer.model.map.MiriamType; import uk.ac.ebi.miriam.lib.MiriamLink; public class MiriamConnectorTest extends AnnotationTestFunctions { - Logger logger = Logger.getLogger(MiriamConnectorTest.class); - - @Autowired - MiriamConnector miriamConnector; - - GeneralCacheInterface cache; - - @Before - public void setUp() throws Exception { - cache = miriamConnector.getCache(); - } - - @After - public void tearDown() throws Exception { - miriamConnector.setCache(cache); - } - - @Test - public void testGoUri() throws Exception { - try { - assertFalse(MiriamType.GO.getUris().size() == 1); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test(timeout = 15000) - public void testMeshUrl() throws Exception { - try { - // exclude first cached value - miriamConnector.setCache(new GeneralCacheWithExclusion(cache, 1)); - MiriamData md = new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.MESH_2012, "D004249"); - - String pageContent = getWebpage(miriamConnector.getUrlString(md)); - assertTrue(pageContent.contains("DNA Damage")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetUrl() throws Exception { - try { - // exclude first cached value - miriamConnector.setCache(new GeneralCacheWithExclusion(cache, 1)); - MiriamData md = TaxonomyBackend.HUMAN_TAXONOMY; - - String url = miriamConnector.getUrlString(md); - assertNotNull(url); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetUrlForInvalidMiriam() throws Exception { - try { - miriamConnector.getUrlString(new MiriamData()); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Data type cannot be empty")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetUrlForInvalidMiriam2() throws Exception { - try { - miriamConnector.getUrlString(new MiriamData(MiriamType.UNKNOWN,"")); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("cannot be retreived")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetUrlForInvalidMiriam3() throws Exception { - try { - String url = miriamConnector.getUrlString(new MiriamData(MiriamType.ENTREZ,"abc")); - assertNull(url); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testIsValidIdentifier() throws Exception { - try { - assertTrue(miriamConnector.isValidIdentifier(MiriamType.ENTREZ.getCommonName()+":"+"1234")); - assertFalse(miriamConnector.isValidIdentifier("blablabla")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testResolveUrl() throws Exception { - try { - // exclude first cached value - miriamConnector.setCache(new GeneralCacheWithExclusion(cache, 1)); - for (MiriamType mt : MiriamType.values()) { - if (!MiriamType.UNKNOWN.equals(mt)) { - assertTrue("Invalid URI for MiriamType: " + mt, miriamConnector.isValid(mt.getUris().get(0))); - } - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefresh() throws Exception { - String query = MiriamConnector.VALID_URI_PREFIX + MiriamType.HGNC.getUris().get(0); - try { - String res = miriamConnector.refreshCacheQuery(query); - assertNotNull(res); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefresh2() throws Exception { - MiriamData md = TaxonomyBackend.HUMAN_TAXONOMY; - String query = MiriamConnector.LINK_DB_PREFIX + md.getDataType().getUris().get(0) + "\n" + md.getResource(); - try { - String res = miriamConnector.refreshCacheQuery(query); - assertNotNull(res); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefresh3() throws Exception { - try { - String res = miriamConnector.refreshCacheQuery("https://www.google.pl/"); - assertNotNull(res); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetUrl2() throws Exception { - try { - // exclude first cached value - miriamConnector.setCache(new GeneralCacheWithExclusion(cache, 1)); - MiriamData md = TaxonomyBackend.HUMAN_TAXONOMY; - - String url = miriamConnector.getUrlString2(md); - assertNotNull(url); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testMiriamDataToUri() throws Exception { - try { - assertNotNull(miriamConnector.miriamDataToUri(TaxonomyBackend.HUMAN_TAXONOMY)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + Logger logger = Logger.getLogger(MiriamConnectorTest.class); + + @Autowired + MiriamConnector miriamConnector; + + GeneralCacheInterface cache; + + @Before + public void setUp() throws Exception { + cache = miriamConnector.getCache(); + } + + @After + public void tearDown() throws Exception { + miriamConnector.setCache(cache); + } + + @Test + public void testGoUri() throws Exception { + try { + assertFalse(MiriamType.GO.getUris().size() == 1); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test(timeout = 15000) + public void testMeshUrl() throws Exception { + try { + // exclude first cached value + miriamConnector.setCache(new GeneralCacheWithExclusion(cache, 1)); + MiriamData md = new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.MESH_2012, "D004249"); + + String pageContent = getWebpage(miriamConnector.getUrlString(md)); + assertTrue(pageContent.contains("DNA Damage")); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetUrl() throws Exception { + try { + // exclude first cached value + miriamConnector.setCache(new GeneralCacheWithExclusion(cache, 1)); + MiriamData md = TaxonomyBackend.HUMAN_TAXONOMY; + + String url = miriamConnector.getUrlString(md); + assertNotNull(url); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetUrlForInvalidMiriam() throws Exception { + try { + miriamConnector.getUrlString(new MiriamData()); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Data type cannot be empty")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetUrlForInvalidMiriam2() throws Exception { + try { + miriamConnector.getUrlString(new MiriamData(MiriamType.UNKNOWN, "")); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("cannot be retreived")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetUrlForInvalidMiriam3() throws Exception { + try { + String url = miriamConnector.getUrlString(new MiriamData(MiriamType.ENTREZ, "abc")); + assertNull(url); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testIsValidIdentifier() throws Exception { + try { + assertTrue(miriamConnector.isValidIdentifier(MiriamType.ENTREZ.getCommonName() + ":" + "1234")); + assertFalse(miriamConnector.isValidIdentifier("blablabla")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testResolveUrl() throws Exception { + try { + // exclude first cached value + miriamConnector.setCache(new GeneralCacheWithExclusion(cache, 1)); + for (MiriamType mt : MiriamType.values()) { + if (!MiriamType.UNKNOWN.equals(mt)) { + assertTrue("Invalid URI for MiriamType: " + mt, miriamConnector.isValid(mt.getUris().get(0))); + } + } + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefresh() throws Exception { + String query = MiriamConnector.VALID_URI_PREFIX + MiriamType.HGNC.getUris().get(0); + try { + String res = miriamConnector.refreshCacheQuery(query); + assertNotNull(res); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefresh2() throws Exception { + MiriamData md = TaxonomyBackend.HUMAN_TAXONOMY; + String query = MiriamConnector.LINK_DB_PREFIX + md.getDataType().getUris().get(0) + "\n" + md.getResource(); + try { + String res = miriamConnector.refreshCacheQuery(query); + assertNotNull(res); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefresh3() throws Exception { + try { + String res = miriamConnector.refreshCacheQuery("https://www.google.pl/"); + assertNotNull(res); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetUrl2() throws Exception { + try { + // exclude first cached value + miriamConnector.setCache(new GeneralCacheWithExclusion(cache, 1)); + MiriamData md = TaxonomyBackend.HUMAN_TAXONOMY; + + String url = miriamConnector.getUrlString2(md); + assertNotNull(url); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testMiriamDataToUri() throws Exception { + try { + assertNotNull(miriamConnector.miriamDataToUri(TaxonomyBackend.HUMAN_TAXONOMY)); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } @Test public void testGetUrl2WithInvalidApiResponse() throws Exception { @@ -230,18 +230,18 @@ public class MiriamConnectorTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), anyString())).thenThrow(new IOException()); miriamConnector.setWebPageDownloader(mockDownloader); - miriamConnector.getUrlString2(TaxonomyBackend.HUMAN_TAXONOMY); + miriamConnector.getUrlString2(TaxonomyBackend.HUMAN_TAXONOMY); - } catch (AnnotationException e) { - assertTrue(e.getMessage().contains("Problem with accessing miriam REST API")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - miriamConnector.setWebPageDownloader(downloader); - miriamConnector.setCache(cache); - } - } + } catch (AnnotationException e) { + assertTrue(e.getMessage().contains("Problem with accessing miriam REST API")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + miriamConnector.setWebPageDownloader(downloader); + miriamConnector.setCache(cache); + } + } @Test public void testGetUrl2WithInvalidApiResponse2() throws Exception { @@ -254,18 +254,18 @@ public class MiriamConnectorTest extends AnnotationTestFunctions { when(mockDownloader.getFromNetwork(anyString(), anyString(), anyString())).thenReturn(""); miriamConnector.setWebPageDownloader(mockDownloader); - miriamConnector.getUrlString2(TaxonomyBackend.HUMAN_TAXONOMY); + miriamConnector.getUrlString2(TaxonomyBackend.HUMAN_TAXONOMY); - } catch (AnnotationException e) { - assertTrue(e.getMessage().contains("Problem with parsing miriam REST API response")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - miriamConnector.setWebPageDownloader(downloader); - miriamConnector.setCache(cache); - } - } + } catch (AnnotationException e) { + assertTrue(e.getMessage().contains("Problem with parsing miriam REST API response")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + miriamConnector.setWebPageDownloader(downloader); + miriamConnector.setCache(cache); + } + } @Test @@ -286,97 +286,97 @@ public class MiriamConnectorTest extends AnnotationTestFunctions { } } - @Test - public void testRefreshInvalidCacheQuery() throws Exception { - try { - miriamConnector.refreshCacheQuery("invalid_query"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefreshInvalidCacheQuery2() throws Exception { - try { - miriamConnector.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefreshInvalidCacheQuery3() throws Exception { - try { - miriamConnector.refreshCacheQuery(MiriamConnector.LINK_DB_PREFIX); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Miriam link query is invalid")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCheckValidyOfEmptyUri() throws Exception { - try { - //user connector without cache - boolean value = new MiriamConnector().isValid(""); - assertFalse(value); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, miriamConnector.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSimulateDownStatus() throws Exception { - MiriamLink link = miriamConnector.getLink(); - try { - MiriamLink mockDownloader = Mockito.mock(MiriamLink.class); - when(mockDownloader.getLocations(any())).thenThrow(new InvalidStateException()); - miriamConnector.setLink(mockDownloader); - assertEquals(ExternalServiceStatusType.DOWN, miriamConnector.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - miriamConnector.setLink(link); - } - } - - @Test - public void testSimulateDownStatus2() throws Exception { - MiriamLink link = miriamConnector.getLink(); - try { - MiriamLink mockDownloader = Mockito.mock(MiriamLink.class); - when(mockDownloader.getLocations(any())).thenReturn(null); - miriamConnector.setLink(mockDownloader); - assertEquals(ExternalServiceStatusType.DOWN, miriamConnector.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - miriamConnector.setLink(link); - } - } + @Test + public void testRefreshInvalidCacheQuery() throws Exception { + try { + miriamConnector.refreshCacheQuery("invalid_query"); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Don't know what to do")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefreshInvalidCacheQuery2() throws Exception { + try { + miriamConnector.refreshCacheQuery(new Object()); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Don't know what to do")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefreshInvalidCacheQuery3() throws Exception { + try { + miriamConnector.refreshCacheQuery(MiriamConnector.LINK_DB_PREFIX); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Miriam link query is invalid")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testCheckValidyOfEmptyUri() throws Exception { + try { + // user connector without cache + boolean value = new MiriamConnector().isValid(""); + assertFalse(value); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testStatus() throws Exception { + try { + assertEquals(ExternalServiceStatusType.OK, miriamConnector.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testSimulateDownStatus() throws Exception { + MiriamLink link = miriamConnector.getLink(); + try { + MiriamLink mockDownloader = Mockito.mock(MiriamLink.class); + when(mockDownloader.getLocations(any())).thenThrow(new InvalidStateException()); + miriamConnector.setLink(mockDownloader); + assertEquals(ExternalServiceStatusType.DOWN, miriamConnector.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + miriamConnector.setLink(link); + } + } + + @Test + public void testSimulateDownStatus2() throws Exception { + MiriamLink link = miriamConnector.getLink(); + try { + MiriamLink mockDownloader = Mockito.mock(MiriamLink.class); + when(mockDownloader.getLocations(any())).thenReturn(null); + miriamConnector.setLink(mockDownloader); + assertEquals(ExternalServiceStatusType.DOWN, miriamConnector.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + miriamConnector.setLink(link); + } + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotatorTest.java index 8ca9b43561724061b813fab1ca5c433d3673665e..a000cdc242deaf393ac42530947149713043b521 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotatorTest.java @@ -39,808 +39,814 @@ import uk.ac.ebi.chebi.webapps.chebiWS.model.OntologyDataItem; import uk.ac.ebi.chebi.webapps.chebiWS.model.SearchCategory; public class ChebiAnnotatorTest extends AnnotationTestFunctions { - static Logger logger = Logger.getLogger(ChebiAnnotatorTest.class); - - @Autowired - ChebiAnnotator backend; - - @Autowired - private GeneralCacheInterface cache; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetIdByName() throws Exception { - try { - MiriamData id = backend.getChebiForChebiName("adenine"); - assertEquals(new MiriamData(MiriamType.CHEBI, "CHEBI:16708"), id); - id = backend.getChebiForChebiName("asdf bvclcx lcxj vxlcvkj"); - assertNull(id); - assertNull(backend.getChebiForChebiName(null)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testNameById() throws Exception { - try { - String name = backend.getChebiNameForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708")); - assertEquals("adenine", name); - name = backend.getChebiNameForChebiId(new MiriamData(MiriamType.CHEBI, "16708")); - assertEquals("adenine", name); - name = backend.getChebiNameForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708a")); - assertNull(name); - name = backend.getChebiNameForChebiId(null); - assertNull(name); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testChebiById() throws Exception { - try { - Chebi chebi = backend.getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708")); - assertNotNull(chebi); - assertEquals("adenine", chebi.getName()); - assertEquals("Nc1ncnc2[nH]cnc12", chebi.getSmiles()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testChebiByIdWhenConnectionFails() throws Exception { - try { - cache = backend.getCache(); - // exclude first cached value - backend.setCache(null); - - ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); - - OntologyDataItem item = new OntologyDataItem(); - item.setChebiId("CHEBI:18008"); - item.setType("is a"); - - Entity entity = new Entity(); - entity.getOntologyChildren().add(item); - entity.getOntologyParents().add(item); - when(chebiWebServiceClient.getLiteEntity(any(), any(), eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())) - .thenThrow(new ChebiWebServiceFault_Exception(null, null)); - - // we will use mock object as a connection to chebi server - backend.setClient(chebiWebServiceClient); - - backend.getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708")); - fail("Exception expected"); - - } catch (ChebiSearchException e) { - assertTrue(e.getMessage().contains("Problem with chebi")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - // restore cache for other tests - backend.setCache(cache); - // remove mock - backend.setClient(null); - } - } - - @Test - public void testChebiByInvalidId() throws Exception { - try { - backend.getChebiElementForChebiId(new MiriamData(MiriamType.WIKIPEDIA, "water")); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testChebi() throws Exception { - try { - - Chebi chebi = backend.getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708")); - assertNotNull(chebi); - assertEquals("adenine", chebi.getName()); - assertEquals("Nc1ncnc2[nH]cnc12", chebi.getSmiles()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testChebiOntologyForWater() throws Exception { - try { - - Chebi chebi = backend.getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:15377")); - assertNotNull(chebi); - assertTrue(chebi.getIncomingChebi().size() > 0); - assertTrue(chebi.getOutgoingChebi().size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test(timeout = 15000) - public void testCachableInterfaceById() throws Exception { - String query = "id: CHEBI:28423"; - String newRes = "hello"; - try { - waitForRefreshCacheQueueToEmpty(); - - cache.setCachedQuery(query, backend.getCacheType(), newRes); - cache.invalidateByQuery(query, backend.getCacheType()); - - waitForRefreshCacheQueueToEmpty(); - - String res = cache.getStringByQuery(query, backend.getCacheType()); - - assertNotNull(res); - - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test(timeout = 15000) - public void testCachableInterfaceByName() throws Exception { - String query = "name: water"; - String newRes = "hello"; - try { - waitForRefreshCacheQueueToEmpty(); - - cache.setCachedQuery(query, backend.getCacheType(), newRes); - cache.invalidateByQuery(query, backend.getCacheType()); - - waitForRefreshCacheQueueToEmpty(); - - String res = cache.getStringByQuery(query, backend.getCacheType()); - - assertNotNull(res); - - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testChebiNameToId1() throws Exception { - try { - // easy tests with some molecule - MiriamData result = backend.getChebiForChebiName("L-glutamate(2-)"); - assertNotNull(result); - assertTrue(result.getResource().contains("CHEBI:29988")); - // unknown molecule - MiriamData string = backend.getChebiForChebiName("blablasblasblsabsal"); - assertNull(string); - - // and water - result = backend.getChebiForChebiName("H2O"); - assertNotNull(result); - assertTrue(result.getResource().contains("CHEBI:15377")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testChebiNameToId4() throws Exception { - try { - // easy tests with some molecule - MiriamData result = backend.getChebiForChebiName("Ca2+"); - assertEquals(new MiriamData(MiriamType.CHEBI, "CHEBI:29108"), result); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testChebiOntologyIds() throws Exception { - try { - // unknown molecule - List<MiriamData> res = backend.getOntologyChebiIdsForChebiName("blablasblasblsabsal"); - assertNotNull(res); - assertEquals(0, res.size()); - - // and water - res = backend.getOntologyChebiIdsForChebiName("h2o"); - assertNotNull(res); - assertTrue(res.size() > 1); - assertTrue(res.contains(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "CHEBI:24431"))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testChebiNameToId2() throws Exception { - try { - // and now tests more complicated (how to find hydron?) - MiriamData md = backend.getChebiForChebiName("hydron"); - assertNotNull(md); - assertTrue(md.getResource().contains("CHEBI:15378")); - md = backend.getChebiForChebiName("H+"); - assertNotNull(md); - assertTrue(md.getResource().contains("CHEBI:15378")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testChebiNameToId3() throws Exception { - try { - // and the tricky one - I couldn't find it via chebi online search tool... - // But java API do the trick... - // assertEquals("CHEBI:456214",converter.chebiNameToId("NADP+")); - // however manual mapping done by chemist says different...: - MiriamData md = backend.getChebiForChebiName("NADP+"); - assertNotNull(md); - assertTrue(md.getResource().contains("CHEBI:18009")); - md = backend.getChebiForChebiName("NADP(+)"); - assertNotNull(md); - assertTrue(md.getResource().contains("CHEBI:18009")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAnnotateChemical() throws Exception { - try { - SimpleMolecule simpleMolecule = new SimpleMolecule("id"); - simpleMolecule.setName("water"); - - backend.annotateElement(simpleMolecule); - - assertFalse(simpleMolecule.getFullName().equals("")); - assertFalse(simpleMolecule.getInChI().equals("")); - assertFalse(simpleMolecule.getInChIKey().equals("")); - assertFalse(simpleMolecule.getSmiles().equals("")); - assertFalse(simpleMolecule.getSynonyms().size() == 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAnnotateWhenConnectionFails() throws Exception { - try { - SimpleMolecule simpleMolecule = new SimpleMolecule("id"); - simpleMolecule.setName("water"); - - ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); - - OntologyDataItem item = new OntologyDataItem(); - item.setChebiId("CHEBI:18008"); - item.setType("is a"); - - Entity entity = new Entity(); - entity.getOntologyChildren().add(item); - entity.getOntologyParents().add(item); - when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.CHEBI_NAME), eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())) - .thenThrow(new ChebiWebServiceFault_Exception(null, null)); - - // we will use mock object as a connection to chebi server - backend.setClient(chebiWebServiceClient); - - backend.setCache(null); - backend.annotateElement(simpleMolecule); - - fail("Exceptione expected"); - } catch (AnnotatorException e) { - assertTrue(e.getMessage().contains("Problem with getting information about chebi")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - backend.setCache(cache); - backend.setClient(null); - } - } - - @Test - public void testAnnotateChemicalWithInvalidName() throws Exception { - try { - SimpleMolecule simpleMolecule = new SimpleMolecule("id"); - simpleMolecule.setName("blasdh"); - - backend.annotateElement(simpleMolecule); - - assertEquals(1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testUpdateChemicalFromDb() throws Exception { - try { - SimpleMolecule simpleMolecule = new SimpleMolecule("id"); - simpleMolecule.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "CHEBI:15377")); - - backend.annotateElement(simpleMolecule); - - assertFalse("".equals(simpleMolecule.getFullName())); - assertFalse(simpleMolecule.getInChI().equals("")); - assertFalse(simpleMolecule.getInChIKey().equals("")); - assertFalse(simpleMolecule.getSmiles().equals("")); - assertFalse(simpleMolecule.getSynonyms().size() == 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testUpdateChemicalFromDbWithDifferentData() throws Exception { - try { - SimpleMolecule simpleMolecule = new SimpleMolecule("id"); - simpleMolecule.setName("water"); - simpleMolecule.setFullName("xxx"); - simpleMolecule.setInChI("x"); - simpleMolecule.setInChIKey("x"); - simpleMolecule.setSmiles("x"); - simpleMolecule.addSynonym("x"); - simpleMolecule.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "CHEBI:15377")); - - backend.annotateElement(simpleMolecule); - - assertEquals(5, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() throws Exception { - try { - assertNotNull(backend.getCommonName()); - assertNotNull(backend.getUrl()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefreshGetOntology() throws Exception { - cache = backend.getCache(); - try { - // exclude first cached value - backend.setCache(null); - - ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); - - OntologyDataItem item = new OntologyDataItem(); - item.setChebiId("CHEBI:18008"); - item.setType("is a"); - - Entity entity = new Entity(); - entity.getOntologyChildren().add(item); - entity.getOntologyParents().add(item); - when(chebiWebServiceClient.getCompleteEntity(any(String.class))).thenReturn(entity); - - // we will use mock object as a connection to chebi server - backend.setClient(chebiWebServiceClient); - - String query = ChebiAnnotator.ONTOLOGY_PREFIX + "CHEBI:18009"; - String result = backend.refreshCacheQuery(query); - assertNotNull(result); - assertTrue(result.contains("CHEBI:18008")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - // restore cache for other tests - backend.setCache(cache); - // remove mock - backend.setClient(null); - } - } - - @Test - public void testGetChebiForChebiNameInFormula() throws Exception { - cache = backend.getCache(); - try { - String chebiId = "CHEBI:18008"; - String name = "art_name"; - DataItem matchedElement = new DataItem(); - matchedElement.setData(name); - // exclude first cached value - backend.setCache(null); - - ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); - - OntologyDataItem item = new OntologyDataItem(); - - Entity entity = new Entity(); - entity.getOntologyChildren().add(item); - entity.getOntologyParents().add(item); - entity.setChebiAsciiName(""); - entity.getFormulae().add(matchedElement); - entity.setChebiId(chebiId); - - when(chebiWebServiceClient.getCompleteEntity(any(String.class))).thenReturn(entity); - LiteEntityList liteEntityList = new LiteEntityList(); - - LiteEntity liteEntity = new LiteEntity(); - liteEntityList.getListElement().add(liteEntity); - when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.CHEBI_NAME), eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())) - .thenReturn(liteEntityList); - - // we will use mock object as a connection to chebi server - backend.setClient(chebiWebServiceClient); - - MiriamData result = backend.getChebiForChebiName(name); - assertNotNull(result); - assertEquals(chebiId, result.getResource()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - // restore cache for other tests - backend.setCache(cache); - // remove mock - backend.setClient(null); - } - } - - @Test - public void testGetChebiForChebiNameInFormula2() throws Exception { - cache = backend.getCache(); - try { - String chebiId = "CHEBI:18008"; - String name = "art_name"; - DataItem matchedElement = new DataItem(); - matchedElement.setData(name); - // exclude first cached value - backend.setCache(null); - - ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); - - OntologyDataItem item = new OntologyDataItem(); - - Entity entity = new Entity(); - entity.getOntologyChildren().add(item); - entity.getOntologyParents().add(item); - entity.setChebiAsciiName(""); - entity.getFormulae().add(matchedElement); - entity.setChebiId(chebiId); - - when(chebiWebServiceClient.getCompleteEntity(any(String.class))).thenReturn(entity); - LiteEntityList liteEntityList = new LiteEntityList(); - - LiteEntity liteEntity = new LiteEntity(); - liteEntityList.getListElement().add(liteEntity); - // when searching by name return empty list - when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.CHEBI_NAME), eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())) - .thenReturn(new LiteEntityList()); - // when searchng by all return list with elements - when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.ALL), eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())) - .thenReturn(liteEntityList); - - // we will use mock object as a connection to chebi server - backend.setClient(chebiWebServiceClient); - - MiriamData result = backend.getChebiForChebiName(name); - assertNotNull(result); - assertEquals(chebiId, result.getResource()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - // restore cache for other tests - backend.setCache(cache); - // remove mock - backend.setClient(null); - } - } - - @Test - public void testGetChebiForChebiNameInSynonym() throws Exception { - cache = backend.getCache(); - try { - String chebiId = "CHEBI:18008"; - String name = "art_name"; - DataItem matchedElement = new DataItem(); - matchedElement.setData(name); - // exclude first cached value - backend.setCache(null); - - ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); - - OntologyDataItem item = new OntologyDataItem(); - - Entity entity = new Entity(); - entity.getOntologyChildren().add(item); - entity.getOntologyParents().add(item); - entity.setChebiAsciiName(""); - entity.getSynonyms().add(matchedElement); - entity.setChebiId(chebiId); - - when(chebiWebServiceClient.getCompleteEntity(any(String.class))).thenReturn(entity); - LiteEntityList liteEntityList = new LiteEntityList(); - - LiteEntity liteEntity = new LiteEntity(); - liteEntityList.getListElement().add(liteEntity); - when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.CHEBI_NAME), eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())) - .thenReturn(liteEntityList); - - // we will use mock object as a connection to chebi server - backend.setClient(chebiWebServiceClient); - - MiriamData result = backend.getChebiForChebiName(name); - assertNotNull(result); - assertEquals(chebiId, result.getResource()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - // restore cache for other tests - backend.setCache(cache); - // remove mock - backend.setClient(null); - } - } - - @Test - public void testGetChebiForChebiNameInSynonym2() throws Exception { - cache = backend.getCache(); - try { - String chebiId = "CHEBI:18008"; - String name = "art_name"; - DataItem matchedElement = new DataItem(); - matchedElement.setData(name); - // exclude first cached value - backend.setCache(null); - - ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); - - OntologyDataItem item = new OntologyDataItem(); - - Entity entity = new Entity(); - entity.getOntologyChildren().add(item); - entity.getOntologyParents().add(item); - entity.setChebiAsciiName(""); - entity.getSynonyms().add(matchedElement); - entity.setChebiId(chebiId); - - when(chebiWebServiceClient.getCompleteEntity(any(String.class))).thenReturn(entity); - LiteEntityList liteEntityList = new LiteEntityList(); - - LiteEntity liteEntity = new LiteEntity(); - liteEntityList.getListElement().add(liteEntity); - // when searching by name return empty list - when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.CHEBI_NAME), eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())) - .thenReturn(new LiteEntityList()); - // when searchng by all return list with elements - when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.ALL), eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())) - .thenReturn(liteEntityList); - - // we will use mock object as a connection to chebi server - backend.setClient(chebiWebServiceClient); - - MiriamData result = backend.getChebiForChebiName(name); - assertNotNull(result); - assertEquals(chebiId, result.getResource()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - // restore cache for other tests - backend.setCache(cache); - // remove mock - backend.setClient(null); - } - } - - @Test - public void testGetChebiForChebiNameWithConnectionProblems() throws Exception { - cache = backend.getCache(); - try { - // exclude first cached value - backend.setCache(null); - - ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); - - // when searching by name return empty list - when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.CHEBI_NAME), eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())) - .thenThrow(new ChebiWebServiceFault_Exception(null, null)); - - // we will use mock object as a connection to chebi server - backend.setClient(chebiWebServiceClient); - - backend.getChebiForChebiName("bla"); - - } catch (ChebiSearchException e) { - assertTrue(e.getMessage().contains("Problem with chebi connection")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - // restore cache for other tests - backend.setCache(cache); - // remove mock - backend.setClient(null); - } - } - - @Test - public void testRefreshWhenProblemWithConnnector() throws Exception { - cache = backend.getCache(); - try { - // exclude first cached value - backend.setCache(null); - - ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); - - OntologyDataItem item = new OntologyDataItem(); - item.setChebiId("CHEBI:18008"); - item.setType("is a"); - - Entity entity = new Entity(); - entity.getOntologyChildren().add(item); - entity.getOntologyParents().add(item); - when(chebiWebServiceClient.getCompleteEntity(any(String.class))).thenThrow(new ChebiWebServiceFault_Exception(null, null)); - - // we will use mock object as a connection to chebi server - backend.setClient(chebiWebServiceClient); - - String query = ChebiAnnotator.ONTOLOGY_PREFIX + "CHEBI:18009"; - backend.refreshCacheQuery(query); - fail("Exception expected"); - - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - // restore cache for other tests - backend.setCache(cache); - // remove mock - backend.setClient(null); - } - } - - @Test - public void testRefreshInvalidQuery() throws Exception { - try { - backend.refreshCacheQuery("invalid string"); - - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefreshInvalidQuery2() throws Exception { - try { - backend.refreshCacheQuery(new Object()); - - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, backend.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSimulateDownStatus() throws Exception { - backend.setCache(null); - try { - ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); - when(chebiWebServiceClient.getLiteEntity(any(), any(), eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())) - .thenThrow(new ChebiWebServiceFault_Exception(null, null)); - backend.setClient(chebiWebServiceClient); - assertEquals(ExternalServiceStatusType.DOWN, backend.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - backend.setCache(cache); - backend.setClient(null); - } - } - - @Test - public void testSimulateChangedStatus() throws Exception { - backend.setCache(null); - try { - ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); - backend.setClient(chebiWebServiceClient); - - String chebiId = "CHEBI:18008"; - String name = "art"; - DataItem matchedElement = new DataItem(); - matchedElement.setData(name); - // exclude first cached value - backend.setCache(null); - - OntologyDataItem item = new OntologyDataItem(); - - Entity entity = new Entity(); - entity.getOntologyChildren().add(item); - entity.getOntologyParents().add(item); - entity.setChebiAsciiName(""); - entity.getSynonyms().add(matchedElement); - entity.setChebiId(chebiId); - - when(chebiWebServiceClient.getCompleteEntity(any(String.class))).thenReturn(entity); - LiteEntityList liteEntityList = new LiteEntityList(); - - LiteEntity liteEntity = new LiteEntity(); - liteEntityList.getListElement().add(liteEntity); - when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.CHEBI_NAME), eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())) - .thenReturn(liteEntityList); - when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.ALL), eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())) - .thenReturn(liteEntityList); - - assertEquals(ExternalServiceStatusType.CHANGED, backend.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - backend.setCache(cache); - backend.setClient(null); - } - } + static Logger logger = Logger.getLogger(ChebiAnnotatorTest.class); + + @Autowired + ChebiAnnotator backend; + + @Autowired + private GeneralCacheInterface cache; + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetIdByName() throws Exception { + try { + MiriamData id = backend.getChebiForChebiName("adenine"); + assertEquals(new MiriamData(MiriamType.CHEBI, "CHEBI:16708"), id); + id = backend.getChebiForChebiName("asdf bvclcx lcxj vxlcvkj"); + assertNull(id); + assertNull(backend.getChebiForChebiName(null)); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testNameById() throws Exception { + try { + String name = backend.getChebiNameForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708")); + assertEquals("adenine", name); + name = backend.getChebiNameForChebiId(new MiriamData(MiriamType.CHEBI, "16708")); + assertEquals("adenine", name); + name = backend.getChebiNameForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708a")); + assertNull(name); + name = backend.getChebiNameForChebiId(null); + assertNull(name); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testChebiById() throws Exception { + try { + Chebi chebi = backend.getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708")); + assertNotNull(chebi); + assertEquals("adenine", chebi.getName()); + assertEquals("Nc1ncnc2[nH]cnc12", chebi.getSmiles()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testChebiByIdWhenConnectionFails() throws Exception { + try { + cache = backend.getCache(); + // exclude first cached value + backend.setCache(null); + + ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); + + OntologyDataItem item = new OntologyDataItem(); + item.setChebiId("CHEBI:18008"); + item.setType("is a"); + + Entity entity = new Entity(); + entity.getOntologyChildren().add(item); + entity.getOntologyParents().add(item); + when(chebiWebServiceClient.getLiteEntity(any(), any(), eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), + any())).thenThrow(new ChebiWebServiceFault_Exception(null, null)); + + // we will use mock object as a connection to chebi server + backend.setClient(chebiWebServiceClient); + + backend.getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708")); + fail("Exception expected"); + + } catch (ChebiSearchException e) { + assertTrue(e.getMessage().contains("Problem with chebi")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + // restore cache for other tests + backend.setCache(cache); + // remove mock + backend.setClient(null); + } + } + + @Test + public void testChebiByInvalidId() throws Exception { + try { + backend.getChebiElementForChebiId(new MiriamData(MiriamType.WIKIPEDIA, "water")); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testChebi() throws Exception { + try { + + Chebi chebi = backend.getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:16708")); + assertNotNull(chebi); + assertEquals("adenine", chebi.getName()); + assertEquals("Nc1ncnc2[nH]cnc12", chebi.getSmiles()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testChebiOntologyForWater() throws Exception { + try { + + Chebi chebi = backend.getChebiElementForChebiId(new MiriamData(MiriamType.CHEBI, "CHEBI:15377")); + assertNotNull(chebi); + assertTrue(chebi.getIncomingChebi().size() > 0); + assertTrue(chebi.getOutgoingChebi().size() > 0); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test(timeout = 15000) + public void testCachableInterfaceById() throws Exception { + String query = "id: CHEBI:28423"; + String newRes = "hello"; + try { + waitForRefreshCacheQueueToEmpty(); + + cache.setCachedQuery(query, backend.getCacheType(), newRes); + cache.invalidateByQuery(query, backend.getCacheType()); + + waitForRefreshCacheQueueToEmpty(); + + String res = cache.getStringByQuery(query, backend.getCacheType()); + + assertNotNull(res); + + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test(timeout = 15000) + public void testCachableInterfaceByName() throws Exception { + String query = "name: water"; + String newRes = "hello"; + try { + waitForRefreshCacheQueueToEmpty(); + + cache.setCachedQuery(query, backend.getCacheType(), newRes); + cache.invalidateByQuery(query, backend.getCacheType()); + + waitForRefreshCacheQueueToEmpty(); + + String res = cache.getStringByQuery(query, backend.getCacheType()); + + assertNotNull(res); + + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testChebiNameToId1() throws Exception { + try { + // easy tests with some molecule + MiriamData result = backend.getChebiForChebiName("L-glutamate(2-)"); + assertNotNull(result); + assertTrue(result.getResource().contains("CHEBI:29988")); + // unknown molecule + MiriamData string = backend.getChebiForChebiName("blablasblasblsabsal"); + assertNull(string); + + // and water + result = backend.getChebiForChebiName("H2O"); + assertNotNull(result); + assertTrue(result.getResource().contains("CHEBI:15377")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testChebiNameToId4() throws Exception { + try { + // easy tests with some molecule + MiriamData result = backend.getChebiForChebiName("Ca2+"); + assertEquals(new MiriamData(MiriamType.CHEBI, "CHEBI:29108"), result); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testChebiOntologyIds() throws Exception { + try { + // unknown molecule + List<MiriamData> res = backend.getOntologyChebiIdsForChebiName("blablasblasblsabsal"); + assertNotNull(res); + assertEquals(0, res.size()); + + // and water + res = backend.getOntologyChebiIdsForChebiName("h2o"); + assertNotNull(res); + assertTrue(res.size() > 1); + assertTrue( + res.contains(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "CHEBI:24431"))); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testChebiNameToId2() throws Exception { + try { + // and now tests more complicated (how to find hydron?) + MiriamData md = backend.getChebiForChebiName("hydron"); + assertNotNull(md); + assertTrue(md.getResource().contains("CHEBI:15378")); + md = backend.getChebiForChebiName("H+"); + assertNotNull(md); + assertTrue(md.getResource().contains("CHEBI:15378")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testChebiNameToId3() throws Exception { + try { + // and the tricky one - I couldn't find it via chebi online search tool... + // But java API do the trick... + // assertEquals("CHEBI:456214",converter.chebiNameToId("NADP+")); + // however manual mapping done by chemist says different...: + MiriamData md = backend.getChebiForChebiName("NADP+"); + assertNotNull(md); + assertTrue(md.getResource().contains("CHEBI:18009")); + md = backend.getChebiForChebiName("NADP(+)"); + assertNotNull(md); + assertTrue(md.getResource().contains("CHEBI:18009")); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testAnnotateChemical() throws Exception { + try { + SimpleMolecule simpleMolecule = new SimpleMolecule("id"); + simpleMolecule.setName("water"); + + backend.annotateElement(simpleMolecule); + + assertFalse(simpleMolecule.getFullName().equals("")); + assertFalse(simpleMolecule.getInChI().equals("")); + assertFalse(simpleMolecule.getInChIKey().equals("")); + assertFalse(simpleMolecule.getSmiles().equals("")); + assertFalse(simpleMolecule.getSynonyms().size() == 0); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testAnnotateWhenConnectionFails() throws Exception { + try { + SimpleMolecule simpleMolecule = new SimpleMolecule("id"); + simpleMolecule.setName("water"); + + ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); + + OntologyDataItem item = new OntologyDataItem(); + item.setChebiId("CHEBI:18008"); + item.setType("is a"); + + Entity entity = new Entity(); + entity.getOntologyChildren().add(item); + entity.getOntologyParents().add(item); + when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.CHEBI_NAME), + eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())) + .thenThrow(new ChebiWebServiceFault_Exception(null, null)); + + // we will use mock object as a connection to chebi server + backend.setClient(chebiWebServiceClient); + + backend.setCache(null); + backend.annotateElement(simpleMolecule); + + fail("Exceptione expected"); + } catch (AnnotatorException e) { + assertTrue(e.getMessage().contains("Problem with getting information about chebi")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + backend.setCache(cache); + backend.setClient(null); + } + } + + @Test + public void testAnnotateChemicalWithInvalidName() throws Exception { + try { + SimpleMolecule simpleMolecule = new SimpleMolecule("id"); + simpleMolecule.setName("blasdh"); + + backend.annotateElement(simpleMolecule); + + assertEquals(1, getWarnings().size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testUpdateChemicalFromDb() throws Exception { + try { + SimpleMolecule simpleMolecule = new SimpleMolecule("id"); + simpleMolecule + .addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "CHEBI:15377")); + + backend.annotateElement(simpleMolecule); + + assertFalse("".equals(simpleMolecule.getFullName())); + assertFalse(simpleMolecule.getInChI().equals("")); + assertFalse(simpleMolecule.getInChIKey().equals("")); + assertFalse(simpleMolecule.getSmiles().equals("")); + assertFalse(simpleMolecule.getSynonyms().size() == 0); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testUpdateChemicalFromDbWithDifferentData() throws Exception { + try { + SimpleMolecule simpleMolecule = new SimpleMolecule("id"); + simpleMolecule.setName("water"); + simpleMolecule.setFullName("xxx"); + simpleMolecule.setInChI("x"); + simpleMolecule.setInChIKey("x"); + simpleMolecule.setSmiles("x"); + simpleMolecule.addSynonym("x"); + simpleMolecule + .addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "CHEBI:15377")); + + backend.annotateElement(simpleMolecule); + + assertEquals(5, getWarnings().size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetters() throws Exception { + try { + assertNotNull(backend.getCommonName()); + assertNotNull(backend.getUrl()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefreshGetOntology() throws Exception { + cache = backend.getCache(); + try { + // exclude first cached value + backend.setCache(null); + + ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); + + OntologyDataItem item = new OntologyDataItem(); + item.setChebiId("CHEBI:18008"); + item.setType("is a"); + + Entity entity = new Entity(); + entity.getOntologyChildren().add(item); + entity.getOntologyParents().add(item); + when(chebiWebServiceClient.getCompleteEntity(any(String.class))).thenReturn(entity); + + // we will use mock object as a connection to chebi server + backend.setClient(chebiWebServiceClient); + + String query = ChebiAnnotator.ONTOLOGY_PREFIX + "CHEBI:18009"; + String result = backend.refreshCacheQuery(query); + assertNotNull(result); + assertTrue(result.contains("CHEBI:18008")); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + // restore cache for other tests + backend.setCache(cache); + // remove mock + backend.setClient(null); + } + } + + @Test + public void testGetChebiForChebiNameInFormula() throws Exception { + cache = backend.getCache(); + try { + String chebiId = "CHEBI:18008"; + String name = "art_name"; + DataItem matchedElement = new DataItem(); + matchedElement.setData(name); + // exclude first cached value + backend.setCache(null); + + ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); + + OntologyDataItem item = new OntologyDataItem(); + + Entity entity = new Entity(); + entity.getOntologyChildren().add(item); + entity.getOntologyParents().add(item); + entity.setChebiAsciiName(""); + entity.getFormulae().add(matchedElement); + entity.setChebiId(chebiId); + + when(chebiWebServiceClient.getCompleteEntity(any(String.class))).thenReturn(entity); + LiteEntityList liteEntityList = new LiteEntityList(); + + LiteEntity liteEntity = new LiteEntity(); + liteEntityList.getListElement().add(liteEntity); + when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.CHEBI_NAME), + eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())).thenReturn(liteEntityList); + + // we will use mock object as a connection to chebi server + backend.setClient(chebiWebServiceClient); + + MiriamData result = backend.getChebiForChebiName(name); + assertNotNull(result); + assertEquals(chebiId, result.getResource()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + // restore cache for other tests + backend.setCache(cache); + // remove mock + backend.setClient(null); + } + } + + @Test + public void testGetChebiForChebiNameInFormula2() throws Exception { + cache = backend.getCache(); + try { + String chebiId = "CHEBI:18008"; + String name = "art_name"; + DataItem matchedElement = new DataItem(); + matchedElement.setData(name); + // exclude first cached value + backend.setCache(null); + + ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); + + OntologyDataItem item = new OntologyDataItem(); + + Entity entity = new Entity(); + entity.getOntologyChildren().add(item); + entity.getOntologyParents().add(item); + entity.setChebiAsciiName(""); + entity.getFormulae().add(matchedElement); + entity.setChebiId(chebiId); + + when(chebiWebServiceClient.getCompleteEntity(any(String.class))).thenReturn(entity); + LiteEntityList liteEntityList = new LiteEntityList(); + + LiteEntity liteEntity = new LiteEntity(); + liteEntityList.getListElement().add(liteEntity); + // when searching by name return empty list + when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.CHEBI_NAME), + eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())).thenReturn(new LiteEntityList()); + // when searchng by all return list with elements + when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.ALL), + eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())).thenReturn(liteEntityList); + + // we will use mock object as a connection to chebi server + backend.setClient(chebiWebServiceClient); + + MiriamData result = backend.getChebiForChebiName(name); + assertNotNull(result); + assertEquals(chebiId, result.getResource()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + // restore cache for other tests + backend.setCache(cache); + // remove mock + backend.setClient(null); + } + } + + @Test + public void testGetChebiForChebiNameInSynonym() throws Exception { + cache = backend.getCache(); + try { + String chebiId = "CHEBI:18008"; + String name = "art_name"; + DataItem matchedElement = new DataItem(); + matchedElement.setData(name); + // exclude first cached value + backend.setCache(null); + + ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); + + OntologyDataItem item = new OntologyDataItem(); + + Entity entity = new Entity(); + entity.getOntologyChildren().add(item); + entity.getOntologyParents().add(item); + entity.setChebiAsciiName(""); + entity.getSynonyms().add(matchedElement); + entity.setChebiId(chebiId); + + when(chebiWebServiceClient.getCompleteEntity(any(String.class))).thenReturn(entity); + LiteEntityList liteEntityList = new LiteEntityList(); + + LiteEntity liteEntity = new LiteEntity(); + liteEntityList.getListElement().add(liteEntity); + when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.CHEBI_NAME), + eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())).thenReturn(liteEntityList); + + // we will use mock object as a connection to chebi server + backend.setClient(chebiWebServiceClient); + + MiriamData result = backend.getChebiForChebiName(name); + assertNotNull(result); + assertEquals(chebiId, result.getResource()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + // restore cache for other tests + backend.setCache(cache); + // remove mock + backend.setClient(null); + } + } + + @Test + public void testGetChebiForChebiNameInSynonym2() throws Exception { + cache = backend.getCache(); + try { + String chebiId = "CHEBI:18008"; + String name = "art_name"; + DataItem matchedElement = new DataItem(); + matchedElement.setData(name); + // exclude first cached value + backend.setCache(null); + + ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); + + OntologyDataItem item = new OntologyDataItem(); + + Entity entity = new Entity(); + entity.getOntologyChildren().add(item); + entity.getOntologyParents().add(item); + entity.setChebiAsciiName(""); + entity.getSynonyms().add(matchedElement); + entity.setChebiId(chebiId); + + when(chebiWebServiceClient.getCompleteEntity(any(String.class))).thenReturn(entity); + LiteEntityList liteEntityList = new LiteEntityList(); + + LiteEntity liteEntity = new LiteEntity(); + liteEntityList.getListElement().add(liteEntity); + // when searching by name return empty list + when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.CHEBI_NAME), + eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())).thenReturn(new LiteEntityList()); + // when searchng by all return list with elements + when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.ALL), + eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())).thenReturn(liteEntityList); + + // we will use mock object as a connection to chebi server + backend.setClient(chebiWebServiceClient); + + MiriamData result = backend.getChebiForChebiName(name); + assertNotNull(result); + assertEquals(chebiId, result.getResource()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + // restore cache for other tests + backend.setCache(cache); + // remove mock + backend.setClient(null); + } + } + + @Test + public void testGetChebiForChebiNameWithConnectionProblems() throws Exception { + cache = backend.getCache(); + try { + // exclude first cached value + backend.setCache(null); + + ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); + + // when searching by name return empty list + when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.CHEBI_NAME), + eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())) + .thenThrow(new ChebiWebServiceFault_Exception(null, null)); + + // we will use mock object as a connection to chebi server + backend.setClient(chebiWebServiceClient); + + backend.getChebiForChebiName("bla"); + + } catch (ChebiSearchException e) { + assertTrue(e.getMessage().contains("Problem with chebi connection")); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + // restore cache for other tests + backend.setCache(cache); + // remove mock + backend.setClient(null); + } + } + + @Test + public void testRefreshWhenProblemWithConnnector() throws Exception { + cache = backend.getCache(); + try { + // exclude first cached value + backend.setCache(null); + + ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); + + OntologyDataItem item = new OntologyDataItem(); + item.setChebiId("CHEBI:18008"); + item.setType("is a"); + + Entity entity = new Entity(); + entity.getOntologyChildren().add(item); + entity.getOntologyParents().add(item); + when(chebiWebServiceClient.getCompleteEntity(any(String.class))) + .thenThrow(new ChebiWebServiceFault_Exception(null, null)); + + // we will use mock object as a connection to chebi server + backend.setClient(chebiWebServiceClient); + + String query = ChebiAnnotator.ONTOLOGY_PREFIX + "CHEBI:18009"; + backend.refreshCacheQuery(query); + fail("Exception expected"); + + } catch (SourceNotAvailable e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + // restore cache for other tests + backend.setCache(cache); + // remove mock + backend.setClient(null); + } + } + + @Test + public void testRefreshInvalidQuery() throws Exception { + try { + backend.refreshCacheQuery("invalid string"); + + fail("Exception expected"); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Don't know what to do")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefreshInvalidQuery2() throws Exception { + try { + backend.refreshCacheQuery(new Object()); + + fail("Exception expected"); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Don't know what to do")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testStatus() throws Exception { + try { + assertEquals(ExternalServiceStatusType.OK, backend.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testSimulateDownStatus() throws Exception { + backend.setCache(null); + try { + ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); + when(chebiWebServiceClient.getLiteEntity(any(), any(), eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), + any())).thenThrow(new ChebiWebServiceFault_Exception(null, null)); + backend.setClient(chebiWebServiceClient); + assertEquals(ExternalServiceStatusType.DOWN, backend.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + backend.setCache(cache); + backend.setClient(null); + } + } + + @Test + public void testSimulateChangedStatus() throws Exception { + backend.setCache(null); + try { + ChebiWebServiceClient chebiWebServiceClient = Mockito.mock(ChebiWebServiceClient.class); + backend.setClient(chebiWebServiceClient); + + String chebiId = "CHEBI:18008"; + String name = "art"; + DataItem matchedElement = new DataItem(); + matchedElement.setData(name); + // exclude first cached value + backend.setCache(null); + + OntologyDataItem item = new OntologyDataItem(); + + Entity entity = new Entity(); + entity.getOntologyChildren().add(item); + entity.getOntologyParents().add(item); + entity.setChebiAsciiName(""); + entity.getSynonyms().add(matchedElement); + entity.setChebiId(chebiId); + + when(chebiWebServiceClient.getCompleteEntity(any(String.class))).thenReturn(entity); + LiteEntityList liteEntityList = new LiteEntityList(); + + LiteEntity liteEntity = new LiteEntity(); + liteEntityList.getListElement().add(liteEntity); + when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.CHEBI_NAME), + eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())).thenReturn(liteEntityList); + when(chebiWebServiceClient.getLiteEntity(any(), eq(SearchCategory.ALL), + eq(ChebiAnnotator.MAX_SEARCH_RESULTS_FROM_CHEBI_API), any())).thenReturn(liteEntityList); + + assertEquals(ExternalServiceStatusType.CHANGED, backend.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + backend.setCache(cache); + backend.setClient(null); + } + } } diff --git a/frontend-js/src/main/js/gui/leftPanel/GuiUtils.js b/frontend-js/src/main/js/gui/leftPanel/GuiUtils.js index 8c6f1b1208d5dfb3d231a3be95c691aa64740556..033761cb459461969bd3e7476027be35e5222e7e 100644 --- a/frontend-js/src/main/js/gui/leftPanel/GuiUtils.js +++ b/frontend-js/src/main/js/gui/leftPanel/GuiUtils.js @@ -16,29 +16,29 @@ function GuiUtils(configuration) { GuiUtils.prototype = Object.create(AbstractGuiElement.prototype); GuiUtils.prototype.constructor = GuiUtils; -GuiUtils.prototype.setConfiguration = function(configuration) { +GuiUtils.prototype.setConfiguration = function (configuration) { this._configuration = configuration; }; -GuiUtils.prototype.getConfiguration = function() { +GuiUtils.prototype.getConfiguration = function () { return this._configuration; }; -GuiUtils.prototype.createLabel = function(value) { +GuiUtils.prototype.createLabel = function (value) { var result = document.createElement("span"); result.innerHTML = value; result.className = "minerva-label"; return result; }; -GuiUtils.prototype.createPostTranslationalModifications = function(label, value) { +GuiUtils.prototype.createPostTranslationalModifications = function (label, value) { var result = document.createElement("div"); if (value !== undefined && value.length > 0) { var self = this; result.appendChild(self.createLabel(label)); result.appendChild(self.createNewLine()); var list = Functions.createElement({ - type : "ul" + type: "ul" }); for (var i = 0; i < value.length; i++) { var name = value[i].name; @@ -51,7 +51,7 @@ GuiUtils.prototype.createPostTranslationalModifications = function(label, value) desc = state + ","; } var row = Functions.createElement({ - type : "li" + type: "li" }); row.appendChild(self.createLabelText(desc)); list.appendChild(row); @@ -61,7 +61,7 @@ GuiUtils.prototype.createPostTranslationalModifications = function(label, value) return result; }; -GuiUtils.prototype.createCandidates = function(label, value) { +GuiUtils.prototype.createCandidates = function (label, value) { var result = document.createElement("div"); if (value !== undefined) { throw new Error("Not implemented"); @@ -69,19 +69,19 @@ GuiUtils.prototype.createCandidates = function(label, value) { return result; }; -GuiUtils.prototype.createChebiTree = function(label, value) { +GuiUtils.prototype.createChebiTree = function (label, value) { var result = document.createElement("div"); if (value !== undefined) { throw new Error("Not implemented"); } return result; }; -GuiUtils.prototype.createSeparator = function() { +GuiUtils.prototype.createSeparator = function () { var result = document.createElement("hr"); return result; }; -GuiUtils.prototype.createNewLine = function(count) { +GuiUtils.prototype.createNewLine = function (count) { var result = document.createElement("p"); if (count > 0) { result.style.height = ((count - 1) * 10) + "px"; @@ -89,7 +89,15 @@ GuiUtils.prototype.createNewLine = function(count) { return result; }; -GuiUtils.prototype.createLink = function(url, name) { +GuiUtils.prototype.createLink = function (url, name) { + if (url === null || url === undefined) { + logger.warn("URL not defined for: \"" + name + "\" link"); + return Functions.createElement( + { + type: "span", + content: name + }); + } var link = document.createElement("a"); link.href = url; link.innerHTML = name; @@ -98,14 +106,14 @@ GuiUtils.prototype.createLink = function(url, name) { return link; }; -GuiUtils.prototype.createAnnotationLink = function(annotation, showType) { +GuiUtils.prototype.createAnnotationLink = function (annotation, showType) { var self = this; var name, type, hint; var article = annotation.getArticle(); if (article !== undefined) { hint = article.getTitle() + " " + article.getAuthors().join(", ") + ", " + article.getYear() + ", " - + article.getJournal(); + + article.getJournal(); type = "PUBMED"; name = article.getId(); } else { @@ -134,7 +142,7 @@ GuiUtils.prototype.createAnnotationLink = function(annotation, showType) { } }; -GuiUtils.prototype.createAnnotations = function(label, value, options) { +GuiUtils.prototype.createAnnotations = function (label, value, options) { var self = this; var inline = false; @@ -156,7 +164,7 @@ GuiUtils.prototype.createAnnotations = function(label, value, options) { return result; }; -GuiUtils.prototype.createAnnotationList = function(annotations, options) { +GuiUtils.prototype.createAnnotationList = function (annotations, options) { var showType = true; var inline = false; if (options !== undefined) { @@ -205,7 +213,7 @@ GuiUtils.prototype.createAnnotationList = function(annotations, options) { return result; }; -GuiUtils.prototype.createLabelText = function(value) { +GuiUtils.prototype.createLabelText = function (value) { var result = document.createElement("span"); if (value !== undefined) { result.innerHTML = value; @@ -213,7 +221,7 @@ GuiUtils.prototype.createLabelText = function(value) { return result; }; -GuiUtils.prototype.createInputText = function(value) { +GuiUtils.prototype.createInputText = function (value) { var result = document.createElement("input"); result.setAttribute('type', 'text'); @@ -223,7 +231,7 @@ GuiUtils.prototype.createInputText = function(value) { return result; }; -GuiUtils.prototype.createTextArea = function(value) { +GuiUtils.prototype.createTextArea = function (value) { var result = document.createElement("textarea"); if (value !== undefined) { @@ -233,7 +241,7 @@ GuiUtils.prototype.createTextArea = function(value) { return result; }; -GuiUtils.prototype.createParamLine = function(label, value) { +GuiUtils.prototype.createParamLine = function (label, value) { var result = document.createElement("div"); if (value !== undefined && value !== null && value !== "") { var self = this; @@ -243,7 +251,7 @@ GuiUtils.prototype.createParamLine = function(label, value) { return result; }; -GuiUtils.prototype.createIcon = function(icon) { +GuiUtils.prototype.createIcon = function (icon) { var result = document.createElement("div"); if (icon !== undefined && icon !== null) { var img = document.createElement("img"); @@ -255,7 +263,7 @@ GuiUtils.prototype.createIcon = function(icon) { return result; }; -GuiUtils.prototype.createArrayParamLine = function(label, value) { +GuiUtils.prototype.createArrayParamLine = function (label, value) { var result = document.createElement("div"); if (value !== undefined && value.length > 0) { var self = this; @@ -265,7 +273,7 @@ GuiUtils.prototype.createArrayParamLine = function(label, value) { return result; }; -GuiUtils.prototype.createSubMapLink = function(label, modelId) { +GuiUtils.prototype.createSubMapLink = function (label, modelId) { var self = this; var result = document.createElement("div"); if (modelId !== undefined) { @@ -273,7 +281,7 @@ GuiUtils.prototype.createSubMapLink = function(label, modelId) { var model = self.getMap().getSubmapById(modelId).getModel(); button.innerHTML = model.getName(); - button.onclick = function() { + button.onclick = function () { return self.getMap().openSubmap(modelId); }; result.appendChild(this.createLabel(label)); @@ -282,16 +290,16 @@ GuiUtils.prototype.createSubMapLink = function(label, modelId) { return result; }; -GuiUtils.prototype.createTableRow = function(elements) { +GuiUtils.prototype.createTableRow = function (elements) { var row = Functions.createElement({ - type : "div", - style : "display: table-row;" + type: "div", + style: "display: table-row;" }); for (var i = 0; i < elements.length; i++) { var cell = Functions.createElement({ - type : "div", - style : "display: table-cell;" + type: "div", + style: "display: table-cell;" }); cell.appendChild(elements[i]); row.appendChild(cell); @@ -299,7 +307,7 @@ GuiUtils.prototype.createTableRow = function(elements) { return row; }; -GuiUtils.prototype.createReactionElement = function(params) { +GuiUtils.prototype.createReactionElement = function (params) { var reaction = params.reaction; var showTitle = ((params.showTitle === undefined) || params.showTitle); var self = this; @@ -338,7 +346,7 @@ GuiUtils.prototype.createReactionElement = function(params) { return div; }; -GuiUtils.prototype.createAliasElement = function(params) { +GuiUtils.prototype.createAliasElement = function (params) { var alias = params.alias; var icon = params.icon; var showTitle = ((params.showTitle === undefined) || params.showTitle); @@ -378,7 +386,7 @@ GuiUtils.prototype.createAliasElement = function(params) { return div; }; -GuiUtils.prototype.createReactantsLine = function(label, value) { +GuiUtils.prototype.createReactantsLine = function (label, value) { var result = document.createElement("div"); if (value !== undefined && value.length > 0) { for (var i = 0; i < value.length; i++) { @@ -388,7 +396,7 @@ GuiUtils.prototype.createReactantsLine = function(label, value) { return result; }; -GuiUtils.prototype.createProductsLine = function(label, value) { +GuiUtils.prototype.createProductsLine = function (label, value) { var result = document.createElement("div"); if (value !== undefined && value.length > 0) { for (var i = 0; i < value.length; i++) { @@ -398,7 +406,7 @@ GuiUtils.prototype.createProductsLine = function(label, value) { return result; }; -GuiUtils.prototype.createModifiersLine = function(label, value) { +GuiUtils.prototype.createModifiersLine = function (label, value) { var result = document.createElement("div"); if (value !== undefined && value.length > 0) { for (var i = 0; i < value.length; i++) { diff --git a/frontend-js/src/test/js/gui/leftPanel/ChemicalPanel-test.js b/frontend-js/src/test/js/gui/leftPanel/ChemicalPanel-test.js index cdf1b7d628afabeedd4e68601871886aa4bf3f29..6f3bd39d72aa093ec09a6eaf0127f7697dde084e 100644 --- a/frontend-js/src/test/js/gui/leftPanel/ChemicalPanel-test.js +++ b/frontend-js/src/test/js/gui/leftPanel/ChemicalPanel-test.js @@ -83,7 +83,7 @@ describe('ChemicalPanel', function() { }); return chemicalDbOverlay.searchByQuery("rotenone").then(function() { - assert.equal(logger.getWarnings().length, 0); + assert.equal(logger.getWarnings().length, 1); assert.ok(testDiv.innerHTML.indexOf("marker/mechanism") >= 0); }); }); @@ -101,7 +101,7 @@ describe('ChemicalPanel', function() { panel.getControlElement(PanelControlElementType.SEARCH_INPUT).value = "rotenone"; return panel.searchByQuery().then(function() { - assert.equal(logger.getWarnings().length, 0); + assert.equal(logger.getWarnings().length, 1); assert.ok(testDiv.innerHTML.indexOf("Rotenone ") >= 0); }); }); diff --git a/frontend-js/src/test/js/gui/leftPanel/GuiUtils-test.js b/frontend-js/src/test/js/gui/leftPanel/GuiUtils-test.js index f179817e800fb620d2217dbc41a8e66ed20460dd..c31b71809fb86bbd19dd6824ef8d395dde69e267 100644 --- a/frontend-js/src/test/js/gui/leftPanel/GuiUtils-test.js +++ b/frontend-js/src/test/js/gui/leftPanel/GuiUtils-test.js @@ -9,7 +9,7 @@ var chai = require('chai'); var assert = chai.assert; var logger = require('../../logger'); -describe('GuiUtils', function() { +describe('GuiUtils', function () { it('constructor', function() { var map = helper.createCustomMap(); @@ -19,7 +19,7 @@ describe('GuiUtils', function() { assert.equal(logger.getWarnings().length, 0); }); - it('default', function() { + it('default', function () { var aliasObj = { symbol : "S1_SYMBOL", formerSymbols : [], @@ -35,9 +35,9 @@ describe('GuiUtils', function() { width : 70.0, height : 25.0 }, - formula : "FORMULA", - id : 380217, - references : [], + formula: "FORMULA", + id: 380217, + references: [] }; var alias = new Alias(aliasObj); @@ -49,12 +49,12 @@ describe('GuiUtils', function() { guiUtils.setMap(map); var aliasDiv = guiUtils.createAliasElement({ - alias : alias + alias: alias }); assert.ok(aliasDiv.innerHTML); }); - it('createLabelText for undefined', function() { + it('createLabelText for undefined', function () { var map = helper.createCustomMap(); var guiUtils = new GuiUtils(); @@ -64,7 +64,7 @@ describe('GuiUtils', function() { assert.notOk(res.innerHTML); }); - it('createSubMapLink', function() { + it('createSubMapLink', function () { var map = helper.createCustomMap(); var guiUtils = new GuiUtils(); @@ -74,22 +74,22 @@ describe('GuiUtils', function() { assert.ok(res.innerHTML); }); - it('createPostTranslationalModifications', function() { + it('createPostTranslationalModifications', function () { var alias = helper.createAlias(); alias.setOther({ - "modifications" : [ { - "name" : "S63", - "state" : "PHOSPHORYLATED" + "modifications": [{ + "name": "S63", + "state": "PHOSPHORYLATED" }, { - "name" : "S73", - "state" : "PHOSPHORYLATED" + "name": "S73", + "state": "PHOSPHORYLATED" }, { - "name" : "", - "state" : "PHOSPHORYLATED" + "name": "", + "state": "PHOSPHORYLATED" }, { - "name" : null, - "state" : "PHOSPHORYLATED" - } ] + "name": null, + "state": "PHOSPHORYLATED" + }] }); var utils = new GuiUtils(helper.getConfiguration()); @@ -98,8 +98,8 @@ describe('GuiUtils', function() { assert.ok(res.innerHTML.indexOf("phosphorylated") >= 0); }); - describe('createReactionElement', function() { - it('type in desc', function() { + describe('createReactionElement', function () { + it('type in desc', function () { var map = helper.createCustomMap(); helper.createSearchDbOverlay(map); @@ -111,13 +111,13 @@ describe('GuiUtils', function() { reaction.setType(reactionType); assert.ok(guiUtils.createReactionElement({ - reaction : reaction + reaction: reaction }).innerHTML.indexOf(reactionType) >= 0); }); }); - describe('createAliasElement', function() { - it('full name in desc', function() { + describe('createAliasElement', function () { + it('full name in desc', function () { var map = helper.createCustomMap(); helper.createSearchDbOverlay(map); @@ -127,14 +127,30 @@ describe('GuiUtils', function() { alias.setFullName("xxx"); assert.ok(guiUtils.createAliasElement({ - alias : alias + alias: alias }).innerHTML.indexOf("Full name") >= 0); alias.setFullName(""); assert.ok(guiUtils.createAliasElement({ - alias : alias + alias: alias }).innerHTML.indexOf("Full name") === -1); }); }); + describe('createLink', function () { + it('normal', function () { + var guiUtils = new GuiUtils(); + var link = guiUtils.createLink("http://www.minerva.uni.lu", "PD map"); + assert.ok(link); + assert.equal(0, logger.getWarnings().length); + }); + + it('with null link', function () { + var guiUtils = new GuiUtils(); + var link = guiUtils.createLink(null, "PD map"); + assert.ok(link); + assert.ok(logger.getWarnings().length > 0); + }); + }); + }); diff --git a/frontend-js/src/test/js/gui/leftPanel/LeftPanel-test.js b/frontend-js/src/test/js/gui/leftPanel/LeftPanel-test.js index 95051feab6a7431e00e031bd1031b6bf47dc0ef4..9d74a1f651204063fabd7b856551e8c75f743adf 100644 --- a/frontend-js/src/test/js/gui/leftPanel/LeftPanel-test.js +++ b/frontend-js/src/test/js/gui/leftPanel/LeftPanel-test.js @@ -13,80 +13,80 @@ var logger = require('../../logger'); describe('LeftPanel', function () { - it('constructor', function () { - var map = helper.createCustomMap(); + it('constructor', function () { + var map = helper.createCustomMap(); + helper.createSearchDbOverlay(map); + helper.createDrugDbOverlay(map); + helper.createChemicalDbOverlay(map); + helper.createMiRnaDbOverlay(map); + + var panel = new LeftPanel({ + element: testDiv, + customMap: map + }); + + assert.equal(logger.getWarnings().length, 0); + + return panel.destroy(); + }); + + describe('prepareElementDetailsContent', function () { + it('for element', function () { + var map; + var panel; + return ServerConnector.getProject().then(function (project) { + map = helper.createCustomMap(project); + helper.createSearchDbOverlay(map); helper.createDrugDbOverlay(map); helper.createChemicalDbOverlay(map); helper.createMiRnaDbOverlay(map); - var panel = new LeftPanel({ - element: testDiv, - customMap: map + panel = new LeftPanel({ + element: testDiv, + customMap: map }); - assert.equal(logger.getWarnings().length, 0); - + var element = new IdentifiedElement({ + id: 329163, + type: "ALIAS", + modelId: map.getId() + }); + return map.getModel().getByIdentifiedElement(element, true); + }).then(function (alias) { + var div = panel.prepareElementDetailsContent(alias); + assert.ok(div); return panel.destroy(); + }); }); + it('for point', function () { + var map; + var panel; + return ServerConnector.getProject().then(function (project) { + map = helper.createCustomMap(project); - describe('prepareElementDetailsContent', function () { - it('for element', function () { - var map; - var panel; - return ServerConnector.getProject().then(function (project) { - map = helper.createCustomMap(project); - - helper.createSearchDbOverlay(map); - helper.createDrugDbOverlay(map); - helper.createChemicalDbOverlay(map); - helper.createMiRnaDbOverlay(map); - - panel = new LeftPanel({ - element: testDiv, - customMap: map - }); - - var element = new IdentifiedElement({ - id: 329163, - type: "ALIAS", - modelId: map.getId() - }); - return map.getModel().getByIdentifiedElement(element, true); - }).then(function (alias) { - var div = panel.prepareElementDetailsContent(alias); - assert.ok(div); - return panel.destroy(); - }); + helper.createSearchDbOverlay(map); + helper.createDrugDbOverlay(map); + helper.createChemicalDbOverlay(map); + helper.createMiRnaDbOverlay(map); + + panel = new LeftPanel({ + element: testDiv, + customMap: map }); - it('for point', function () { - var map; - var panel; - return ServerConnector.getProject().then(function (project) { - map = helper.createCustomMap(project); - - helper.createSearchDbOverlay(map); - helper.createDrugDbOverlay(map); - helper.createChemicalDbOverlay(map); - helper.createMiRnaDbOverlay(map); - - panel = new LeftPanel({ - element: testDiv, - customMap: map - }); - - var element = new IdentifiedElement({ - id: "(1.00,2.00)", - type: "POINT", - modelId: map.getId() - }); - return map.getModel().getByIdentifiedElement(element, true); - }).then(function (point) { - var div = panel.prepareElementDetailsContent(point); - assert.ok(div); - return panel.destroy(); - }); + + var element = new IdentifiedElement({ + id: "(1.00,2.00)", + type: "POINT", + modelId: map.getId() }); + return map.getModel().getByIdentifiedElement(element, true); + }).then(function (point) { + var div = panel.prepareElementDetailsContent(point); + assert.ok(div); + return panel.destroy(); + }); }); + }); }); diff --git a/pom.xml b/pom.xml index c4ae7d49e1981914751eb1164fe8e0733c5f00b6..6da6fa5d7c9371f53a610c110362519bd0d1d82c 100644 --- a/pom.xml +++ b/pom.xml @@ -58,7 +58,7 @@ <gson.version>2.2.2</gson.version> - <chebi-ws.version>2.2.2</chebi-ws.version> + <chebi-ws.version>2.3.2</chebi-ws.version> <miriam-lib.version>1.1.5</miriam-lib.version>