From 3a1b80c5ab087a0b6baa0546a9c3eaf8d1614c3e Mon Sep 17 00:00:00 2001 From: "piotr.gawron" <piotr.gawron@uni-new> Date: Fri, 23 Sep 2016 11:12:06 +0200 Subject: [PATCH] temp commit SpeciesAlias implements AnnotatedObject and Element doesn't most of the tests pass --- .../services/ImproperAnnotations.java | 20 +- .../services/MissingAnnotation.java | 89 +- .../services/MissingRequiredAnnotations.java | 134 +- .../annotation/services/ModelAnnotator.java | 9 +- .../annotation/services/TaxonomyBackend.java | 2 +- .../services/annotators/ChebiAnnotator.java | 3 +- .../services/annotators/ElementAnnotator.java | 24 +- .../services/annotators/EnsemblAnnotator.java | 26 +- .../services/annotators/EntrezAnnotator.java | 22 +- .../services/annotators/GoAnnotator.java | 19 +- .../services/annotators/HgncAnnotator.java | 15 +- .../services/annotators/ReconAnnotator.java | 51 +- .../annotation/AnnotationTestFunctions.java | 8 +- .../services/DrugbankHTMLParserTest.java | 1322 +++++++------- .../services/ImproperAnnotationsTest.java | 32 +- .../services/MissingAnnotationTest.java | 3 +- .../MissingRequiredAnnotationsTest.java | 5 +- .../services/ModelAnnotatorTest.java | 30 +- .../annotators/ChebiAnnotatorTest.java | 11 +- .../annotators/ElementAnnotatorTest.java | 7 +- .../annotators/EnsemblAnnotatorTest.java | 24 +- .../annotators/EntrezAnnotatorTest.java | 13 +- .../services/annotators/GoAnnotatorTest.java | 12 +- .../annotators/HgncAnnotatorTest.java | 19 +- .../annotators/ReconAnnotatorTest.java | 19 +- .../annotators/UniprotAnnotatorTest.java | 13 +- .../lcsb/mapviewer/run/ConsoleConverter.java | 4 +- .../celldesigner/annotation/NoteField.java | 48 +- .../annotation/RestAnnotationParser.java | 5 +- .../species/AntisenseRnaXmlParser.java | 4 +- .../celldesigner/species/GeneXmlParser.java | 4 +- .../species/ProteinXmlParser.java | 4 +- .../celldesigner/species/RnaXmlParser.java | 4 +- .../species/SpeciesCollectionXmlParser.java | 3 +- .../species/SpeciesSbmlParser.java | 4 +- .../CellDesignerXmlParserTest.java | 6 +- .../annotation/RestAnnotationParserTest.java | 34 +- .../model/celldesigner/species/ModelMock.java | 6 + .../lcsb/mapviewer/model/map/Element.java | 19 +- .../model/map/layout/alias/Alias.java | 91 +- .../map/layout/alias/CompartmentAlias.java | 846 ++++----- .../lcsb/mapviewer/model/map/model/Model.java | 2 + .../model/map/model/ModelFullIndexed.java | 34 +- .../modelutils/map/ElementUtils.java | 8 +- .../modelutils/map/RequireAnnotationMap.java | 25 +- .../map/layout/alias/AliasComparatorTest.java | 473 +++-- .../model/map/model/ModelFullIndexedTest.java | 6 +- .../mapviewer/model/map/model/ModelTest.java | 28 +- .../wikipathway/XML/ModelContructor.java | 4 +- .../wikipathway/XML/ModelToGPML.java | 5 +- .../services/impl/SearchService.java | 1562 +++++++++-------- .../services/search/db/TargetViewFactory.java | 4 +- .../view/PubmedAnnotatedElementsView.java | 213 +-- 53 files changed, 2848 insertions(+), 2530 deletions(-) diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ImproperAnnotations.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ImproperAnnotations.java index f45364d877..a9bad2ed25 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ImproperAnnotations.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ImproperAnnotations.java @@ -6,6 +6,7 @@ import java.util.List; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.AnnotatedObject; import lcsb.mapviewer.model.map.MiriamData; +import lcsb.mapviewer.model.map.layout.alias.Alias; import lcsb.mapviewer.modelutils.map.ElementUtils; /** @@ -28,20 +29,6 @@ public class ImproperAnnotations implements ProblematicAnnotation { */ private List<MiriamData> wrongAnnotations = new ArrayList<>(); - /** - * Constructor that initializes the data with miriam annotation for element. - * - * @param md - * miriam annotation - */ - public ImproperAnnotations(MiriamData md) { - if (md.getElement() == null) { - throw new InvalidArgumentException("Only miriam data from elements are accepted"); - } - this.wrongAnnotations.add(md); - this.object = md.getElement(); - } - /** * Constructor that initializes the data with {@link #object annotated object} * and list of improper {@link MiriamData}. @@ -55,6 +42,11 @@ public class ImproperAnnotations implements ProblematicAnnotation { if (list.size() == 0) { throw new InvalidArgumentException("List of improper annotations cannot be null"); } + if (object instanceof Alias) { + if (((Alias) object).getElement() == null) { + throw new InvalidArgumentException("Alias doesn't contain element"); + } + } this.object = object; wrongAnnotations.addAll(list); } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MissingAnnotation.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MissingAnnotation.java index 1b1979a677..1bfa269ebf 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MissingAnnotation.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MissingAnnotation.java @@ -1,41 +1,48 @@ -package lcsb.mapviewer.annotation.services; - -import lcsb.mapviewer.model.map.AnnotatedObject; -import lcsb.mapviewer.modelutils.map.ElementUtils; - -/** - * Defines annotation problem with element when there are no annotations for the - * element. - * - * @author Piotr Gawron - * - */ -public class MissingAnnotation implements ProblematicAnnotation { - - /** - * Object improperly annotated. - */ - private AnnotatedObject object; - - /** - * Constructor that initializes the data with {@link #object annotated object} - * . - * - * @param object - * annotated object that miss annotation - */ - public MissingAnnotation(AnnotatedObject object) { - this.object = object; - } - - @Override - public String getMessage() { - return new ElementUtils().getElementTag(object) + "misses annotations."; - } - - @Override - public String toString() { - return getMessage(); - } - -} +package lcsb.mapviewer.annotation.services; + +import lcsb.mapviewer.common.exception.InvalidArgumentException; +import lcsb.mapviewer.model.map.AnnotatedObject; +import lcsb.mapviewer.model.map.layout.alias.Alias; +import lcsb.mapviewer.modelutils.map.ElementUtils; + +/** + * Defines annotation problem with element when there are no annotations for the + * element. + * + * @author Piotr Gawron + * + */ +public class MissingAnnotation implements ProblematicAnnotation { + + /** + * Object improperly annotated. + */ + private AnnotatedObject object; + + /** + * Constructor that initializes the data with {@link #object annotated object} + * . + * + * @param object + * annotated object that miss annotation + */ + public MissingAnnotation(AnnotatedObject object) { + if (object instanceof Alias) { + if (((Alias) object).getElement() == null) { + throw new InvalidArgumentException("Alias doesn't contain element"); + } + } + this.object = object; + } + + @Override + public String getMessage() { + return new ElementUtils().getElementTag(object) + "misses annotations."; + } + + @Override + public String toString() { + return getMessage(); + } + +} diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MissingRequiredAnnotations.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MissingRequiredAnnotations.java index c060a8be5b..f0621c7b96 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MissingRequiredAnnotations.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MissingRequiredAnnotations.java @@ -1,64 +1,70 @@ -package lcsb.mapviewer.annotation.services; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.AnnotatedObject; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.modelutils.map.ElementUtils; - -/** - * Defines problem with element annotation when there are some required - * annotations,but none of them can be found in the element. - * - * @author Piotr Gawron - * - */ -public class MissingRequiredAnnotations implements ProblematicAnnotation { - - /** - * Object improperly annotated. - */ - private AnnotatedObject object; - - /** - * Required miriam type. - */ - private List<MiriamType> requiredMiriamType = new ArrayList<>(); - - /** - * Constructor that initializes the data with {@link #object annotated object} - * and list of improper {@link MiriamData}. - * - * @param list - * list of missing but required {@link MiriamType} - * @param object - * annotated object - */ - public MissingRequiredAnnotations(AnnotatedObject object, Collection<MiriamType> list) { - if (list.size() == 0) { - throw new InvalidArgumentException("List of improper annotations cannot be null"); - } - this.object = object; - requiredMiriamType.addAll(list); - } - - @Override - public String getMessage() { - StringBuilder result = new StringBuilder(new ElementUtils().getElementTag(object)); - result.append("misses one of the following annotations: "); - for (MiriamType type : requiredMiriamType) { - result.append(type.getCommonName()); - } - return result.toString(); - } - - @Override - public String toString() { - return getMessage(); - } - -} +package lcsb.mapviewer.annotation.services; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import lcsb.mapviewer.common.exception.InvalidArgumentException; +import lcsb.mapviewer.model.map.AnnotatedObject; +import lcsb.mapviewer.model.map.MiriamData; +import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.Alias; +import lcsb.mapviewer.modelutils.map.ElementUtils; + +/** + * Defines problem with element annotation when there are some required + * annotations,but none of them can be found in the element. + * + * @author Piotr Gawron + * + */ +public class MissingRequiredAnnotations implements ProblematicAnnotation { + + /** + * Object improperly annotated. + */ + private AnnotatedObject object; + + /** + * Required miriam type. + */ + private List<MiriamType> requiredMiriamType = new ArrayList<>(); + + /** + * Constructor that initializes the data with {@link #object annotated object} + * and list of improper {@link MiriamData}. + * + * @param list + * list of missing but required {@link MiriamType} + * @param object + * annotated object + */ + public MissingRequiredAnnotations(AnnotatedObject object, Collection<MiriamType> list) { + if (list.size() == 0) { + throw new InvalidArgumentException("List of improper annotations cannot be null"); + } + if (object instanceof Alias) { + if (((Alias) object).getElement() == null) { + throw new InvalidArgumentException("Alias doesn't contain element"); + } + } + this.object = object; + requiredMiriamType.addAll(list); + } + + @Override + public String getMessage() { + StringBuilder result = new StringBuilder(new ElementUtils().getElementTag(object)); + result.append("misses one of the following annotations: "); + for (MiriamType type : requiredMiriamType) { + result.append(type.getCommonName()); + } + return result.toString(); + } + + @Override + public String toString() { + return getMessage(); + } + +} diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ModelAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ModelAnnotator.java index 3bf3311fcc..0a446b4576 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ModelAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ModelAnnotator.java @@ -32,6 +32,7 @@ import lcsb.mapviewer.model.map.AnnotatedObject; import lcsb.mapviewer.model.map.Element; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.Alias; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Species; @@ -279,7 +280,7 @@ public class ModelAnnotator { double amount = model.getElements().size() + model.getReactions().size(); // annotate all elements - for (Element element : model.getElements()) { + for (Alias element : model.getAliases()) { List<ElementAnnotator> list = null; if (annotators != null) { list = annotators.get(element.getClass()); @@ -364,7 +365,7 @@ public class ModelAnnotator { double ratio = modelCounter / modelSize; double size = model.getElements().size() + model.getReactions().size(); double counter = 0; - for (Element element : model.getElements()) { + for (Alias element : model.getAliases()) { result.addAll(findImproperAnnotations(element, validAnnotations.get(element.getClass()))); counter++; updater.setProgress(ratio * IProgressUpdater.MAX_PROGRESS + (counter / size * IProgressUpdater.MAX_PROGRESS) / modelSize); @@ -428,8 +429,8 @@ public class ModelAnnotator { models.add(m); models.addAll(m.getSubmodels()); for (Model model : models) { - for (Element element : model.getElements()) { - result.addAll(findMissing(element, requestedAnnotations.get(element.getClass()))); + for (Alias alias : model.getAliases()) { + result.addAll(findMissing(alias, requestedAnnotations.get(alias.getClass()))); } for (Reaction reaction : model.getReactions()) { result.addAll(findMissing(reaction, requestedAnnotations.get(reaction.getClass()))); diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/TaxonomyBackend.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/TaxonomyBackend.java index 1f8975be1d..a0f44718f2 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/TaxonomyBackend.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/TaxonomyBackend.java @@ -106,7 +106,7 @@ public class TaxonomyBackend extends CachableInterface implements IExternalServi queryTerm = "Rattus norvegicus"; } queryTerm = URLEncoder.encode(queryTerm, "UTF-8"); - String url = "http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?lvl=0&name=" + queryTerm; + String url = "https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?lvl=0&name=" + queryTerm; String page = getWebPageContent(url); Pattern idPattern = Pattern.compile("<em>Taxonomy ID: </em>([0-9]+)"); Matcher matcher = idPattern.matcher(page); 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 bc37df5ec1..4d1935e25b 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 @@ -24,6 +24,7 @@ import lcsb.mapviewer.model.map.AnnotatedObject; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamRelationType; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.Alias; import lcsb.mapviewer.model.map.species.Chemical; import lcsb.mapviewer.modelutils.map.ElementUtils; import uk.ac.ebi.chebi.webapps.chebiWS.client.ChebiWebServiceClient; @@ -457,7 +458,7 @@ public class ChebiAnnotator extends ElementAnnotator implements IExternalService chebi = getChebiElementForChebiId(md); } } - Chemical species = (Chemical) element; + Chemical species = (Chemical) ((Alias) element).getElement(); if (chebi != null) { super.setFullName(species, chebi.getName(), warnPrefix); diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotator.java index 364102eafe..2178786f6f 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotator.java @@ -10,6 +10,7 @@ import lcsb.mapviewer.model.map.AnnotatedObject; import lcsb.mapviewer.model.map.Element; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.Alias; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Chemical; import lcsb.mapviewer.model.map.species.Species; @@ -27,18 +28,18 @@ public abstract class ElementAnnotator extends CachableInterface { /** * Default class logger. */ - private final Logger logger = Logger.getLogger(ElementAnnotator.class); + private final Logger logger = Logger.getLogger(ElementAnnotator.class); /** * List of classes that can be annotated by this {@link IElementAnnotator * annotator}. */ - private final List<Class<? extends AnnotatedObject>> validClasses = new ArrayList<Class<? extends AnnotatedObject>>(); + private final List<Class<?>> validClasses = new ArrayList<>(); /** * Should be this annotator used as a default annotatior. */ - private boolean isDefault = false; + private boolean isDefault = false; /** * Default constructor. @@ -54,9 +55,7 @@ public abstract class ElementAnnotator extends CachableInterface { public ElementAnnotator(Class<? extends CachableInterface> clazz, Class<?>[] validClasses, boolean isDefault) { super(clazz); for (Class<?> validClass : validClasses) { - if (AnnotatedObject.class.isAssignableFrom(validClass)) { - addValidClass((Class<? extends AnnotatedObject>) validClass); - } + addValidClass(validClass); } this.isDefault = isDefault; } @@ -77,7 +76,7 @@ public abstract class ElementAnnotator extends CachableInterface { * * @return a list of all classes that can be annotated using this annotator */ - public List<Class<? extends AnnotatedObject>> getValidClasses() { + public List<Class<?>> getValidClasses() { return validClasses; } @@ -91,8 +90,12 @@ public abstract class ElementAnnotator extends CachableInterface { * <code>false</code> otherwise */ public boolean isAnnotatable(AnnotatedObject object) { - for (Class<? extends AnnotatedObject> clazz : getValidClasses()) { - if (clazz.isAssignableFrom(object.getClass())) { + Class<?> clazz = object.getClass(); + if (object instanceof Alias) { + clazz = ((Alias) object).getElement().getClass(); + } + for (Class<?> validClazz : getValidClasses()) { + if (validClazz.isAssignableFrom(clazz)) { return true; } } @@ -105,7 +108,7 @@ public abstract class ElementAnnotator extends CachableInterface { * @param clazz * class to add */ - private void addValidClass(Class<? extends AnnotatedObject> clazz) { + private void addValidClass(Class<?> clazz) { validClasses.add(clazz); } @@ -254,7 +257,6 @@ public abstract class ElementAnnotator extends CachableInterface { } - /** * Sets {@link Chemical#smiles}. * diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotator.java index 1f1b9f7dcb..8931870e6e 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotator.java @@ -21,9 +21,10 @@ import lcsb.mapviewer.annotation.services.WrongResponseCodeIOException; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.model.map.AnnotatedObject; -import lcsb.mapviewer.model.map.Element; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.Alias; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.species.Gene; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Protein; @@ -114,7 +115,9 @@ public class EnsemblAnnotator extends ElementAnnotator implements IExternalServi GenericProtein species = new GenericProtein(); species.addMiriamData(new MiriamData(MiriamType.ENSEMBL, "ENSG00000157764")); - annotateElement(species); + + SpeciesAlias proteinAlias = new SpeciesAlias(species); + annotateElement(proteinAlias); if (species.getFullName() == null || species.getFullName().isEmpty()) { status.setStatus(ExternalServiceStatusType.CHANGED); @@ -180,7 +183,7 @@ public class EnsemblAnnotator extends ElementAnnotator implements IExternalServi /** * Annotates element using identifier given in the parameter. * - * @param element + * @param annotatedObject * element that we want to annotate * @param entrezMiriamData * identifier that should be used for annotation @@ -189,7 +192,7 @@ public class EnsemblAnnotator extends ElementAnnotator implements IExternalServi * @throws AnnotatorException * thrown when there is a problem with annotating element */ - private void annotateElement(AnnotatedObject element, MiriamData entrezMiriamData, String prefix) throws AnnotatorException { + private void annotateElement(AnnotatedObject annotatedObject, MiriamData entrezMiriamData, String prefix) throws AnnotatorException { String query = REST_SERVICE_URL + entrezMiriamData.getResource() + URL_SUFFIX; try { String content = getWebPageContent(query); @@ -211,15 +214,15 @@ public class EnsemblAnnotator extends ElementAnnotator implements IExternalServi if ("EntrezGene".equals(dbname)) { String entrezId = super.getNodeAttr("primary_id", node); if (entrezId != null && !entrezId.isEmpty()) { - element.addMiriamData(new MiriamData(MiriamType.ENTREZ, entrezId)); + annotatedObject.addMiriamData(new MiriamData(MiriamType.ENTREZ, entrezId)); } String symbol = super.getNodeAttr("display_id", node); if (symbol != null) { - setSymbol(element, symbol, prefix); + setSymbol(annotatedObject, symbol, prefix); } String fullName = super.getNodeAttr("description", node); if (symbol != null) { - setFullName((Element) element, fullName, prefix); + setFullName(((Alias) annotatedObject).getElement(), fullName, prefix); } NodeList synonymNodeList = node.getChildNodes(); @@ -233,11 +236,11 @@ public class EnsemblAnnotator extends ElementAnnotator implements IExternalServi String hgncId = super.getNodeAttr("primary_id", node); if (hgncId != null && !hgncId.isEmpty()) { hgncId = hgncId.replaceAll("HGNC:", ""); - element.addMiriamData(new MiriamData(MiriamType.HGNC, hgncId)); + annotatedObject.addMiriamData(new MiriamData(MiriamType.HGNC, hgncId)); } String hgncSymbol = super.getNodeAttr("display_id", node); if (hgncSymbol != null && !hgncSymbol.isEmpty()) { - element.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, hgncSymbol)); + annotatedObject.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, hgncSymbol)); } NodeList synonymNodeList = node.getChildNodes(); @@ -255,7 +258,7 @@ public class EnsemblAnnotator extends ElementAnnotator implements IExternalServi List<String> sortedSynonyms = new ArrayList<String>(); sortedSynonyms.addAll(synonyms); Collections.sort(sortedSynonyms); - element.setSynonyms(sortedSynonyms); + annotatedObject.setSynonyms(sortedSynonyms); } } catch (WrongResponseCodeIOException e) { throw new AnnotatorException(e); @@ -281,7 +284,8 @@ public class EnsemblAnnotator extends ElementAnnotator implements IExternalServi throw new InvalidArgumentException("Only " + MiriamType.ENSEMBL + " identifier is accepted as an input"); } Protein protein = new GenericProtein(); - annotateElement(protein, miriamData, ""); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + annotateElement(proteinAlias, miriamData, ""); for (MiriamData md : protein.getMiriamData()) { if (MiriamType.ENTREZ.equals(md.getDataType())) { return md; diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotator.java index 4daf59eeaf..3d71502480 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotator.java @@ -24,10 +24,11 @@ import lcsb.mapviewer.annotation.services.WrongResponseCodeIOException; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.model.map.AnnotatedObject; -import lcsb.mapviewer.model.map.Element; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamRelationType; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.Alias; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.species.Gene; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Protein; @@ -54,7 +55,7 @@ public class EntrezAnnotator extends ElementAnnotator implements IExternalServic /** * Address of Entrez API that should be used for retrieving data. */ - private static final String REST_API_URL = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=gene&rettype=xml&id="; + private static final String REST_API_URL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=gene&rettype=xml&id="; /** * Prefix used in cache key to indicate that cached value contains @@ -130,11 +131,12 @@ public class EntrezAnnotator extends ElementAnnotator implements IExternalServic this.setCache(null); try { - GenericProtein species = new GenericProtein(); - species.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.ENTREZ, "9999")); - annotateElement(species); + GenericProtein protein = new GenericProtein(); + protein.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.ENTREZ, "9999")); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + annotateElement(proteinAlias); - if (species.getFullName() == null || species.getFullName().equals("")) { + if (protein.getFullName() == null || protein.getFullName().equals("")) { status.setStatus(ExternalServiceStatusType.CHANGED); } else { status.setStatus(ExternalServiceStatusType.OK); @@ -186,7 +188,7 @@ public class EntrezAnnotator extends ElementAnnotator implements IExternalServic if (data != null) { setSymbol(element, data.getSymbol(), prefix); - setFullName((Element) element, data.getFullName(), prefix); + setFullName(((Alias) element).getElement(), data.getFullName(), prefix); element.addMiriamData(data.getMiriamData()); element.setSynonyms(data.getSynonyms()); @@ -344,7 +346,8 @@ public class EntrezAnnotator extends ElementAnnotator implements IExternalServic String value = getCacheValue(key); if (value == null) { Protein protein = new GenericProtein(); - annotateElement(protein, miriamData, ""); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + annotateElement(proteinAlias, miriamData, ""); for (MiriamData md : protein.getMiriamData()) { if (MiriamType.HGNC.equals(md.getDataType())) { setCacheValue(key, md.getResource()); @@ -379,7 +382,8 @@ public class EntrezAnnotator extends ElementAnnotator implements IExternalServic } /** - * @param entrezSerializer the entrezSerializer to set + * @param entrezSerializer + * the entrezSerializer to set * @see #entrezSerializer */ protected void setEntrezSerializer(XmlSerializer<EntrezData> entrezSerializer) { diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotator.java index 70edac42c4..b41f36a86d 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotator.java @@ -27,6 +27,8 @@ import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamRelationType; import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.agregator.Compartment; +import lcsb.mapviewer.model.map.layout.alias.Alias; +import lcsb.mapviewer.model.map.layout.alias.CompartmentAlias; import lcsb.mapviewer.model.map.species.ComplexSpecies; import lcsb.mapviewer.model.map.species.Phenotype; import lcsb.mapviewer.modelutils.map.ElementUtils; @@ -112,11 +114,11 @@ public class GoAnnotator extends ElementAnnotator implements IExternalService { String commonName = go.getCommonName(); - Element element = (Element) object; + Element element = ((Alias) object).getElement(); - setFullName(element, commonName, new ElementUtils().getElementTag(element, this)); + setFullName(element, commonName, new ElementUtils().getElementTag(object, this)); String description = go.getDescription(); - setDescription(element, description); + setDescription(object, description); } catch (GoSearchException e) { throw new AnnotatorException(e); } @@ -175,13 +177,14 @@ public class GoAnnotator extends ElementAnnotator implements IExternalService { this.setCache(null); try { - Compartment species = new Compartment(); - species.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.GO, "GO:0046902")); - annotateElement(species); + Compartment compartment = new Compartment(); + compartment.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.GO, "GO:0046902")); + CompartmentAlias compartmentAlias = new CompartmentAlias(compartment); + annotateElement(compartmentAlias); - if (species.getFullName() == null || species.getFullName().equals("")) { + if (compartment.getFullName() == null || compartment.getFullName().equals("")) { status.setStatus(ExternalServiceStatusType.CHANGED); - } else if (species.getNotes() == null || species.getNotes().equals("")) { + } else if (compartment.getNotes() == null || compartment.getNotes().equals("")) { status.setStatus(ExternalServiceStatusType.CHANGED); } else { status.setStatus(ExternalServiceStatusType.OK); diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotator.java index 00b2decd45..fc211be6a7 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotator.java @@ -20,6 +20,8 @@ import lcsb.mapviewer.model.map.Element; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamRelationType; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.Alias; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.species.Gene; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Protein; @@ -90,11 +92,12 @@ public class HgncAnnotator extends ElementAnnotator implements IExternalService this.setCache(null); try { - GenericProtein species = new GenericProtein(); - species.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.HGNC_SYMBOL, "SNCA")); - annotateElement(species); + GenericProtein protein = new GenericProtein(); + protein.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.HGNC_SYMBOL, "SNCA")); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + annotateElement(proteinAlias); - if (species.getFullName() == null || species.getFullName().equals("")) { + if (protein.getFullName() == null || protein.getFullName().equals("")) { status.setStatus(ExternalServiceStatusType.CHANGED); } else { status.setStatus(ExternalServiceStatusType.OK); @@ -184,7 +187,7 @@ public class HgncAnnotator extends ElementAnnotator implements IExternalService } setSymbol(element, getNodeValue(node), prefix); } else if (type.equals("name")) { - setFullName((Element) element, getNodeValue(node), prefix); + setFullName(((Alias) element).getElement(), getNodeValue(node), prefix); } } else if (node.getNodeName().equals("arr")) { String type = getNodeAttr("name", node); @@ -205,7 +208,7 @@ public class HgncAnnotator extends ElementAnnotator implements IExternalService strings.add(getNodeValue(subnode)); } } - ((Element) element).setFormerSymbols(strings); + ((Alias) element).getElement().setFormerSymbols(strings); } else if (type.equals("alias_symbol")) { List<String> strings = new ArrayList<String>(); NodeList sublist = node.getChildNodes(); diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotator.java index 0ee43f4597..f3e76fe098 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotator.java @@ -19,6 +19,8 @@ import lcsb.mapviewer.common.EventStorageLoggerAppender; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.AnnotatedObject; import lcsb.mapviewer.model.map.Element; +import lcsb.mapviewer.model.map.layout.alias.Alias; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Chemical; import lcsb.mapviewer.model.map.species.SimpleMolecule; @@ -92,7 +94,8 @@ public class ReconAnnotator extends ElementAnnotator implements IExternalService try { SimpleMolecule sm = new SimpleMolecule(); sm.setName("h2o"); - annotateElement(sm); + SpeciesAlias smallMoleculeAlias = new SpeciesAlias(sm); + annotateElement(smallMoleculeAlias); status.setStatus(ExternalServiceStatusType.OK); if (sm.getMiriamData().size() == 0) { status.setStatus(ExternalServiceStatusType.CHANGED); @@ -109,11 +112,11 @@ public class ReconAnnotator extends ElementAnnotator implements IExternalService } @Override - public void annotateElement(AnnotatedObject element) throws AnnotatorException { - if (isAnnotatable(element)) { - String id = element.getAbbreviation(); + public void annotateElement(AnnotatedObject annotatedObject) throws AnnotatorException { + if (isAnnotatable(annotatedObject)) { + String id = annotatedObject.getAbbreviation(); if (id == null || id.isEmpty()) { - id = element.getName(); + id = annotatedObject.getName(); } if (id.indexOf("[") > 0) { id = id.substring(0, id.indexOf("[")); @@ -123,18 +126,22 @@ public class ReconAnnotator extends ElementAnnotator implements IExternalService id = tmp[tmp.length - 1]; } String url = null; - if (element instanceof Element) { + Element element = null; + if (annotatedObject instanceof Alias) { + element = ((Alias) annotatedObject).getElement(); + } + if (annotatedObject instanceof Alias) { url = ELEMENT_ANNOTATION_URL_PREFIX + id; - } else if (element instanceof Reaction) { + } else if (annotatedObject instanceof Reaction) { url = REACTION_ANNOTATION_URL_PREFIX + id; } else { - logger.warn(elementUtils.getElementTag(element) + " Unknown class type: " + element.getClass()); + logger.warn(elementUtils.getElementTag(annotatedObject) + " Unknown class type: " + annotatedObject.getClass()); return; } try { String content = getWebPageContent(url); - String prefix = elementUtils.getElementTag(element, this); + String prefix = elementUtils.getElementTag(annotatedObject, this); if (!content.isEmpty()) { JsonElement jelement = new JsonParser().parse(content); @@ -159,23 +166,23 @@ public class ReconAnnotator extends ElementAnnotator implements IExternalService } else if (key.equals("rxn_id")) { continue; } else if (key.equals("abbreviation")) { - setAbbreviation(element, value, prefix); + setAbbreviation(annotatedObject, value, prefix); } else if (key.equals("description")) { - setDescription(element, value); + setDescription(annotatedObject, value); } else if (key.equals("formula")) { - setFormula(element, value, prefix); + setFormula(annotatedObject, value, prefix); } else if (key.equals("reversible")) { continue; } else if (key.equals("mcs")) { - if (element instanceof Reaction) { - setMcs((Reaction) element, value, prefix); + if (annotatedObject instanceof Reaction) { + setMcs((Reaction) annotatedObject, value, prefix); } else { unknown = true; } } else if (key.equals("notes")) { - setDescription(element, value); + setDescription(annotatedObject, value); } else if (key.equals("ecnumber")) { - addEcMiriam(element, value); + addEcMiriam(annotatedObject, value); } else if (key.equals("ref")) { continue; } else if (key.equals("lastModified")) { @@ -191,7 +198,7 @@ public class ReconAnnotator extends ElementAnnotator implements IExternalService } else if (key.equals("csecoida")) { continue; } else if (key.equals("chargedFormula")) { - setFormula(element, value, prefix); + setFormula(annotatedObject, value, prefix); } else if (key.equals("charge")) { if (element instanceof Species) { setCharge((Species) element, value, prefix); @@ -211,15 +218,15 @@ public class ReconAnnotator extends ElementAnnotator implements IExternalService unknown = true; } } else if (key.equals("cheBlId")) { - addChebiMiriam(element, value); + addChebiMiriam(annotatedObject, value); } else if (key.equals("subsystem")) { - setSubsystem((Reaction) element, value, prefix); + setSubsystem((Reaction) annotatedObject, value, prefix); } else if (key.equals("keggId")) { - addKeggMiriam(element, value, prefix); + addKeggMiriam(annotatedObject, value, prefix); } else if (key.equals("pubChemId")) { - addPubchemMiriam(element, value); + addPubchemMiriam(annotatedObject, value); } else if (key.equals("hmdb")) { - addHmdbMiriam(element, value); + addHmdbMiriam(annotatedObject, value); } else if (key.equals("pdmapName")) { // for now we skip it... continue; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/AnnotationTestFunctions.java b/annotation/src/test/java/lcsb/mapviewer/annotation/AnnotationTestFunctions.java index 2064bb9443..a155631f38 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/AnnotationTestFunctions.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/AnnotationTestFunctions.java @@ -119,7 +119,7 @@ public abstract class AnnotationTestFunctions extends AbstractTransactionalJUnit return stringBuilder.toString(); } - protected Node getNodeFromXmlString(String text) throws InvalidXmlSchemaException { + protected Node getNodeFromXmlString(String text) throws InvalidXmlSchemaException, IOException { InputSource is = new InputSource(); is.setCharacterStream(new StringReader(text)); return getXmlDocumentFromInputSource(is).getChildNodes().item(0); @@ -143,7 +143,7 @@ public abstract class AnnotationTestFunctions extends AbstractTransactionalJUnit return null; } - protected Document getXmlDocumentFromInputSource(InputSource stream) throws InvalidXmlSchemaException { + protected Document getXmlDocumentFromInputSource(InputSource stream) throws InvalidXmlSchemaException, IOException { DocumentBuilder db; try { db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); @@ -154,9 +154,7 @@ public abstract class AnnotationTestFunctions extends AbstractTransactionalJUnit try { doc = db.parse(stream); } catch (SAXException e) { - logger.error(e); - } catch (IOException e) { - logger.error(e); + throw new InvalidXmlSchemaException(e); } return doc; } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParserTest.java index f779e52b22..1c98615a79 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParserTest.java @@ -1,654 +1,668 @@ -package lcsb.mapviewer.annotation.services; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; -import org.junit.Test; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; - -import lcsb.mapviewer.annotation.AnnotationTestFunctions; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.data.Drug; -import lcsb.mapviewer.annotation.data.Target; -import lcsb.mapviewer.annotation.services.annotators.UniprotAnnotator; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; - -public class DrugbankHTMLParserTest extends AnnotationTestFunctions { - Logger logger = Logger.getLogger(DrugbankHTMLParserTest.class); - - @Autowired - private DrugbankHTMLParser drugBankHTMLParser; - - @Autowired - private GeneralCacheInterface cache; - - @Test - public void test1FindDrug() throws Exception { - try { - Drug test = drugBankHTMLParser.findDrug("Urokinase"); - assertEquals(MiriamType.DRUGBANK, test.getSources().get(0).getDataType()); - assertEquals("DB00013", test.getSources().get(0).getResource()); - assertEquals("Urokinase", test.getName()); - assertTrue(test.getBloodBrainBarrier().equalsIgnoreCase("N/A")); - boolean res = test.getDescription().contains( - "Low molecular weight form of human urokinase, that consists of an A chain of 2,000 daltons linked by a sulfhydryl bond to a B chain of 30,400 daltons. Recombinant urokinase plasminogen activator"); - assertTrue(res); - assertEquals(10, test.getTargets().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void test2FindDrug() throws Exception { - try { - - Drug test = drugBankHTMLParser.findDrug("diazoxide"); - assertEquals("Diazoxide", test.getName()); - assertEquals("DB01119", test.getSources().get(0).getResource()); - assertTrue(test.getBloodBrainBarrier().equalsIgnoreCase("YES")); - boolean res = test.getDescription().contains( - "A benzothiadiazine derivative that is a peripheral vasodilator used for hypertensive emergencies. It lacks diuretic effect, apparently because it lacks a sulfonamide group. [PubChem]"); - assertTrue(res); - assertEquals(6, test.getTargets().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void test3FindDrug() throws Exception { - - try { - // finding synonym - Drug test = drugBankHTMLParser.findDrug("Rapamycin"); - assertEquals("Sirolimus", test.getName()); - assertEquals("DB00877", test.getSources().get(0).getResource()); - assertTrue(test.getBloodBrainBarrier().equalsIgnoreCase("NO")); - boolean res = test.getDescription().contains( - "A macrolide compound obtained from Streptomyces hygroscopicus that acts by selectively blocking the transcriptional activation of cytokines thereby inhibiting cytokine production. It is bioactive only when bound to immunophilins. Sirolimus is a potent immunosuppressant and possesses both antifungal and antineoplastic properties. [PubChem]"); - assertTrue(res); - assertEquals(3, test.getTargets().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void test4FindDrug() throws Exception { - - try { - Drug test = drugBankHTMLParser.findDrug("Methylamine"); - assertEquals("Methylamine", test.getName()); - assertEquals("DB01828", test.getSources().get(0).getResource()); - assertEquals(null, test.getDescription()); - assertEquals(1, test.getTargets().size()); - - List<Target> tmp; - tmp = test.getTargets(); - for (Target a : tmp) { - assertEquals("Ammonia channel", a.getName()); - assertEquals(2, a.getReferences().size()); - assertEquals(1, a.getGenes().size()); - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void test5FindDrug() throws Exception { - - try { - Drug test = drugBankHTMLParser.findDrug("Amantadine"); - assertEquals("Amantadine", test.getName()); - assertEquals("DB00915", test.getSources().get(0).getResource()); - boolean res = test.getDescription().contains( - "An antiviral that is used in the prophylactic or symptomatic treatment of influenza A. It is also used as an antiparkinsonian agent, to treat extrapyramidal reactions, and for postherpetic neuralgia. The mechanisms of its effects in movement disorders are not well understood but probably reflect an increase in synthesis and release of dopamine, with perhaps some inhibition of dopamine uptake. [PubChem]"); - assertTrue(res); - assertEquals(3, test.getTargets().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void test6FindDrug() throws Exception { - - try { - Drug test = drugBankHTMLParser.findDrug("qwertyuiop"); - assertEquals(null, test); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void test7FindDrug() throws Exception { - try { - - Drug test = drugBankHTMLParser.findDrug("Aluminum hydroxide"); - assertEquals("Aluminum hydroxide", test.getName()); - assertEquals("DB06723", test.getSources().get(0).getResource()); - assertTrue( - test.getDescription().contains( - "Aluminum hydroxide is an inorganic salt used as an antacid. It is a basic compound that acts by neutralizing hydrochloric acid in gastric secretions. Subsequent increases in pH may inhibit the action of pepsin. An increase in bicarbonate ions and prostaglandins may also confer cytoprotective effects.")); - assertEquals(0, test.getTargets().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - // at some point this search threw exception - @Test - public void testFindDrugKainicAcid() throws Exception { - try { - Drug test = drugBankHTMLParser.findDrug("kainic acid"); - assertNotNull(test); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testFindDrugAmantadineWithBrandNames() throws Exception { - try { - Drug test = drugBankHTMLParser.findDrug("amantadine"); - - assertNotNull(test); - assertTrue(test.getBrandNames().contains("PK-Merz")); - assertTrue(test.getBrandNames().contains("Symadine")); - assertTrue(test.getBrandNames().contains("Symmetrel")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testFindDrugSelegiline() throws Exception { - try { - Drug test = drugBankHTMLParser.findDrug("Selegiline"); - assertNotNull(test); - assertEquals(2, test.getTargets().size()); - for (String string : new String[] { "MAOA", "MAOB" }) { - boolean contain = false; - for (Target target : test.getTargets()) { - for (MiriamData md : target.getGenes()) { - if (md.getResource().equals(string)) { - contain = true; - } - } - } - assertTrue("Missing traget: " + string, contain); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testFindDrugDaidzinWithHtmlCharacters() throws Exception { - try { - Drug test = drugBankHTMLParser.findDrug("Daidzin"); - assertNotNull(test); - for (String str : test.getSynonyms()) { - assertFalse(str.contains("'")); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testFindDrugGliclazideWithHtmlTags() throws Exception { - try { - Drug test = drugBankHTMLParser.findDrug("Gliclazide"); - assertNotNull(test); - assertFalse(test.getDescription().contains("<span")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testFindDrugSevofluraneWithHtmlTags() throws Exception { - try { - Drug test = drugBankHTMLParser.findDrug("sevoflurane"); - assertNotNull(test); - for (String str : test.getSynonyms()) { - assertFalse(str.contains("<div")); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testFindDrugByHgncTarget() throws Exception { - try { - List<Drug> drugs = drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "NFKB2")); - assertNotNull(drugs); - assertTrue("Only " + drugs.size() + " drugs were found, but at least 8 were expected", drugs.size() >= 8); - - drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "NFKB2")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testFindDrugByInvalidTarget() throws Exception { - try { - drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.WIKIPEDIA, "h2o")); - fail("Exception"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("type is accepted")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testFindDrugByEmptyTarget() throws Exception { - try { - List<Drug> drugs = drugBankHTMLParser.getDrugListByTarget(null); - assertEquals(0, drugs.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testWrongHgncTarget() throws Exception { - try { - - List<Drug> drugs = drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "BECN1")); - assertNotNull(drugs); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testFindDrugByHgncTargets() throws Exception { - try { - List<Drug> drug1 = drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "NFKB1")); - List<Drug> drug2 = drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "NFKB2")); - int size = drug1.size() + drug2.size(); - - List<MiriamData> list = new ArrayList<MiriamData>(); - list.add(new MiriamData(MiriamType.HGNC_SYMBOL, "NFKB2")); - list.add(new MiriamData(MiriamType.HGNC_SYMBOL, "NFKB1")); - - List<Drug> drugs = drugBankHTMLParser.getDrugListByTargets(list); - assertNotNull(drugs); - assertTrue("Merged list should be shorter then sum of the two lists", drugs.size() < size); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test(timeout = 15000) - public void testCachableInterfaceInvalidateUrl() throws Exception { - String query = "http://google.lu/"; - String newRes = "hello"; - try { - waitForRefreshCacheQueueToEmpty(); - - cache.setCachedQuery(query, drugBankHTMLParser.getCacheType(), newRes); - cache.invalidateByQuery(query, drugBankHTMLParser.getCacheType()); - - waitForRefreshCacheQueueToEmpty(); - - String res = cache.getStringByQuery(query, drugBankHTMLParser.getCacheType()); - - assertNotNull(res); - - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - // wait max 15 second - @Test(timeout = 150000) - public void testCachableInterfaceInvalidateDrug() throws Exception { - - String query = "drug:amantadine"; - String newRes = "hello"; - try { - waitForRefreshCacheQueueToEmpty(); - - cache.setCachedQuery(query, drugBankHTMLParser.getCacheType(), newRes); - cache.invalidateByQuery(query, drugBankHTMLParser.getCacheType()); - - waitForRefreshCacheQueueToEmpty(); - - String res = cache.getStringByQuery(query, drugBankHTMLParser.getCacheType()); - - assertNotNull(res); - - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testByTargetsForCCNB1() throws Exception { - try { - List<MiriamData> targets = new ArrayList<>(); - MiriamData miriamTarget = new MiriamData(MiriamType.HGNC_SYMBOL, "CCNB1"); - targets.add(miriamTarget); - List<Drug> drugs = drugBankHTMLParser.getDrugListByTargets(targets); - for (Drug drug : drugs) { - boolean found = false; - for (Target target : drug.getTargets()) { - for (MiriamData md : target.getGenes()) { - if (miriamTarget.equals(md)) { - found = true; - } - } - } - assertTrue("Drug " + drug.getName() + " doesn't contain expected target", found); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testFindIbuprofen() throws Exception { - - try { - Drug test = drugBankHTMLParser.findDrug("Ibuprofen"); - assertEquals("Ibuprofen", test.getName()); - assertEquals("DB01050", test.getSources().get(0).getResource()); - assertNotNull(test.getDescription()); - assertEquals(8, test.getTargets().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testFindDopamine() throws Exception { - - try { - Drug test = drugBankHTMLParser.findDrug("Dopamine"); - for (Target target : test.getTargets()) { - assertFalse(target.getName().contains("Details")); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testFindGadobutrol() throws Exception { - - try { - Drug test = drugBankHTMLParser.findDrug("Gadobutrol"); - assertTrue(test.getBloodBrainBarrier().equalsIgnoreCase("NO")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testFindDrugWithSpecialCharacters() throws Exception { - - try { - Drug test = drugBankHTMLParser.findDrug("Guanosine-5’-Diphosphate"); - assertFalse(test.getName().contains("&")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefreshInvalidCacheQuery() throws Exception { - try { - drugBankHTMLParser.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 { - drugBankHTMLParser.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 testRefreshCacheQueryNotAvailable() throws Exception { - WebPageDownloader downloader = drugBankHTMLParser.getWebPageDownloader(); - try { - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString())).thenThrow(new IOException()); - drugBankHTMLParser.setWebPageDownloader(mockDownloader); - drugBankHTMLParser.refreshCacheQuery("http://google.pl/"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - drugBankHTMLParser.setWebPageDownloader(downloader); - } - } - - @Test - public void testRefreshCacheQueryWhenDbNotAvailable() throws Exception { - WebPageDownloader downloader = drugBankHTMLParser.getWebPageDownloader(); - GeneralCacheInterface cache = drugBankHTMLParser.getCache(); - try { - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString())).thenThrow(new IOException()); - drugBankHTMLParser.setWebPageDownloader(mockDownloader); - drugBankHTMLParser.setCache(null); - - drugBankHTMLParser.refreshCacheQuery(DrugbankHTMLParser.DRUG_NAME_PREFIX + "aspirin"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - drugBankHTMLParser.setWebPageDownloader(downloader); - drugBankHTMLParser.setCache(cache); - } - } - - @Test - public void testGetPubmedFromRef() throws Exception { - try { - String descriptionString = "<a href=\"/pubmed/1234\">link to 1234</a>"; - List<MiriamData> result = drugBankHTMLParser.getPubmedFromRef(descriptionString); - assertEquals(1, result.size()); - assertEquals(new MiriamData(MiriamType.PUBMED, "1234"), result.get(0)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetPubmedFromRef2() throws Exception { - try { - String descriptionString = "<a href=\"/pubmed/12345678901234_\">link to 123456789</a>"; - List<MiriamData> result = drugBankHTMLParser.getPubmedFromRef(descriptionString); - assertEquals(1, result.size()); - assertEquals(new MiriamData(MiriamType.PUBMED, "123456789"), result.get(0)); - assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetPubmedFromRef3() throws Exception { - try { - String descriptionString = "<a href=\"/pubmed/invalid\">link to invalid</a>"; - List<MiriamData> result = drugBankHTMLParser.getPubmedFromRef(descriptionString); - assertEquals(0, result.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetDescription() throws Exception { - try { - String descriptionString = "untagged description"; - assertNull(drugBankHTMLParser.getDescriptionForDrug(descriptionString)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetTargets() throws Exception { - try { - String descriptionString = "invalid content"; - List<Target> targets = drugBankHTMLParser.getTargetsForDrug(descriptionString); - assertEquals(0, targets.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, drugBankHTMLParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSimulateDownStatus() throws Exception { - WebPageDownloader downloader = drugBankHTMLParser.getWebPageDownloader(); - try { - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString())).thenThrow(new IOException()); - drugBankHTMLParser.setWebPageDownloader(mockDownloader); - assertEquals(ExternalServiceStatusType.DOWN, drugBankHTMLParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - drugBankHTMLParser.setWebPageDownloader(downloader); - } - } - - @Test - public void testSimulateChangedStatus() throws Exception { - WebPageDownloader downloader = drugBankHTMLParser.getWebPageDownloader(); - try { - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString())).thenReturn(""); - drugBankHTMLParser.setWebPageDownloader(mockDownloader); - assertEquals(ExternalServiceStatusType.CHANGED, drugBankHTMLParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - drugBankHTMLParser.setWebPageDownloader(downloader); - } - } - - @Test - public void testGetBBB() throws Exception { - try { - assertTrue(drugBankHTMLParser.getBloodBrainBarrier("<tr><td>Blood Brain Barrier</td><td>-</td><td>0.7581</td></tr>").equalsIgnoreCase("NO")); - assertTrue(drugBankHTMLParser.getBloodBrainBarrier("<tr><td>Blood Brain Barrier</td><td>+</td><td>0.7581</td></tr>").equalsIgnoreCase("YES")); - assertTrue(drugBankHTMLParser.getBloodBrainBarrier("<tr><td>Blood Brain Barrier</td><td>don't know</td><td>0.7581</td></tr>").equalsIgnoreCase("N/A")); - assertTrue(drugBankHTMLParser.getBloodBrainBarrier("invalid str").equalsIgnoreCase("N/A")); - assertTrue(drugBankHTMLParser.getBloodBrainBarrier("<tr><td>Blood Brain Barrier</td>invalid str").equalsIgnoreCase("N/A")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() throws Exception { - DrugbankHTMLParser parser = new DrugbankHTMLParser(); - UniprotAnnotator uniprotAnnotator = new UniprotAnnotator(); - parser.setUniprotAnnotator(uniprotAnnotator); - assertEquals(uniprotAnnotator, parser.getUniprotAnnotator()); - } - -} +package lcsb.mapviewer.annotation.services; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; + +import lcsb.mapviewer.annotation.AnnotationTestFunctions; +import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; +import lcsb.mapviewer.annotation.cache.GeneralCacheWithExclusion; +import lcsb.mapviewer.annotation.cache.SourceNotAvailable; +import lcsb.mapviewer.annotation.cache.WebPageDownloader; +import lcsb.mapviewer.annotation.data.Drug; +import lcsb.mapviewer.annotation.data.Target; +import lcsb.mapviewer.annotation.services.annotators.UniprotAnnotator; +import lcsb.mapviewer.common.exception.InvalidArgumentException; +import lcsb.mapviewer.model.map.MiriamData; +import lcsb.mapviewer.model.map.MiriamType; + +public class DrugbankHTMLParserTest extends AnnotationTestFunctions { + Logger logger = Logger.getLogger(DrugbankHTMLParserTest.class); + + @Autowired + private DrugbankHTMLParser drugBankHTMLParser; + + @Autowired + private GeneralCacheInterface cache; + + @Before + public void setUp() throws Exception { + drugBankHTMLParser.setCache(new GeneralCacheWithExclusion(cache, 1)); + } + + @After + public void tearDown() throws Exception { + drugBankHTMLParser.setCache(cache); + } + + + @Test + public void test1FindDrug() throws Exception { + try { + Drug test = drugBankHTMLParser.findDrug("Urokinase"); + assertEquals(MiriamType.DRUGBANK, test.getSources().get(0).getDataType()); + assertEquals("DB00013", test.getSources().get(0).getResource()); + assertEquals("Urokinase", test.getName()); + assertTrue(test.getBloodBrainBarrier().equalsIgnoreCase("N/A")); + boolean res = test.getDescription().contains( + "Low molecular weight form of human urokinase, that consists of an A chain of 2,000 daltons linked by a sulfhydryl bond to a B chain of 30,400 daltons. Recombinant urokinase plasminogen activator"); + assertTrue(res); + assertEquals(10, test.getTargets().size()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void test2FindDrug() throws Exception { + try { + + Drug test = drugBankHTMLParser.findDrug("diazoxide"); + assertEquals("Diazoxide", test.getName()); + assertEquals("DB01119", test.getSources().get(0).getResource()); + assertTrue(test.getBloodBrainBarrier().equalsIgnoreCase("YES")); + boolean res = test.getDescription().contains( + "A benzothiadiazine derivative that is a peripheral vasodilator used for hypertensive emergencies. It lacks diuretic effect, apparently because it lacks a sulfonamide group. [PubChem]"); + assertTrue(res); + assertEquals(6, test.getTargets().size()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + } + + @Test + public void test3FindDrug() throws Exception { + + try { + // finding synonym + Drug test = drugBankHTMLParser.findDrug("Rapamycin"); + assertEquals("Sirolimus", test.getName()); + assertEquals("DB00877", test.getSources().get(0).getResource()); + assertTrue(test.getBloodBrainBarrier().equalsIgnoreCase("NO")); + boolean res = test.getDescription().contains( + "A macrolide compound obtained from Streptomyces hygroscopicus that acts by selectively blocking the transcriptional activation of cytokines thereby inhibiting cytokine production. It is bioactive only when bound to immunophilins. Sirolimus is a potent immunosuppressant and possesses both antifungal and antineoplastic properties. [PubChem]"); + assertTrue(res); + assertEquals(3, test.getTargets().size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void test4FindDrug() throws Exception { + + try { + Drug test = drugBankHTMLParser.findDrug("Methylamine"); + assertEquals("Methylamine", test.getName()); + assertEquals("DB01828", test.getSources().get(0).getResource()); + assertEquals(null, test.getDescription()); + assertEquals(1, test.getTargets().size()); + + List<Target> tmp; + tmp = test.getTargets(); + for (Target a : tmp) { + assertEquals("Ammonia channel", a.getName()); + assertEquals(2, a.getReferences().size()); + assertEquals(1, a.getGenes().size()); + } + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void test5FindDrug() throws Exception { + + try { + Drug test = drugBankHTMLParser.findDrug("Amantadine"); + assertEquals("Amantadine", test.getName()); + assertEquals("DB00915", test.getSources().get(0).getResource()); + boolean res = test.getDescription().contains( + "An antiviral that is used in the prophylactic or symptomatic treatment of influenza A. It is also used as an antiparkinsonian agent, to treat extrapyramidal reactions, and for postherpetic neuralgia. The mechanisms of its effects in movement disorders are not well understood but probably reflect an increase in synthesis and release of dopamine, with perhaps some inhibition of dopamine uptake. [PubChem]"); + assertTrue(res); + assertEquals(3, test.getTargets().size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void test6FindDrug() throws Exception { + + try { + Drug test = drugBankHTMLParser.findDrug("qwertyuiop"); + assertEquals(null, test); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void test7FindDrug() throws Exception { + try { + + Drug test = drugBankHTMLParser.findDrug("Aluminum hydroxide"); + assertEquals("Aluminum hydroxide", test.getName()); + assertEquals("DB06723", test.getSources().get(0).getResource()); + assertTrue( + test.getDescription().contains( + "Aluminum hydroxide is an inorganic salt used as an antacid. It is a basic compound that acts by neutralizing hydrochloric acid in gastric secretions. Subsequent increases in pH may inhibit the action of pepsin. An increase in bicarbonate ions and prostaglandins may also confer cytoprotective effects.")); + assertEquals(0, test.getTargets().size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + // at some point this search threw exception + @Test + public void testFindDrugKainicAcid() throws Exception { + try { + Drug test = drugBankHTMLParser.findDrug("kainic acid"); + assertNotNull(test); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testFindDrugAmantadineWithBrandNames() throws Exception { + try { + Drug test = drugBankHTMLParser.findDrug("amantadine"); + + assertNotNull(test); + assertTrue(test.getBrandNames().contains("PK-Merz")); + assertTrue(test.getBrandNames().contains("Symadine")); + assertTrue(test.getBrandNames().contains("Symmetrel")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testFindDrugSelegiline() throws Exception { + try { + Drug test = drugBankHTMLParser.findDrug("Selegiline"); + assertNotNull(test); + assertEquals(2, test.getTargets().size()); + for (String string : new String[] { "MAOA", "MAOB" }) { + boolean contain = false; + for (Target target : test.getTargets()) { + for (MiriamData md : target.getGenes()) { + if (md.getResource().equals(string)) { + contain = true; + } + } + } + assertTrue("Missing traget: " + string, contain); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testFindDrugDaidzinWithHtmlCharacters() throws Exception { + try { + Drug test = drugBankHTMLParser.findDrug("Daidzin"); + assertNotNull(test); + for (String str : test.getSynonyms()) { + assertFalse(str.contains("'")); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testFindDrugGliclazideWithHtmlTags() throws Exception { + try { + Drug test = drugBankHTMLParser.findDrug("Gliclazide"); + assertNotNull(test); + assertFalse(test.getDescription().contains("<span")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testFindDrugSevofluraneWithHtmlTags() throws Exception { + try { + Drug test = drugBankHTMLParser.findDrug("sevoflurane"); + assertNotNull(test); + for (String str : test.getSynonyms()) { + assertFalse(str.contains("<div")); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testFindDrugByHgncTarget() throws Exception { + try { + List<Drug> drugs = drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "NFKB2")); + assertNotNull(drugs); + assertTrue("Only " + drugs.size() + " drugs were found, but at least 8 were expected", drugs.size() >= 8); + + drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "NFKB2")); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testFindDrugByInvalidTarget() throws Exception { + try { + drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.WIKIPEDIA, "h2o")); + fail("Exception"); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("type is accepted")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testFindDrugByEmptyTarget() throws Exception { + try { + List<Drug> drugs = drugBankHTMLParser.getDrugListByTarget(null); + assertEquals(0, drugs.size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testWrongHgncTarget() throws Exception { + try { + + List<Drug> drugs = drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "BECN1")); + assertNotNull(drugs); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testFindDrugByHgncTargets() throws Exception { + try { + List<Drug> drug1 = drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "NFKB1")); + List<Drug> drug2 = drugBankHTMLParser.getDrugListByTarget(new MiriamData(MiriamType.HGNC_SYMBOL, "NFKB2")); + int size = drug1.size() + drug2.size(); + + List<MiriamData> list = new ArrayList<MiriamData>(); + list.add(new MiriamData(MiriamType.HGNC_SYMBOL, "NFKB2")); + list.add(new MiriamData(MiriamType.HGNC_SYMBOL, "NFKB1")); + + List<Drug> drugs = drugBankHTMLParser.getDrugListByTargets(list); + assertNotNull(drugs); + assertTrue("Merged list should be shorter then sum of the two lists", drugs.size() < size); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + } + + @Test(timeout = 15000) + public void testCachableInterfaceInvalidateUrl() throws Exception { + String query = "http://google.lu/"; + String newRes = "hello"; + try { + waitForRefreshCacheQueueToEmpty(); + + cache.setCachedQuery(query, drugBankHTMLParser.getCacheType(), newRes); + cache.invalidateByQuery(query, drugBankHTMLParser.getCacheType()); + + waitForRefreshCacheQueueToEmpty(); + + String res = cache.getStringByQuery(query, drugBankHTMLParser.getCacheType()); + + assertNotNull(res); + + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + // wait max 15 second + @Test(timeout = 150000) + public void testCachableInterfaceInvalidateDrug() throws Exception { + + String query = "drug:amantadine"; + String newRes = "hello"; + try { + waitForRefreshCacheQueueToEmpty(); + + cache.setCachedQuery(query, drugBankHTMLParser.getCacheType(), newRes); + cache.invalidateByQuery(query, drugBankHTMLParser.getCacheType()); + + waitForRefreshCacheQueueToEmpty(); + + String res = cache.getStringByQuery(query, drugBankHTMLParser.getCacheType()); + + assertNotNull(res); + + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testByTargetsForCCNB1() throws Exception { + try { + List<MiriamData> targets = new ArrayList<>(); + MiriamData miriamTarget = new MiriamData(MiriamType.HGNC_SYMBOL, "CCNB1"); + targets.add(miriamTarget); + List<Drug> drugs = drugBankHTMLParser.getDrugListByTargets(targets); + for (Drug drug : drugs) { + boolean found = false; + for (Target target : drug.getTargets()) { + for (MiriamData md : target.getGenes()) { + if (miriamTarget.equals(md)) { + found = true; + } + } + } + assertTrue("Drug " + drug.getName() + " doesn't contain expected target", found); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + } + + @Test + public void testFindIbuprofen() throws Exception { + + try { + Drug test = drugBankHTMLParser.findDrug("Ibuprofen"); + assertEquals("Ibuprofen", test.getName()); + assertEquals("DB01050", test.getSources().get(0).getResource()); + assertNotNull(test.getDescription()); + assertEquals(8, test.getTargets().size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testFindDopamine() throws Exception { + + try { + Drug test = drugBankHTMLParser.findDrug("Dopamine"); + for (Target target : test.getTargets()) { + assertFalse(target.getName().contains("Details")); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testFindGadobutrol() throws Exception { + + try { + Drug test = drugBankHTMLParser.findDrug("Gadobutrol"); + assertTrue(test.getBloodBrainBarrier().equalsIgnoreCase("NO")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testFindDrugWithSpecialCharacters() throws Exception { + + try { + Drug test = drugBankHTMLParser.findDrug("Guanosine-5’-Diphosphate"); + assertFalse(test.getName().contains("&")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefreshInvalidCacheQuery() throws Exception { + try { + drugBankHTMLParser.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 { + drugBankHTMLParser.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 testRefreshCacheQueryNotAvailable() throws Exception { + WebPageDownloader downloader = drugBankHTMLParser.getWebPageDownloader(); + try { + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString())).thenThrow(new IOException()); + drugBankHTMLParser.setWebPageDownloader(mockDownloader); + drugBankHTMLParser.refreshCacheQuery("http://google.pl/"); + fail("Exception expected"); + } catch (SourceNotAvailable e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + drugBankHTMLParser.setWebPageDownloader(downloader); + } + } + + @Test + public void testRefreshCacheQueryWhenDbNotAvailable() throws Exception { + WebPageDownloader downloader = drugBankHTMLParser.getWebPageDownloader(); + GeneralCacheInterface cache = drugBankHTMLParser.getCache(); + try { + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString())).thenThrow(new IOException()); + drugBankHTMLParser.setWebPageDownloader(mockDownloader); + drugBankHTMLParser.setCache(null); + + drugBankHTMLParser.refreshCacheQuery(DrugbankHTMLParser.DRUG_NAME_PREFIX + "aspirin"); + fail("Exception expected"); + } catch (SourceNotAvailable e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + drugBankHTMLParser.setWebPageDownloader(downloader); + drugBankHTMLParser.setCache(cache); + } + } + + @Test + public void testGetPubmedFromRef() throws Exception { + try { + String descriptionString = "<a href=\"/pubmed/1234\">link to 1234</a>"; + List<MiriamData> result = drugBankHTMLParser.getPubmedFromRef(descriptionString); + assertEquals(1, result.size()); + assertEquals(new MiriamData(MiriamType.PUBMED, "1234"), result.get(0)); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetPubmedFromRef2() throws Exception { + try { + String descriptionString = "<a href=\"/pubmed/12345678901234_\">link to 123456789</a>"; + List<MiriamData> result = drugBankHTMLParser.getPubmedFromRef(descriptionString); + assertEquals(1, result.size()); + assertEquals(new MiriamData(MiriamType.PUBMED, "123456789"), result.get(0)); + assertEquals(1, getWarnings().size()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetPubmedFromRef3() throws Exception { + try { + String descriptionString = "<a href=\"/pubmed/invalid\">link to invalid</a>"; + List<MiriamData> result = drugBankHTMLParser.getPubmedFromRef(descriptionString); + assertEquals(0, result.size()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetDescription() throws Exception { + try { + String descriptionString = "untagged description"; + assertNull(drugBankHTMLParser.getDescriptionForDrug(descriptionString)); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetTargets() throws Exception { + try { + String descriptionString = "invalid content"; + List<Target> targets = drugBankHTMLParser.getTargetsForDrug(descriptionString); + assertEquals(0, targets.size()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testStatus() throws Exception { + try { + assertEquals(ExternalServiceStatusType.OK, drugBankHTMLParser.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testSimulateDownStatus() throws Exception { + WebPageDownloader downloader = drugBankHTMLParser.getWebPageDownloader(); + try { + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString())).thenThrow(new IOException()); + drugBankHTMLParser.setWebPageDownloader(mockDownloader); + assertEquals(ExternalServiceStatusType.DOWN, drugBankHTMLParser.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + drugBankHTMLParser.setWebPageDownloader(downloader); + } + } + + @Test + public void testSimulateChangedStatus() throws Exception { + WebPageDownloader downloader = drugBankHTMLParser.getWebPageDownloader(); + try { + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString())).thenReturn(""); + drugBankHTMLParser.setWebPageDownloader(mockDownloader); + assertEquals(ExternalServiceStatusType.CHANGED, drugBankHTMLParser.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + drugBankHTMLParser.setWebPageDownloader(downloader); + } + } + + @Test + public void testGetBBB() throws Exception { + try { + assertTrue(drugBankHTMLParser.getBloodBrainBarrier("<tr><td>Blood Brain Barrier</td><td>-</td><td>0.7581</td></tr>").equalsIgnoreCase("NO")); + assertTrue(drugBankHTMLParser.getBloodBrainBarrier("<tr><td>Blood Brain Barrier</td><td>+</td><td>0.7581</td></tr>").equalsIgnoreCase("YES")); + assertTrue(drugBankHTMLParser.getBloodBrainBarrier("<tr><td>Blood Brain Barrier</td><td>don't know</td><td>0.7581</td></tr>").equalsIgnoreCase("N/A")); + assertTrue(drugBankHTMLParser.getBloodBrainBarrier("invalid str").equalsIgnoreCase("N/A")); + assertTrue(drugBankHTMLParser.getBloodBrainBarrier("<tr><td>Blood Brain Barrier</td>invalid str").equalsIgnoreCase("N/A")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetters() throws Exception { + DrugbankHTMLParser parser = new DrugbankHTMLParser(); + UniprotAnnotator uniprotAnnotator = new UniprotAnnotator(); + parser.setUniprotAnnotator(uniprotAnnotator); + assertEquals(uniprotAnnotator, parser.getUniprotAnnotator()); + } + +} diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ImproperAnnotationsTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ImproperAnnotationsTest.java index 86912c1ca5..64f51a4fc4 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ImproperAnnotationsTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ImproperAnnotationsTest.java @@ -15,6 +15,7 @@ import org.junit.Test; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.species.Species; public class ImproperAnnotationsTest { @@ -31,34 +32,12 @@ public class ImproperAnnotationsTest { public void tearDown() throws Exception { } - @Test - public void testConstructor() { - try { - new ImproperAnnotations(new MiriamData()); - fail("Exceptione expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Only miriam data from elements are accepted")); - } - } - - @Test - public void testConstructor2() { - try { - MiriamData md = new MiriamData(MiriamType.CAS,"a"); - md.setElement(new Species()); - ImproperAnnotations ie = new ImproperAnnotations(md); - assertNotNull(ie.toString()); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Only miriam data from elements are accepted")); - } - } - @Test public void testConstructor3() { try { - List<MiriamData> list= new ArrayList<>(); - list.add(new MiriamData(MiriamType.CAS,"a")); - ImproperAnnotations ie = new ImproperAnnotations(new Species(), list); + List<MiriamData> list = new ArrayList<>(); + list.add(new MiriamData(MiriamType.CAS, "a")); + ImproperAnnotations ie = new ImproperAnnotations(new SpeciesAlias(new Species()), list); assertNotNull(ie.toString()); } catch (InvalidArgumentException e) { assertTrue(e.getMessage().contains("Only miriam data from elements are accepted")); @@ -68,12 +47,11 @@ public class ImproperAnnotationsTest { @Test public void testConstructor4() { try { - new ImproperAnnotations(new Species(),new ArrayList<>()); + new ImproperAnnotations(new SpeciesAlias(), new ArrayList<>()); fail("Exceptione expected"); } catch (InvalidArgumentException e) { assertTrue(e.getMessage().contains("List of improper annotations cannot be null")); } } - } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MissingAnnotationTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MissingAnnotationTest.java index 2598c8173b..c09b9977ad 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MissingAnnotationTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MissingAnnotationTest.java @@ -7,6 +7,7 @@ import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.species.Species; public class MissingAnnotationTest { @@ -25,7 +26,7 @@ public class MissingAnnotationTest { @Test public void test() { - MissingAnnotation annotation = new MissingAnnotation(new Species()); + MissingAnnotation annotation = new MissingAnnotation(new SpeciesAlias(new Species())); assertTrue(annotation.toString().contains("misses annotations")); } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MissingRequiredAnnotationsTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MissingRequiredAnnotationsTest.java index d9effdfe84..f10a257d01 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MissingRequiredAnnotationsTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MissingRequiredAnnotationsTest.java @@ -12,6 +12,7 @@ import org.junit.Test; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.species.Species; public class MissingRequiredAnnotationsTest { @@ -31,7 +32,7 @@ public class MissingRequiredAnnotationsTest { @Test public void testConstructorWithInvalidParams() { try { - new MissingRequiredAnnotations(new Species(), new ArrayList<>()); + new MissingRequiredAnnotations(new SpeciesAlias(), new ArrayList<>()); } catch (InvalidArgumentException e) { assertTrue(e.getMessage().contains("List of improper annotations cannot be null")); } @@ -42,7 +43,7 @@ public class MissingRequiredAnnotationsTest { try { List<MiriamType> list = new ArrayList<>(); list.add(MiriamType.CAS); - MissingRequiredAnnotations mre = new MissingRequiredAnnotations(new Species(), list); + MissingRequiredAnnotations mre = new MissingRequiredAnnotations(new SpeciesAlias(new Species()), list); assertTrue(mre.toString().contains("misses one of the following annotations")); } catch (InvalidArgumentException e) { assertTrue(e.getMessage().contains("List of improper annotations cannot be null")); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ModelAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ModelAnnotatorTest.java index 3f5688eea7..9dce60f1b8 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ModelAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ModelAnnotatorTest.java @@ -34,6 +34,7 @@ import lcsb.mapviewer.model.map.Element; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamRelationType; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; @@ -70,17 +71,26 @@ public class ModelAnnotatorTest extends AnnotationTestFunctions { public void testAnnotateModel() { try { Model model = new ModelFullIndexed(null); - Protein species = new Protein(); - species.setName("SNCA"); - species.setElementId("id1"); - model.addElement(species); + Protein protein = new Protein(); + protein.setName("SNCA"); + protein.setElementId("id1"); + model.addElement(protein); - Protein species2 = new Protein(); - species2.setName("PDK1"); - species2.setElementId("id2"); - species2.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CAS, "c")); - model.addElement(species2); + Protein protein2 = new Protein(); + protein2.setName("PDK1"); + protein2.setElementId("id2"); + protein2.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CAS, "c")); + model.addElement(protein2); model.addReaction(new Reaction()); + + SpeciesAlias proteinAlias1 = new SpeciesAlias(protein); + proteinAlias1.setAliasId("a1"); + + SpeciesAlias proteinAlias2 = new SpeciesAlias(protein2); + proteinAlias2.setAliasId("a2"); + + model.addAlias(proteinAlias1); + model.addAlias(proteinAlias2); modelAnnotator.annotateModel(model, updater, null); @@ -246,7 +256,7 @@ public class ModelAnnotatorTest extends AnnotationTestFunctions { @Test public void testFindMissingAnnotations() throws Exception { try { - Model model = getModelForFile("testFiles/annotation/missingAnnotations.xml", true); + Model model = getModelForFile("testFiles/annotation/missingAnnotations.xml", false); Collection<? extends ProblematicAnnotation> results = modelAnnotator.findMissingAnnotations(model, null); assertEquals(7, results.size()); 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 907a84c6f3..09cc9d16f3 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 @@ -28,6 +28,7 @@ import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamRelationType; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.species.Chemical; import lcsb.mapviewer.model.map.species.SimpleMolecule; import uk.ac.ebi.chebi.webapps.chebiWS.client.ChebiWebServiceClient; @@ -320,7 +321,7 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { Chemical chemical = new SimpleMolecule(); chemical.setName("water"); - backend.annotateElement(chemical); + backend.annotateElement(new SpeciesAlias(chemical)); assertFalse(chemical.getFullName().equals("")); assertFalse(chemical.getInChI().equals("")); @@ -356,7 +357,7 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { backend.setClient(chebiWebServiceClient); backend.setCache(null); - backend.annotateElement(chemical); + backend.annotateElement(new SpeciesAlias(chemical)); fail("Exceptione expected"); } catch (AnnotatorException e) { @@ -376,7 +377,7 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { Chemical chemical = new SimpleMolecule(); chemical.setName("blasdh"); - backend.annotateElement(chemical); + backend.annotateElement(new SpeciesAlias(chemical)); assertEquals(1, getWarnings().size()); @@ -393,7 +394,7 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { chemical.setName("water"); chemical.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "CHEBI:15377")); - backend.annotateElement(chemical); + backend.annotateElement(new SpeciesAlias(chemical)); assertFalse("".equals(chemical.getFullName())); assertFalse(chemical.getInChI().equals("")); @@ -419,7 +420,7 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { chemical.addSynonym("x"); chemical.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "CHEBI:15377")); - backend.annotateElement(chemical); + backend.annotateElement(new SpeciesAlias(chemical)); assertEquals(5, getWarnings().size()); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotatorTest.java index a976dd47c3..5e6019ac4d 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotatorTest.java @@ -12,6 +12,7 @@ import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.cache.CachableInterface; import lcsb.mapviewer.annotation.cache.SourceNotAvailable; import lcsb.mapviewer.model.map.AnnotatedObject; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Ion; import lcsb.mapviewer.model.map.species.Species; @@ -62,7 +63,8 @@ public class ElementAnnotatorTest extends AnnotationTestFunctions { public void testSetNotMathcingSymbol() { Species species = new Species(); species.setSymbol("X"); - annotator.setSymbol(species, "Y", null); + SpeciesAlias speciesAlias = new SpeciesAlias(species); + annotator.setSymbol(speciesAlias, "Y", null); assertEquals(1, getWarnings().size()); } @@ -80,7 +82,8 @@ public class ElementAnnotatorTest extends AnnotationTestFunctions { public void testSetNotMatchingNotes() { Species species = new Species(); species.setNotes("X"); - annotator.setDescription(species, "Y"); + SpeciesAlias speciesAlias = new SpeciesAlias(species); + annotator.setDescription(speciesAlias, "Y"); assertEquals(0, getWarnings().size()); } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotatorTest.java index 8cdcdaa40f..013debe583 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotatorTest.java @@ -24,10 +24,11 @@ import lcsb.mapviewer.annotation.cache.WebPageDownloader; import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; import lcsb.mapviewer.annotation.services.WrongResponseCodeIOException; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.Element; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.species.GenericProtein; +import lcsb.mapviewer.model.map.species.Species; public class EnsemblAnnotatorTest extends AnnotationTestFunctions { @@ -48,7 +49,8 @@ public class EnsemblAnnotatorTest extends AnnotationTestFunctions { MiriamData nsmf = new MiriamData(MiriamType.ENSEMBL, "ENSG00000157764"); GenericProtein protein = new GenericProtein(); protein.addMiriamData(nsmf); - ensemblAnnotator.annotateElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + ensemblAnnotator.annotateElement(proteinAlias); assertNotNull(protein.getSymbol()); assertNotNull(protein.getFullName()); assertTrue(protein.getMiriamData().size() > 1); @@ -91,8 +93,9 @@ public class EnsemblAnnotatorTest extends AnnotationTestFunctions { GenericProtein protein = new GenericProtein(); protein.addMiriamData(nsmf); protein.addMiriamData(nsmf1); - ensemblAnnotator.annotateElement(protein); - + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + ensemblAnnotator.annotateElement(proteinAlias); + assertEquals(1, getWarnings().size()); } catch (Exception e) { @@ -105,8 +108,9 @@ public class EnsemblAnnotatorTest extends AnnotationTestFunctions { public void testGetAnnotationsWhenNoIdFound() throws Exception { try { GenericProtein protein = new GenericProtein(); - ensemblAnnotator.annotateElement(protein); - + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + ensemblAnnotator.annotateElement(proteinAlias); + assertEquals(1, getWarnings().size()); } catch (Exception e) { @@ -121,7 +125,8 @@ public class EnsemblAnnotatorTest extends AnnotationTestFunctions { MiriamData nsmf = new MiriamData(MiriamType.ENSEMBL, "blabla"); GenericProtein protein = new GenericProtein(); protein.addMiriamData(nsmf); - ensemblAnnotator.annotateElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + ensemblAnnotator.annotateElement(proteinAlias); assertEquals("There should be warning about invalid ensembl identifier", 1, getWarnings().size()); @@ -281,9 +286,10 @@ public class EnsemblAnnotatorTest extends AnnotationTestFunctions { WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); when(mockDownloader.getFromNetwork(anyString())).thenThrow(new WrongResponseCodeIOException(null, 0)); ensemblAnnotator.setWebPageDownloader(mockDownloader); - Element element = new GenericProtein(); + Species element = new GenericProtein(); element.addMiriamData(new MiriamData(MiriamType.ENSEMBL, "1234")); - ensemblAnnotator.annotateElement(element); + SpeciesAlias proteinAlias = new SpeciesAlias(element); + ensemblAnnotator.annotateElement(proteinAlias); fail("Exception expected"); } catch (AnnotatorException e) { } catch (Exception e) { diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotatorTest.java index e862c5ccae..90a81413d5 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotatorTest.java @@ -30,6 +30,7 @@ import lcsb.mapviewer.annotation.services.WrongResponseCodeIOException; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.species.GenericProtein; public class EntrezAnnotatorTest extends AnnotationTestFunctions { @@ -51,7 +52,8 @@ public class EntrezAnnotatorTest extends AnnotationTestFunctions { MiriamData nsmf = new MiriamData(MiriamType.ENTREZ, "84532"); GenericProtein protein = new GenericProtein(); protein.addMiriamData(nsmf); - entrezAnnotator.annotateElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + entrezAnnotator.annotateElement(proteinAlias); assertNotNull(protein.getSymbol()); assertNotNull(protein.getFullName()); assertNotNull(protein.getNotes()); @@ -88,7 +90,8 @@ public class EntrezAnnotatorTest extends AnnotationTestFunctions { MiriamData nsmf = new MiriamData(MiriamType.ENTREZ, "blabla"); GenericProtein protein = new GenericProtein(); protein.addMiriamData(nsmf); - entrezAnnotator.annotateElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + entrezAnnotator.annotateElement(proteinAlias); assertEquals(1, getWarnings().size()); @@ -310,7 +313,8 @@ public class EntrezAnnotatorTest extends AnnotationTestFunctions { public void testAnnotateElementWithoutId() throws Exception { try { GenericProtein protein = new GenericProtein(); - entrezAnnotator.annotateElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + entrezAnnotator.annotateElement(proteinAlias); assertEquals(1, getWarnings().size()); @@ -326,7 +330,8 @@ public class EntrezAnnotatorTest extends AnnotationTestFunctions { GenericProtein protein = new GenericProtein(); protein.addMiriamData(new MiriamData(MiriamType.ENTREZ, "6647")); protein.addMiriamData(new MiriamData(MiriamType.ENTREZ, "6648")); - entrezAnnotator.annotateElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + entrezAnnotator.annotateElement(proteinAlias); assertEquals(1, getWarnings().size()); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotatorTest.java index 1c718a56a4..6494c6630f 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotatorTest.java @@ -29,6 +29,7 @@ import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamRelationType; import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.agregator.Compartment; +import lcsb.mapviewer.model.map.layout.alias.CompartmentAlias; public class GoAnnotatorTest extends AnnotationTestFunctions { Logger logger = Logger.getLogger(GoAnnotatorTest.class); @@ -50,11 +51,12 @@ public class GoAnnotatorTest extends AnnotationTestFunctions { @Test public void testContent() throws Exception { try { - Compartment species = new Compartment(); - species.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.GO, "GO:0046902")); - goAnnotator.annotateElement(species); - assertFalse(species.getFullName().equals("")); - assertFalse(species.getNotes().equals("")); + Compartment comp = new Compartment(); + comp.addMiriamData(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.GO, "GO:0046902")); + CompartmentAlias compartmentAlias = new CompartmentAlias(comp); + goAnnotator.annotateElement(compartmentAlias); + assertFalse(comp.getFullName().equals("")); + assertFalse(comp.getNotes().equals("")); } catch (Exception e) { e.printStackTrace(); throw e; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotatorTest.java index f9a9a222a1..28d8a2c8cb 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotatorTest.java @@ -18,6 +18,7 @@ import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.species.GenericProtein; public class HgncAnnotatorTest extends AnnotationTestFunctions { @@ -41,7 +42,8 @@ public class HgncAnnotatorTest extends AnnotationTestFunctions { MiriamData nsmf = new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); GenericProtein protein = new GenericProtein(); protein.addMiriamData(nsmf); - hgncAnnotator.annotateElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + hgncAnnotator.annotateElement(proteinAlias); assertNotNull(protein.getSymbol()); assertTrue(protein.getFormerSymbols().size() > 0); assertNotNull(protein.getFullName()); @@ -90,7 +92,8 @@ public class HgncAnnotatorTest extends AnnotationTestFunctions { MiriamData nsmf = new MiriamData(MiriamType.HGNC, "11138"); GenericProtein protein = new GenericProtein(); protein.addMiriamData(nsmf); - hgncAnnotator.annotateElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + hgncAnnotator.annotateElement(proteinAlias); assertNotNull(protein.getSymbol()); assertTrue(protein.getFormerSymbols().size() > 0); assertNotNull(protein.getFullName()); @@ -133,7 +136,8 @@ public class HgncAnnotatorTest extends AnnotationTestFunctions { try { GenericProtein protein = new GenericProtein(); protein.setName("SNCA"); - hgncAnnotator.annotateElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + hgncAnnotator.annotateElement(proteinAlias); assertNotNull(protein.getSymbol()); assertNotNull(protein.getName()); assertTrue(protein.getFormerSymbols().size() > 0); @@ -177,7 +181,8 @@ public class HgncAnnotatorTest extends AnnotationTestFunctions { try { GenericProtein protein = new GenericProtein(); protein.setName("UNKNNOWNASD asd"); - hgncAnnotator.annotateElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + hgncAnnotator.annotateElement(proteinAlias); assertEquals(1, getWarnings().size()); @@ -192,7 +197,8 @@ public class HgncAnnotatorTest extends AnnotationTestFunctions { try { GenericProtein protein = new GenericProtein(); protein.setName("cAMP/cGMP-dependent protein kinase"); - hgncAnnotator.annotateElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + hgncAnnotator.annotateElement(proteinAlias); assertEquals(1, getWarnings().size()); @@ -247,7 +253,8 @@ public class HgncAnnotatorTest extends AnnotationTestFunctions { GenericProtein protein = new GenericProtein(); protein.addMiriamData(md1); protein.addMiriamData(md2); - hgncAnnotator.annotateElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + hgncAnnotator.annotateElement(proteinAlias); assertEquals(1, getWarnings().size()); assertEquals("SNCA", protein.getName()); } catch (Exception e) { diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotatorTest.java index 20d8ffe7f3..6c67b162ed 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotatorTest.java @@ -21,6 +21,7 @@ import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.cache.WebPageDownloader; import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; import lcsb.mapviewer.common.exception.InvalidArgumentException; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.SimpleMolecule; @@ -54,10 +55,11 @@ public class ReconAnnotatorTest extends AnnotationTestFunctions { @Test public void testAnnotateElement() throws Exception { try { - SimpleMolecule reaction = new SimpleMolecule(); - reaction.setAbbreviation("h2o"); - reconAnnotator.annotateElement(reaction); - assertTrue("No new annotations from recon db imported", reaction.getMiriamData().size() > 0); + SimpleMolecule smallMolecule = new SimpleMolecule(); + smallMolecule.setAbbreviation("h2o"); + SpeciesAlias smallMoleculeAlias = new SpeciesAlias(smallMolecule); + reconAnnotator.annotateElement(smallMoleculeAlias); + assertTrue("No new annotations from recon db imported", smallMolecule.getMiriamData().size() > 0); assertEquals(0, getWarnings().size()); } catch (Exception e) { e.printStackTrace(); @@ -68,10 +70,11 @@ public class ReconAnnotatorTest extends AnnotationTestFunctions { @Test public void testAnnotateElement2() throws Exception { try { - SimpleMolecule reaction = new SimpleMolecule(); - reaction.setAbbreviation("P5CRm"); - reconAnnotator.annotateElement(reaction); - assertEquals(0, reaction.getMiriamData().size()); + SimpleMolecule smallMolecule = new SimpleMolecule(); + smallMolecule.setAbbreviation("P5CRm"); + SpeciesAlias smallMoleculeAlias = new SpeciesAlias(smallMolecule); + reconAnnotator.annotateElement(smallMoleculeAlias); + assertEquals(0, smallMolecule.getMiriamData().size()); assertFalse(getWarnings().size() == 0); } catch (Exception e) { e.printStackTrace(); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotatorTest.java index b6d4df75d7..41304c4ae2 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotatorTest.java @@ -21,6 +21,7 @@ import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.species.Protein; public class UniprotAnnotatorTest extends AnnotationTestFunctions { @@ -42,7 +43,8 @@ public class UniprotAnnotatorTest extends AnnotationTestFunctions { Protein protein = new Protein(); protein.setName("P01308"); - uniprotAnnotator.annotateElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + uniprotAnnotator.annotateElement(proteinAlias); assertTrue(protein.getMiriamData().size() > 0); @@ -76,7 +78,8 @@ public class UniprotAnnotatorTest extends AnnotationTestFunctions { Protein protein = new Protein(); protein.setName("bla"); protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P01308")); - uniprotAnnotator.annotateElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + uniprotAnnotator.annotateElement(proteinAlias); assertTrue(protein.getMiriamData().size() > 1); @@ -110,7 +113,8 @@ public class UniprotAnnotatorTest extends AnnotationTestFunctions { Protein protein = new Protein(); protein.setName("bla"); protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "bla")); - uniprotAnnotator.annotateElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + uniprotAnnotator.annotateElement(proteinAlias); assertEquals(1, protein.getMiriamData().size()); @@ -128,7 +132,8 @@ public class UniprotAnnotatorTest extends AnnotationTestFunctions { try { Protein protein = new Protein(); protein.setName("bla"); - uniprotAnnotator.annotateElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + uniprotAnnotator.annotateElement(proteinAlias); assertEquals(0, protein.getMiriamData().size()); diff --git a/console/src/main/java/lcsb/mapviewer/run/ConsoleConverter.java b/console/src/main/java/lcsb/mapviewer/run/ConsoleConverter.java index 3f6ad5730d..ffe85ab03a 100644 --- a/console/src/main/java/lcsb/mapviewer/run/ConsoleConverter.java +++ b/console/src/main/java/lcsb/mapviewer/run/ConsoleConverter.java @@ -243,7 +243,7 @@ public class ConsoleConverter { } String className = cols[typeColumn]; - Class<? extends AnnotatedObject> clazz = elementUtils.getClassByName(className); + Class<? > clazz = elementUtils.getClassByName(className); if (clazz == null) { throw new InvalidInputDataExecption("Unknown element type: " + className, filename); } @@ -403,7 +403,7 @@ public class ConsoleConverter { } String className = cols[typeColumn]; - Class<? extends AnnotatedObject> clazz = elementUtils.getClassByName(className); + Class<? > clazz = elementUtils.getClassByName(className); if (clazz == null) { throw new InvalidInputDataExecption("Unknown element type: " + className, filename); } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteField.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteField.java index 085d68505a..b654b06476 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteField.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteField.java @@ -17,32 +17,32 @@ public enum NoteField { * List of {@link MiriamType#HGNC} identifiers. */ HGNC("HGNC_ID", AnnotatedObject.class, MiriamType.HGNC), // - + /** * List of {@link MiriamType#REFSEQ} identifiers. */ REFSEQ("RefSeq_ID", AnnotatedObject.class, MiriamType.REFSEQ), // - + /** * List of {@link MiriamType#ENTREZ} identifiers. */ ENTREZ("EntrezGene_ID", AnnotatedObject.class, MiriamType.ENTREZ), // - + /** * List of {@link MiriamType#REACTOME} identifiers. */ REACTOME("Reactome_ID", AnnotatedObject.class, MiriamType.REACTOME), // - + /** * List of {@link MiriamType#PUBMED} identifiers. */ PUBMED("Pubmed_ID", AnnotatedObject.class, MiriamType.PUBMED), // - + /** * List of {@link MiriamType#KEGG_GENES} identifiers. */ KEGG_GENES("KEGG_ID", AnnotatedObject.class, MiriamType.KEGG_GENES), // - + /** * List of {@link MiriamType#PANTHER} identifiers. */ @@ -52,22 +52,22 @@ public enum NoteField { * {@link Element#symbol}. */ SYMBOL("Symbol", Element.class, null), // - + /** * {@link Element#fullName}. */ NAME("Name", Element.class, null), // - + /** * {@link Element#notes} or {@link Reaction#notes} . */ DESCRIPTION("Description", AnnotatedObject.class, null), // - + /** * {@link Element#formerSymbols}. */ PREVIOUS_SYMBOLS("Previous Symbols", Element.class, null), // - + /** * {@link Element#synonyms} or {@link Reaction#synonyms}. */ @@ -82,27 +82,27 @@ public enum NoteField { * {@link Reaction#formula}. */ FORMULA("Formula", Reaction.class, null), // - + /** * {@link Reaction#mechanicalConfidenceScore}. */ MECHANICAL_CONFIDENCE_SCORE("MechanicalConfidenceScore", Reaction.class, null), // - + /** * {@link Reaction#lowerBound}. */ LOWER_BOUND("LowerBound", Reaction.class, null), // - + /** * {@link Reaction#upperBound}. */ UPPER_BOUND("UpperBound", Reaction.class, null), // - + /** * {@link Reaction#subsystem}. */ SUBSYSTEM("Subsystem", Reaction.class, null), // - + /** * {@link Reaction#geneProteinReaction}. */ @@ -112,7 +112,7 @@ public enum NoteField { * {@link Element#formula}. */ CHARGED_FORMULA("ChargedFormula", Element.class, null), // - + /** * {@link Species#charge}. */ @@ -121,17 +121,17 @@ public enum NoteField { /** * Name used in the notes to distinguish fields. */ - private String commonName; - + private String commonName; + /** * What object class can have this field. */ - private Class<? extends AnnotatedObject> clazz; - + private Class<?> clazz; + /** * What {@link MiriamType} is associated with the field. */ - private MiriamType miriamType; + private MiriamType miriamType; /** * Default constructor. @@ -141,7 +141,7 @@ public enum NoteField { * @param clazz * {@link #clazz} */ - NoteField(String name, Class<? extends AnnotatedObject> clazz) { + NoteField(String name, Class<?> clazz) { this.commonName = name; this.clazz = clazz; } @@ -156,7 +156,7 @@ public enum NoteField { * @param type * {@link #miriamType} */ - NoteField(String name, Class<? extends AnnotatedObject> clazz, MiriamType type) { + NoteField(String name, Class<?> clazz, MiriamType type) { this(name, clazz); this.miriamType = type; } @@ -181,7 +181,7 @@ public enum NoteField { * @return the clazz * @see #clazz */ - public Class<? extends AnnotatedObject> getClazz() { + public Class<?> getClazz() { return clazz; } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParser.java index 0a31a2b18b..7a24eea2f9 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParser.java @@ -25,6 +25,7 @@ import lcsb.mapviewer.model.map.Element; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamRelationType; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.Alias; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Species; import lcsb.mapviewer.modelutils.map.ElementUtils; @@ -650,8 +651,8 @@ public class RestAnnotationParser extends XmlParser { setUpperBoundToReaction(reaction, ann); setSubsystemToReaction(reaction, ann); setGeneProteinReactionToReaction(reaction, ann); - } else if (object instanceof Element) { - Element element = (Element) object; + } else if (object instanceof Alias) { + Element element = ((Alias) object).getElement(); setFullNameToSpecies(element, ann); setFormerSymbolsToSpecies(element, ann); if (element instanceof Species) { diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/AntisenseRnaXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/AntisenseRnaXmlParser.java index c9686b4f1e..e2850f1b46 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/AntisenseRnaXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/AntisenseRnaXmlParser.java @@ -7,6 +7,7 @@ import org.w3c.dom.NodeList; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.species.AntisenseRna; import lcsb.mapviewer.model.map.species.fields.AntisenseRnaRegion; import lcsb.mapviewer.model.map.species.fields.AntisenseRnaRegion.AntisenseRnaRegionType; @@ -35,7 +36,8 @@ public class AntisenseRnaXmlParser extends AbstractElementXmlParser<AntisenseRna Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("celldesigner:notes")) { - getRap().processNotes(node, antisenseRna); + SpeciesAlias antisenseRnaAlias = new SpeciesAlias(antisenseRna); + getRap().processNotes(node, antisenseRnaAlias); } else if (node.getNodeName().equals("celldesigner:listOfRegions")) { NodeList residueList = node.getChildNodes(); for (int j = 0; j < residueList.getLength(); j++) { diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/GeneXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/GeneXmlParser.java index fb8ea0db3c..7620293ce5 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/GeneXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/GeneXmlParser.java @@ -7,6 +7,7 @@ import org.w3c.dom.NodeList; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.species.Gene; import lcsb.mapviewer.model.map.species.fields.ModificationResidue; @@ -34,7 +35,8 @@ public class GeneXmlParser extends AbstractElementXmlParser<Gene> { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("celldesigner:notes")) { - getRap().processNotes(node, gene); + SpeciesAlias geneAlias = new SpeciesAlias(gene); + getRap().processNotes(node, geneAlias); } else if (node.getNodeName().equals("celldesigner:listOfRegions")) { NodeList residueList = node.getChildNodes(); for (int j = 0; j < residueList.getLength(); j++) { diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinXmlParser.java index c425ee2854..41fb7a8147 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinXmlParser.java @@ -7,6 +7,7 @@ import org.w3c.dom.NodeList; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.species.Protein; import lcsb.mapviewer.model.map.species.fields.ModificationResidue; @@ -56,7 +57,8 @@ public class ProteinXmlParser extends AbstractElementXmlParser<Protein> { } } } else if (node.getNodeName().equals("celldesigner:notes")) { - getRap().processNotes(node, protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + getRap().processNotes(node, proteinAlias); } else { throw new InvalidXmlSchemaException("Unknown element of celldesigner:protein " + node.getNodeName()); } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/RnaXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/RnaXmlParser.java index e71cd147aa..8d7102a2c7 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/RnaXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/RnaXmlParser.java @@ -7,6 +7,7 @@ import org.w3c.dom.NodeList; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.species.Rna; import lcsb.mapviewer.model.map.species.fields.RnaRegion; @@ -35,7 +36,8 @@ public class RnaXmlParser extends AbstractElementXmlParser<Rna> { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("celldesigner:notes")) { - getRap().processNotes(node, rna); + SpeciesAlias rnaAlias = new SpeciesAlias(rna); + getRap().processNotes(node, rnaAlias); } else if (node.getNodeName().equals("celldesigner:listOfRegions")) { NodeList residueList = node.getChildNodes(); for (int j = 0; j < residueList.getLength(); j++) { diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesCollectionXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesCollectionXmlParser.java index b91e51809b..b2e4529792 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesCollectionXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesCollectionXmlParser.java @@ -398,7 +398,8 @@ public class SpeciesCollectionXmlParser extends XmlParser { Species sp = row.getRight(); sp.setElementId(idIncluded); sp.setName(helpParser.decodeName(nameIncluded)); - rap.processNotes(notesNode, sp); + SpeciesAlias speciesAlias = new SpeciesAlias(sp); + rap.processNotes(notesNode, speciesAlias); result.add(row); } else { diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesSbmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesSbmlParser.java index da83dea93f..1860ed1845 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesSbmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesSbmlParser.java @@ -13,6 +13,7 @@ import lcsb.mapviewer.converter.model.celldesigner.annotation.XmlAnnotationParse import lcsb.mapviewer.converter.model.celldesigner.structure.SpeciesState; import lcsb.mapviewer.model.map.InconsistentModelException; import lcsb.mapviewer.model.map.agregator.Compartment; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.AntisenseRna; import lcsb.mapviewer.model.map.species.ComplexSpecies; @@ -153,7 +154,8 @@ public class SpeciesSbmlParser extends AbstractElementXmlParser<Species> { } if (notesNode != null) { - getRap().processNotes(notesNode, species); + SpeciesAlias speciesAlias = new SpeciesAlias(species); + getRap().processNotes(notesNode, speciesAlias); } if (rdfNode != null) { diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerXmlParserTest.java index 8a32a51f53..74f4148f4f 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerXmlParserTest.java @@ -453,12 +453,13 @@ public class CellDesignerXmlParserTest extends CellDesignerTestFunctions { model.setWidth(10); model.setHeight(10); Protein species = new GenericProtein(); + SpeciesAlias speciesAlias = new SpeciesAlias(species); species.setName("ROS"); species.setElementId("id1"); RestAnnotationParser rap = new RestAnnotationParser(); rap.processNotes( "Symbol: ROS1\r\nName: c-ros oncogene 1 , receptor tyrosine kinase\r\nDescription: RecName: Full=Proto-oncogene tyrosine-protein kinase ROS; EC=2.7.10.1; AltName: Full=Proto-oncogene c-Ros; AltName: Full=Proto-oncogene c-Ros-1; AltName: Full=Receptor tyrosine kinase c-ros oncogene 1; AltName: Full=c-Ros receptor tyrosine kinase; Flags: Precursor;\r\nPrevious Symbols:\r\nSynonyms: ROS, MCF3", - species); + speciesAlias); model.addElement(species); SpeciesAlias alias = new SpeciesAlias(species); @@ -466,11 +467,12 @@ public class CellDesignerXmlParserTest extends CellDesignerTestFunctions { model.addAlias(alias); SimpleMolecule species2 = new SimpleMolecule(); + SpeciesAlias speciesAlias2 = new SpeciesAlias(species2); species2.setName("PDK1"); species2.setElementId("id2"); rap.processNotes( "Symbol: ROS1\r\nName: c-ros oncogene 1 , receptor tyrosine kinase\r\nDescription: RecName: Full=Proto-oncogene tyrosine-protein kinase ROS; EC=2.7.10.1; AltName: Full=Proto-oncogene c-Ros; AltName: Full=Proto-oncogene c-Ros-1; AltName: Full=Receptor tyrosine kinase c-ros oncogene 1; AltName: Full=c-Ros receptor tyrosine kinase; Flags: Precursor;\r\nPrevious Symbols:\r\nSynonyms: ROS, MCF3", - species2); + speciesAlias2); model.addElement(species2); SpeciesAlias alias2 = new SpeciesAlias(species2); diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParserTest.java index c0f1eb5ab1..30699c2dd7 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParserTest.java @@ -27,6 +27,7 @@ import lcsb.mapviewer.model.map.Element; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamRelationType; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Protein; @@ -71,13 +72,14 @@ public class RestAnnotationParserTest extends CellDesignerTestFunctions { RestAnnotationParser parser = new RestAnnotationParser(); Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes.xml"); Protein protein = new Protein(); - parser.processNotes(node.getFirstChild(), protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + parser.processNotes(node.getFirstChild(), proteinAlias); String notes = protein.getNotes(); assertNotNull(notes); assertFalse(notes.contains("body")); assertTrue(notes.contains("some")); // after redoing it should be the same - parser.processNotes(node.getFirstChild(), protein); + parser.processNotes(node.getFirstChild(), proteinAlias); notes = protein.getNotes(); assertNotNull(notes); assertFalse(notes.contains("body")); @@ -94,13 +96,14 @@ public class RestAnnotationParserTest extends CellDesignerTestFunctions { RestAnnotationParser parser = new RestAnnotationParser(); Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes3.xml"); Protein protein = new Protein(); - parser.processNotes(node.getFirstChild(), protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + parser.processNotes(node.getFirstChild(), proteinAlias); String notes = protein.getNotes(); assertNotNull(notes); assertFalse(notes.contains("body")); assertTrue(notes.contains("some")); // after redoing it should be the same - parser.processNotes(node.getFirstChild(), protein); + parser.processNotes(node.getFirstChild(), proteinAlias); notes = protein.getNotes(); assertNotNull(notes); assertFalse(notes.contains("body")); @@ -118,13 +121,14 @@ public class RestAnnotationParserTest extends CellDesignerTestFunctions { Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes4.xml"); Protein protein = new Protein(); protein.setNotes("text"); - parser.processNotes(node.getFirstChild(), protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + parser.processNotes(node.getFirstChild(), proteinAlias); String notes = protein.getNotes(); assertNotNull(notes); assertFalse(notes.contains("body")); assertTrue(notes.contains("some")); // after redoing it should be the same - parser.processNotes(node.getFirstChild(), protein); + parser.processNotes(node.getFirstChild(), proteinAlias); notes = protein.getNotes(); assertNotNull(notes); assertFalse(notes.contains("body")); @@ -149,7 +153,8 @@ public class RestAnnotationParserTest extends CellDesignerTestFunctions { protein.setCharge(9); protein.setSymbol("D"); - parser.processNotes(node.getFirstChild(), protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + parser.processNotes(node.getFirstChild(), proteinAlias); assertEquals(1, protein.getSynonyms().size()); assertEquals(1, protein.getFormerSymbols().size()); @@ -168,7 +173,8 @@ public class RestAnnotationParserTest extends CellDesignerTestFunctions { Document node = getXmlDocumentFromFile("testFiles/xmlNodeTestExamples/notes_invalid_charge.xml"); Protein protein = new Protein(); - parser.processNotes(node.getFirstChild(), protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + parser.processNotes(node.getFirstChild(), proteinAlias); assertEquals(1, getWarnings().size()); @@ -231,13 +237,14 @@ public class RestAnnotationParserTest extends CellDesignerTestFunctions { public void testProcessRdfDescription() throws Exception { try { RestAnnotationParser rap = new RestAnnotationParser(); - Element element = new Species(); - element.setNotes( + Species species = new Species(); + species.setNotes( "begining\n" + "<rdf:RDF>" + "<rdf:Description rdf:about=\"#s2157\">\n" + "<bqmodel:is>\n" + "<rdf:Bag>\n" + "<rdf:li rdf:resource=\"urn:miriam:obo.chebi:CHEBI%3A17515\"/>\n" + "</rdf:Bag>\n" + "</bqmodel:is>\n" + "</rdf:Description>\n" + "</rdf:RDF>" + "\nend ending"); - rap.processRdfDescription(element); - assertEquals("begining\n\nend ending", element.getNotes()); + SpeciesAlias speciesAlias = new SpeciesAlias(species); + rap.processRdfDescription(speciesAlias); + assertEquals("begining\n\nend ending", species.getNotes()); } catch (Exception e) { e.printStackTrace(); throw e; @@ -431,7 +438,8 @@ public class RestAnnotationParserTest extends CellDesignerTestFunctions { try { RestAnnotationParser parser = new RestAnnotationParser(); String str = super.readFile("testFiles/xmlNodeTestExamples/notes5.xml"); - parser.processNotes(str, new Species()); + + parser.processNotes(str, new SpeciesAlias(new Species())); assertEquals(1, getWarnings().size()); diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ModelMock.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ModelMock.java index 4a877e6b7d..89912a4896 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ModelMock.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ModelMock.java @@ -619,5 +619,11 @@ public class ModelMock implements Model { logger.error("Not implemented in mock object"); } + @Override + public List<Alias> getAliasByName(String name) { + // TODO Auto-generated method stub + return null; + } + } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/Element.java b/model/src/main/java/lcsb/mapviewer/model/map/Element.java index 72f2c6c9f3..997ff3697f 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/Element.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/Element.java @@ -48,7 +48,7 @@ import lcsb.mapviewer.model.map.species.ComplexSpecies; @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "species_type_db", discriminatorType = DiscriminatorType.STRING) @DiscriminatorValue("GENERIC_ELEMENT") -public abstract class Element implements AnnotatedObject, Serializable { +public abstract class Element implements Serializable { /** * @@ -180,14 +180,14 @@ public abstract class Element implements AnnotatedObject, Serializable { this.notes = ""; } - @Override public void addMiriamData(Collection<MiriamData> miriamData) { for (MiriamData md : miriamData) { addMiriamData(md); } } - @Override + public abstract String getElementId(); + public void addMiriamData(MiriamData md) { if (this.miriamData.contains(md)) { logger.warn("Miriam data (" + md.getDataType() + ": " + md.getResource() + ") for " + getElementId() + " already exists. Ignoring..."); @@ -198,7 +198,6 @@ public abstract class Element implements AnnotatedObject, Serializable { } - @Override public void setNotes(String notes) { if (notes != null) { if (notes.contains("</html>")) { @@ -257,17 +256,14 @@ public abstract class Element implements AnnotatedObject, Serializable { this.id = id; } - @Override public String getNotes() { return notes; } - @Override public String getSymbol() { return symbol; } - @Override public void setSymbol(String symbol) { this.symbol = symbol; } @@ -289,7 +285,6 @@ public abstract class Element implements AnnotatedObject, Serializable { this.fullName = fullName; } - @Override public String getName() { return name; } @@ -303,12 +298,10 @@ public abstract class Element implements AnnotatedObject, Serializable { this.name = name; } - @Override public List<String> getSynonyms() { return synonyms; } - @Override public void setSynonyms(List<String> synonyms) { this.synonyms = synonyms; } @@ -390,27 +383,22 @@ public abstract class Element implements AnnotatedObject, Serializable { this.model = model.getModelData(); } - @Override public Set<MiriamData> getMiriamData() { return miriamData; } - @Override public String getAbbreviation() { return abbreviation; } - @Override public void setAbbreviation(String abbreviation) { this.abbreviation = abbreviation; } - @Override public String getFormula() { return formula; } - @Override public void setFormula(String formula) { this.formula = formula; } @@ -435,4 +423,5 @@ public abstract class Element implements AnnotatedObject, Serializable { this.formerSymbols.add(formerSymbol); } + public abstract void setElementId(String elementId); } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/alias/Alias.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/alias/Alias.java index 2e2f8b631b..77c681c364 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/alias/Alias.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/alias/Alias.java @@ -5,6 +5,7 @@ import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import java.util.ArrayList; +import java.util.Collection; import java.util.Comparator; import java.util.List; @@ -30,7 +31,9 @@ import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import lcsb.mapviewer.common.exception.InvalidArgumentException; +import lcsb.mapviewer.model.map.AnnotatedObject; import lcsb.mapviewer.model.map.Element; +import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.layout.graphics.LayerText; import lcsb.mapviewer.model.map.model.AliasSubmodelConnection; import lcsb.mapviewer.model.map.model.Model; @@ -51,7 +54,7 @@ import lcsb.mapviewer.model.map.model.ModelData; @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "alias_type_db", discriminatorType = DiscriminatorType.STRING) @DiscriminatorValue("GENERIC_ALIAS") -public abstract class Alias implements Serializable { +public abstract class Alias implements AnnotatedObject, Serializable { /** * @@ -796,4 +799,90 @@ public abstract class Alias implements Serializable { public void addSearchIndex(SearchIndex searchIndex) { searchIndexes.add(searchIndex); } + + @Override + public Collection<MiriamData> getMiriamData() { + return element.getMiriamData(); + } + + @Override + public void addMiriamData(Collection<MiriamData> miriamData) { + element.addMiriamData(miriamData); + } + + @Override + public void addMiriamData(MiriamData md) { + element.addMiriamData(md); + } + + @Override + public String getName() { + return element.getName(); + } + + @Override + public String getNotes() { + return element.getNotes(); + } + + @Override + public String getElementId() { + return element.getElementId(); + } + + @Override + public void setElementId(String elementId) { + element.setElementId(elementId); + } + + @Override + public void setNotes(String notes) { + element.setNotes(notes); + } + + @Override + public String getSymbol() { + return element.getSymbol(); + } + + @Override + public void setSymbol(String symbol) { + element.setSymbol(symbol); + } + + @Override + public List<String> getSynonyms() { + return element.getSynonyms(); + } + + @Override + public void setSynonyms(List<String> synonyms) { + element.setSynonyms(synonyms); + } + + @Override + public String getAbbreviation() { + return element.getAbbreviation(); + } + + @Override + public void setAbbreviation(String abbreviation) { + element.setAbbreviation(abbreviation); + } + + @Override + public void setFormula(String formula) { + element.setFormula(formula); + } + + @Override + public String getFormula() { + return element.getFormula(); + } + + @Override + public void setName(String name) { + element.setName(name); + } + } \ No newline at end of file diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/alias/CompartmentAlias.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/alias/CompartmentAlias.java index 793d49ae2c..809051ea7e 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/alias/CompartmentAlias.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/alias/CompartmentAlias.java @@ -1,421 +1,425 @@ -package lcsb.mapviewer.model.map.layout.alias; - -import java.awt.Color; -import java.awt.geom.Point2D; -import java.util.HashSet; -import java.util.Set; - -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.OneToMany; - -import org.apache.log4j.Logger; -import org.hibernate.annotations.Cascade; -import org.hibernate.annotations.CascadeType; -import org.hibernate.annotations.Type; - -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.agregator.Compartment; - -/** - * This class defines alias for compartment in the model. - * - * @author Piotr Gawron - * - */ -@Entity -@DiscriminatorValue("Compartment Alias") -public class CompartmentAlias extends Alias { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default color of the compartment alias. - */ - private static final Color DEFAULT_COLOR = Color.BLACK; - - /** - * Default witdh of the inner compartment border. - */ - private static final int DEFAULT_INNER_BORDER_WIDTH = 1; - - /** - * Default witdh of the outer compartment border. - */ - private static final int DEFAULT_OUTER_BORDER_WIDTH = 2; - - /** - * Default thickness of compartment border. - */ - private static final int DEFAULT_COMPARTMENT_THICKNESS = 12; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(CompartmentAlias.class.getName()); - - /** - * Thickness of the compartment border. - */ - private double thickness; - - /** - * How thick should be the outer line of the compartment border. - */ - private double outerWidth; - /** - * How thick should be the inner line of the compartment border. - */ - private double innerWidth; - - /** - * Describes where the description of the compartment lies. - */ - @Type(type = "lcsb.mapviewer.persist.mapper.Point2DMapper") - private Point2D namePoint; - - /** - * Aliases that are directly inside this compartment alias. - */ - @Cascade({ CascadeType.ALL }) - @OneToMany(fetch = FetchType.EAGER, mappedBy = "compartmentAlias") - private Set<Alias> aliases; - - /** - * Constructor that creates an alias which is initialized by the data from the - * parameter object. - * - * @param original - * object from which this object is initialized - */ - public CompartmentAlias(CompartmentAlias original) { - super(original); - namePoint = new Point2D.Double(); - namePoint.setLocation(original.getNamePoint()); - thickness = original.thickness; - outerWidth = original.outerWidth; - innerWidth = original.innerWidth; - aliases = new HashSet<Alias>(); - for (Alias alias : original.aliases) { - addAlias(alias.copy()); - } - } - - /** - * Default constructor. - */ - public CompartmentAlias() { - super(); - namePoint = new Point2D.Double(0, 0); - thickness = DEFAULT_COMPARTMENT_THICKNESS; - outerWidth = DEFAULT_OUTER_BORDER_WIDTH; - innerWidth = DEFAULT_INNER_BORDER_WIDTH; - setColor(DEFAULT_COLOR); - aliases = new HashSet<Alias>(); - } - - /** - * Constructor that points on the compartment. - * - * @param compartment - * alias will reference to this compartment - */ - public CompartmentAlias(Compartment compartment) { - this(); - this.setCompartment(compartment); - } - - /** - * - * @param text - * line thickness in String format - */ - public void setLineThickness(String text) { - try { - thickness = Double.parseDouble(text); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid thickness format: " + text, e); - } - } - - /** - * - * @param text - * outer line width in String format - */ - public void setLineOuterWidth(String text) { - try { - outerWidth = Double.parseDouble(text); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid outerWidth format: " + text, e); - } - } - - /** - * - * @param text - * inner line width in String format - */ - public void setLineInnerWidth(String text) { - try { - innerWidth = Double.parseDouble(text); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid innerWidth format: " + text, e); - } - } - - /** - * Add alias into the compartment alias. In case alias already exists in the - * compartment alias InvaliArgumentException is thrown. - * - * @param aliasToAdd - * alias that should be added - */ - public void addAlias(Alias aliasToAdd) { - for (Alias alias : aliases) { - if (alias.getAliasId().equals(aliasToAdd.getAliasId())) { - if (alias.equals(aliasToAdd)) { - return; - } else { - throw new InvalidArgumentException("Alias " + aliasToAdd.getAliasId() + " already on the list of compartment " + getAliasId() + " children"); - } - } - } - aliases.add(aliasToAdd); - aliasToAdd.setCompartmentAlias(this); - } - - /** - * Return set of all aliases inside the compartment alias (not necessery - * directly in the comaprtment alias). - * - * @return list of all aliases in the compartment alias - */ - public Set<Alias> getAllSubAliases() { - Set<Alias> result = new HashSet<Alias>(); - result.addAll(getAliases()); - for (Alias abstractAlias : getAliases()) { - if (abstractAlias instanceof CompartmentAlias) { - result.addAll(((CompartmentAlias) abstractAlias).getAllSubAliases()); - } - } - - return result; - } - - /** - * Check if alias given in the parameter has a common part with this - * compartment alias. In case alias2 lies inside complex the check with - * complex alias is made. - * - * @param alias2 - * alias to be checked - * @return true if the alias2 cross this compartment alias, <code>false</code> - * otherwise - */ - public boolean cross(Alias alias2) { - Set<Alias> parents = new HashSet<Alias>(); - // in case of elements in complexes we have to check if the top level - // complex cross alias - while (alias2.getParent() != null && alias2.getParent() instanceof ComplexAlias) { - alias2 = alias2.getParent(); - if (parents.contains(alias2)) { - throw new InvalidStateException("Cycled nesting in complex parents: " + alias2.getElement().getName()); - } else { - parents.add(alias2); - } - } - - Point2D argumentTopLeftCorner = new Point2D.Double(alias2.getX(), alias2.getY()); - Point2D argumentBottomRightCorner = new Point2D.Double(alias2.getX() + alias2.getWidth(), alias2.getY() + alias2.getHeight()); - - Point2D topLeftCorner = new Point2D.Double(getX(), getY()); - Point2D bottomRightCorner = new Point2D.Double(getX() + getWidth(), getY() + getHeight()); - - return (argumentTopLeftCorner.getX() < bottomRightCorner.getX() && argumentTopLeftCorner.getY() < bottomRightCorner.getY() - && argumentBottomRightCorner.getX() > topLeftCorner.getX() && argumentBottomRightCorner.getY() > topLeftCorner.getY()); - - } - - /** - * Return the title of the compartment to which it references. - * - * @return title of the underlaying compartment - */ - public String getTitle() { - if (getCompartment() != null) { - return getCompartment().getName(); - } else { - return null; - } - - } - - /** - * Checks if there is a species alias with the same name inside the - * compartment alias. - * - * @return <code>true</code> if there is alias with the same name inside - * compartment, <code>false</code> otherwise - */ - public boolean containsIdenticalSpecies() { - for (Alias a : aliases) { - if (a instanceof SpeciesAlias) { - String name = a.getElement().getName(); - if (name.equalsIgnoreCase(getTitle())) { - return true; - } - } - } - return false; - } - - /** - * Creates a copy of this CompartmentAlias. - * - * @return copy of the object - */ - public CompartmentAlias copy() { - if (this.getClass() == CompartmentAlias.class) { - return new CompartmentAlias(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } - - /** - * Removes alias from the compartment alias. - * - * @param alias - * object to be removed - */ - public void removeAlias(Alias alias) { - aliases.remove(alias); - if (alias.getCompartmentAlias() != null) { - if (alias.getCompartmentAlias() == this) { - alias.setCompartmentAlias(null); - } else { - logger.warn("Removing alias from compartment that might not belong there"); - } - } - } - - /** - * Set coordinate of the description point. - * - * @param x - * x coordinate to be set - * @param y - * y coordinate to be set - */ - public void setNamePoint(double x, double y) { - setNamePoint(new Point2D.Double(x, y)); - } - - /** - * @param aliases - * the aliases to set - */ - public void setAliases(Set<Alias> aliases) { - this.aliases = aliases; - } - - /** - * @return the thickness - * @see #thickness - */ - public double getThickness() { - return thickness; - } - - /** - * @param thickness - * the thickness to set - * @see #thickness - */ - public void setThickness(double thickness) { - this.thickness = thickness; - } - - /** - * @return the outerWidth - * @see #outerWidth - */ - public double getOuterWidth() { - return outerWidth; - } - - /** - * @param outerWidth - * the outerWidth to set - * @see #outerWidth - */ - public void setOuterWidth(double outerWidth) { - this.outerWidth = outerWidth; - } - - /** - * @return the innerWidth - * @see #innerWidth - */ - public double getInnerWidth() { - return innerWidth; - } - - /** - * @param innerWidth - * the innerWidth to set - * @see #innerWidth - */ - public void setInnerWidth(double innerWidth) { - this.innerWidth = innerWidth; - } - - /** - * @return the namePoint - * @see #namePoint - */ - public Point2D getNamePoint() { - return namePoint; - } - - /** - * @param namePoint - * the namePoint to set - * @see #namePoint - */ - public void setNamePoint(Point2D namePoint) { - this.namePoint = namePoint; - } - - /** - * @return the compartment - * @see #compartment - */ - public Compartment getCompartment() { - return (Compartment) getElement(); - } - - /** - * @param compartment - * the compartment to set - * @see #compartment - */ - public void setCompartment(Compartment compartment) { - setElement(compartment); - } - - /** - * @return the aliases - * @see #aliases - */ - public Set<Alias> getAliases() { - return aliases; - } - -} +package lcsb.mapviewer.model.map.layout.alias; + +import java.awt.Color; +import java.awt.geom.Point2D; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.OneToMany; + +import org.apache.log4j.Logger; +import org.hibernate.annotations.Cascade; +import org.hibernate.annotations.CascadeType; +import org.hibernate.annotations.Type; + +import lcsb.mapviewer.common.exception.InvalidArgumentException; +import lcsb.mapviewer.common.exception.InvalidStateException; +import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.model.map.MiriamData; +import lcsb.mapviewer.model.map.agregator.Compartment; + +/** + * This class defines alias for compartment in the model. + * + * @author Piotr Gawron + * + */ +@Entity +@DiscriminatorValue("Compartment Alias") +public class CompartmentAlias extends Alias { + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default color of the compartment alias. + */ + private static final Color DEFAULT_COLOR = Color.BLACK; + + /** + * Default witdh of the inner compartment border. + */ + private static final int DEFAULT_INNER_BORDER_WIDTH = 1; + + /** + * Default witdh of the outer compartment border. + */ + private static final int DEFAULT_OUTER_BORDER_WIDTH = 2; + + /** + * Default thickness of compartment border. + */ + private static final int DEFAULT_COMPARTMENT_THICKNESS = 12; + + /** + * Default class logger. + */ + private static Logger logger = Logger.getLogger(CompartmentAlias.class.getName()); + + /** + * Thickness of the compartment border. + */ + private double thickness; + + /** + * How thick should be the outer line of the compartment border. + */ + private double outerWidth; + /** + * How thick should be the inner line of the compartment border. + */ + private double innerWidth; + + /** + * Describes where the description of the compartment lies. + */ + @Type(type = "lcsb.mapviewer.persist.mapper.Point2DMapper") + private Point2D namePoint; + + /** + * Aliases that are directly inside this compartment alias. + */ + @Cascade({ CascadeType.ALL }) + @OneToMany(fetch = FetchType.EAGER, mappedBy = "compartmentAlias") + private Set<Alias> aliases; + + /** + * Constructor that creates an alias which is initialized by the data from the + * parameter object. + * + * @param original + * object from which this object is initialized + */ + public CompartmentAlias(CompartmentAlias original) { + super(original); + namePoint = new Point2D.Double(); + namePoint.setLocation(original.getNamePoint()); + thickness = original.thickness; + outerWidth = original.outerWidth; + innerWidth = original.innerWidth; + aliases = new HashSet<Alias>(); + for (Alias alias : original.aliases) { + addAlias(alias.copy()); + } + } + + /** + * Default constructor. + */ + public CompartmentAlias() { + super(); + namePoint = new Point2D.Double(0, 0); + thickness = DEFAULT_COMPARTMENT_THICKNESS; + outerWidth = DEFAULT_OUTER_BORDER_WIDTH; + innerWidth = DEFAULT_INNER_BORDER_WIDTH; + setColor(DEFAULT_COLOR); + aliases = new HashSet<Alias>(); + } + + /** + * Constructor that points on the compartment. + * + * @param compartment + * alias will reference to this compartment + */ + public CompartmentAlias(Compartment compartment) { + this(); + this.setCompartment(compartment); + } + + /** + * + * @param text + * line thickness in String format + */ + public void setLineThickness(String text) { + try { + thickness = Double.parseDouble(text); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid thickness format: " + text, e); + } + } + + /** + * + * @param text + * outer line width in String format + */ + public void setLineOuterWidth(String text) { + try { + outerWidth = Double.parseDouble(text); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid outerWidth format: " + text, e); + } + } + + /** + * + * @param text + * inner line width in String format + */ + public void setLineInnerWidth(String text) { + try { + innerWidth = Double.parseDouble(text); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid innerWidth format: " + text, e); + } + } + + /** + * Add alias into the compartment alias. In case alias already exists in the + * compartment alias InvaliArgumentException is thrown. + * + * @param aliasToAdd + * alias that should be added + */ + public void addAlias(Alias aliasToAdd) { + for (Alias alias : aliases) { + if (alias.getAliasId().equals(aliasToAdd.getAliasId())) { + if (alias.equals(aliasToAdd)) { + return; + } else { + throw new InvalidArgumentException("Alias " + aliasToAdd.getAliasId() + " already on the list of compartment " + getAliasId() + " children"); + } + } + } + aliases.add(aliasToAdd); + aliasToAdd.setCompartmentAlias(this); + } + + /** + * Return set of all aliases inside the compartment alias (not necessery + * directly in the comaprtment alias). + * + * @return list of all aliases in the compartment alias + */ + public Set<Alias> getAllSubAliases() { + Set<Alias> result = new HashSet<Alias>(); + result.addAll(getAliases()); + for (Alias abstractAlias : getAliases()) { + if (abstractAlias instanceof CompartmentAlias) { + result.addAll(((CompartmentAlias) abstractAlias).getAllSubAliases()); + } + } + + return result; + } + + /** + * Check if alias given in the parameter has a common part with this + * compartment alias. In case alias2 lies inside complex the check with + * complex alias is made. + * + * @param alias2 + * alias to be checked + * @return true if the alias2 cross this compartment alias, <code>false</code> + * otherwise + */ + public boolean cross(Alias alias2) { + Set<Alias> parents = new HashSet<Alias>(); + // in case of elements in complexes we have to check if the top level + // complex cross alias + while (alias2.getParent() != null && alias2.getParent() instanceof ComplexAlias) { + alias2 = alias2.getParent(); + if (parents.contains(alias2)) { + throw new InvalidStateException("Cycled nesting in complex parents: " + alias2.getElement().getName()); + } else { + parents.add(alias2); + } + } + + Point2D argumentTopLeftCorner = new Point2D.Double(alias2.getX(), alias2.getY()); + Point2D argumentBottomRightCorner = new Point2D.Double(alias2.getX() + alias2.getWidth(), alias2.getY() + alias2.getHeight()); + + Point2D topLeftCorner = new Point2D.Double(getX(), getY()); + Point2D bottomRightCorner = new Point2D.Double(getX() + getWidth(), getY() + getHeight()); + + return (argumentTopLeftCorner.getX() < bottomRightCorner.getX() && argumentTopLeftCorner.getY() < bottomRightCorner.getY() + && argumentBottomRightCorner.getX() > topLeftCorner.getX() && argumentBottomRightCorner.getY() > topLeftCorner.getY()); + + } + + /** + * Return the title of the compartment to which it references. + * + * @return title of the underlaying compartment + */ + public String getTitle() { + if (getCompartment() != null) { + return getCompartment().getName(); + } else { + return null; + } + + } + + /** + * Checks if there is a species alias with the same name inside the + * compartment alias. + * + * @return <code>true</code> if there is alias with the same name inside + * compartment, <code>false</code> otherwise + */ + public boolean containsIdenticalSpecies() { + for (Alias a : aliases) { + if (a instanceof SpeciesAlias) { + String name = a.getElement().getName(); + if (name.equalsIgnoreCase(getTitle())) { + return true; + } + } + } + return false; + } + + /** + * Creates a copy of this CompartmentAlias. + * + * @return copy of the object + */ + public CompartmentAlias copy() { + if (this.getClass() == CompartmentAlias.class) { + return new CompartmentAlias(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } + + /** + * Removes alias from the compartment alias. + * + * @param alias + * object to be removed + */ + public void removeAlias(Alias alias) { + aliases.remove(alias); + if (alias.getCompartmentAlias() != null) { + if (alias.getCompartmentAlias() == this) { + alias.setCompartmentAlias(null); + } else { + logger.warn("Removing alias from compartment that might not belong there"); + } + } + } + + /** + * Set coordinate of the description point. + * + * @param x + * x coordinate to be set + * @param y + * y coordinate to be set + */ + public void setNamePoint(double x, double y) { + setNamePoint(new Point2D.Double(x, y)); + } + + /** + * @param aliases + * the aliases to set + */ + public void setAliases(Set<Alias> aliases) { + this.aliases = aliases; + } + + /** + * @return the thickness + * @see #thickness + */ + public double getThickness() { + return thickness; + } + + /** + * @param thickness + * the thickness to set + * @see #thickness + */ + public void setThickness(double thickness) { + this.thickness = thickness; + } + + /** + * @return the outerWidth + * @see #outerWidth + */ + public double getOuterWidth() { + return outerWidth; + } + + /** + * @param outerWidth + * the outerWidth to set + * @see #outerWidth + */ + public void setOuterWidth(double outerWidth) { + this.outerWidth = outerWidth; + } + + /** + * @return the innerWidth + * @see #innerWidth + */ + public double getInnerWidth() { + return innerWidth; + } + + /** + * @param innerWidth + * the innerWidth to set + * @see #innerWidth + */ + public void setInnerWidth(double innerWidth) { + this.innerWidth = innerWidth; + } + + /** + * @return the namePoint + * @see #namePoint + */ + public Point2D getNamePoint() { + return namePoint; + } + + /** + * @param namePoint + * the namePoint to set + * @see #namePoint + */ + public void setNamePoint(Point2D namePoint) { + this.namePoint = namePoint; + } + + /** + * @return the compartment + * @see #compartment + */ + public Compartment getCompartment() { + return (Compartment) getElement(); + } + + /** + * @param compartment + * the compartment to set + * @see #compartment + */ + public void setCompartment(Compartment compartment) { + setElement(compartment); + } + + /** + * @return the aliases + * @see #aliases + */ + public Set<Alias> getAliases() { + return aliases; + } + + +} diff --git a/model/src/main/java/lcsb/mapviewer/model/map/model/Model.java b/model/src/main/java/lcsb/mapviewer/model/map/model/Model.java index 898fbf4110..aedb3c3796 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/model/Model.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/model/Model.java @@ -467,6 +467,8 @@ public interface Model { * @return list of species */ List<Species> getSpeciesByName(String name); + + List<Alias> getAliasByName(String name); /** * diff --git a/model/src/main/java/lcsb/mapviewer/model/map/model/ModelFullIndexed.java b/model/src/main/java/lcsb/mapviewer/model/map/model/ModelFullIndexed.java index 20435af719..512f0e5264 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/model/ModelFullIndexed.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/model/ModelFullIndexed.java @@ -200,13 +200,12 @@ public class ModelFullIndexed implements Model { if (al.getElement() == null) { throw new InvalidArgumentException("ComplexAlias must point to ComplexSpecies. Alias id: " + al.getAliasId() + ", Species id: null"); } else { - throw new InvalidArgumentException( - "ComplexAlias must point to ComplexSpecies. Alias id: " + al.getAliasId() + ", Species id: " + al.getElement().getElementId()); + throw new InvalidArgumentException("ComplexAlias must point to ComplexSpecies. Alias id: " + al.getAliasId() + ", Species id: " + al.getElementId()); } } if (!(al instanceof ComplexAlias) && (al.getSpecies() instanceof ComplexSpecies)) { throw new InvalidArgumentException( - "Non ComplexAlias cannot point to ComplexSpecies. Alias id: " + al.getAliasId() + ", Species id: " + al.getElement().getElementId()); + "Non ComplexAlias cannot point to ComplexSpecies. Alias id: " + al.getAliasId() + ", Species id: " + al.getElementId()); } modelData.addAlias(al); String idSpecies = null; @@ -541,10 +540,10 @@ public class ModelFullIndexed implements Model { @Override public Set<AnnotatedObject> getElementsByAnnotation(MiriamData miriamData) { Set<AnnotatedObject> result = new HashSet<AnnotatedObject>(); - for (Element element : getElements()) { - for (MiriamData md : element.getMiriamData()) { + for (Alias alias : getAliases()) { + for (MiriamData md : alias.getMiriamData()) { if (md.equals(miriamData)) { - result.add(element); + result.add(alias); } } } @@ -697,7 +696,7 @@ public class ModelFullIndexed implements Model { } } else if (alias instanceof CompartmentAlias) { if (!(alias instanceof ArtifitialCompartmentAlias)) { - String compartmentId = alias.getElement().getElementId(); + String compartmentId = alias.getElementId(); List<CompartmentAlias> list = compartmentsAliasByCompartmentId.get(compartmentId); if (list != null) { list.remove(alias); @@ -841,10 +840,10 @@ public class ModelFullIndexed implements Model { // have information about full species here...) so in addAlias method we add // a // "stub species" that we will have to override later - for (SpeciesAlias alias2 : aliasList) { - alias2.setSpecies(species); - } + for (SpeciesAlias alias2 : aliasList) { + alias2.setSpecies(species); } + } @Override public ModelData getModelData() { @@ -939,7 +938,7 @@ public class ModelFullIndexed implements Model { } Integer id = Integer.parseInt(identifier); return getSubmodelById(id); - } + } @Override public Collection<Model> getSubmodels() { @@ -1072,7 +1071,7 @@ public class ModelFullIndexed implements Model { @Override public List<AnnotatedObject> getAnnotatedObjects() { List<AnnotatedObject> result = new ArrayList<>(); - result.addAll(getElements()); + result.addAll(getAliases()); result.addAll(getReactions()); return result; } @@ -1089,4 +1088,15 @@ public class ModelFullIndexed implements Model { } addCreationWarnings(warnings); } + + @Override + public List<Alias> getAliasByName(String name) { + List<Alias> result = new ArrayList<>(); + for (Alias element : getAliases()) { + if (element.getName().equalsIgnoreCase(name)) { + result.add(element); + } + } + return result; + } } diff --git a/model/src/main/java/lcsb/mapviewer/modelutils/map/ElementUtils.java b/model/src/main/java/lcsb/mapviewer/modelutils/map/ElementUtils.java index f269cbe903..d3f62acd71 100644 --- a/model/src/main/java/lcsb/mapviewer/modelutils/map/ElementUtils.java +++ b/model/src/main/java/lcsb/mapviewer/modelutils/map/ElementUtils.java @@ -208,11 +208,11 @@ public final class ElementUtils { * name of the class * @return {@link Class} that extends {@link AnnotatedObject} for a given name */ - public Class<? extends AnnotatedObject> getClassByName(String name) { + public Class<?> getClassByName(String name) { if (elementClasses == null) { refreshClasses(); } - Class<? extends AnnotatedObject> result = elementClasses.get(name); + Class<?> result = elementClasses.get(name); if (result == null) { result = reactionClasses.get(name); } @@ -252,4 +252,8 @@ public final class ElementUtils { ElementUtils.reactionClasses = reactionClasses; } + public String getElementTag(Element element) { + return "[" + element.getClass().getSimpleName() + " " + element.getElementId() + "]\t"; + } + } diff --git a/model/src/main/java/lcsb/mapviewer/modelutils/map/RequireAnnotationMap.java b/model/src/main/java/lcsb/mapviewer/modelutils/map/RequireAnnotationMap.java index 274c8a0470..61d6a8967f 100644 --- a/model/src/main/java/lcsb/mapviewer/modelutils/map/RequireAnnotationMap.java +++ b/model/src/main/java/lcsb/mapviewer/modelutils/map/RequireAnnotationMap.java @@ -19,57 +19,56 @@ import lcsb.mapviewer.model.map.species.Rna; * */ public enum RequireAnnotationMap { - + /** * {@link Reaction}. */ REACTION(Reaction.class), - + /** * {@link Protein}. */ PROTEIN(Protein.class), - + /** * {@link Chemical}. */ CHECMICAL(Chemical.class), - + /** * {@link Rna}. */ RNA(Rna.class), - + /** * {@link Gene}. */ GENE(Gene.class), - + /** * {@link Drug}. */ DRUG(Drug.class), - + /** * {@link ComplexSpecies}. */ COMPLEX(ComplexSpecies.class), - + /** * {@link AntisenseRna}. */ ANTISENSE_RNA(AntisenseRna.class), - + /** * {@link Phenotype}. */ PHENOTYPE(Phenotype.class); - /** * Class which should be annotated. */ - private Class<? extends AnnotatedObject> clazz; + private Class<?> clazz; /** * Default constructor. @@ -77,7 +76,7 @@ public enum RequireAnnotationMap { * @param clazz * {@link #clazz} */ - RequireAnnotationMap(Class<? extends AnnotatedObject> clazz) { + RequireAnnotationMap(Class<?> clazz) { this.clazz = clazz; } @@ -85,7 +84,7 @@ public enum RequireAnnotationMap { * @return the clazz * @see #clazz */ - public Class<? extends AnnotatedObject> getClazz() { + public Class<?> getClazz() { return clazz; } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/alias/AliasComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/alias/AliasComparatorTest.java index 727d7596d9..bdea46ff16 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/alias/AliasComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/alias/AliasComparatorTest.java @@ -1,184 +1,289 @@ -package lcsb.mapviewer.model.map.layout.alias; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.awt.Color; - -import lcsb.mapviewer.common.exception.InvalidClassException; -import lcsb.mapviewer.model.map.Element; -import lcsb.mapviewer.model.map.agregator.Compartment; -import lcsb.mapviewer.model.map.layout.graphics.Layer; -import lcsb.mapviewer.model.map.model.AliasSubmodelConnection; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.model.SubmodelType; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Protein; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class AliasComparatorTest { - - public class Mock extends Alias { - - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - public Alias copy() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Element getElement() { - // TODO Auto-generated method stub - return null; - } - - } - - AliasComparator comparator = new AliasComparator(); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testCompareException() throws Exception { - try { - comparator.compare(new Mock(), new Mock()); - - fail("Exception should occur"); - } catch (InvalidClassException e) { - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testEquals() throws Exception { - try { - assertEquals(0, comparator.compare(new SpeciesAlias("id2"), new SpeciesAlias("id2"))); - assertEquals(0, comparator.compare(new ComplexAlias(), new ComplexAlias())); - assertEquals(0, comparator.compare(null, null)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testDifferent() throws Exception { - try { - assertTrue(comparator.compare(new SpeciesAlias("id2"), new SpeciesAlias("id1")) != 0); - - assertTrue(comparator.compare(null, new SpeciesAlias()) != 0); - assertTrue(comparator.compare(new SpeciesAlias(), null) != 0); - assertTrue(comparator.compare(new SpeciesAlias(), new ComplexAlias()) != 0); - - SpeciesAlias sa1 = new SpeciesAlias("id2"); - SpeciesAlias sa2 = new SpeciesAlias("id2"); - sa2.setY(2); - assertTrue(comparator.compare(sa1, sa2) != 0); - - sa1 = new SpeciesAlias("id2"); - sa2 = new SpeciesAlias("id2"); - sa2.setY(2); - assertTrue(comparator.compare(sa1, sa2) != 0); - - sa1 = new SpeciesAlias("id2"); - sa2 = new SpeciesAlias("id2"); - sa2.setHeight(2); - assertTrue(comparator.compare(sa1, sa2) != 0); - - sa1 = new SpeciesAlias("id2"); - sa2 = new SpeciesAlias("id2"); - sa2.setFontSize(2); - assertTrue(comparator.compare(sa1, sa2) != 0); - - sa1 = new SpeciesAlias("id2"); - sa2 = new SpeciesAlias("id2"); - sa2.setColor(Color.BLUE); - assertTrue(comparator.compare(sa1, sa2) != 0); - - sa1 = new SpeciesAlias("id2"); - sa2 = new SpeciesAlias("id2"); - sa2.setVisibilityLevel(6); - assertTrue(comparator.compare(sa1, sa2) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCompareSubmodel() throws Exception { - try { - Alias alias1 = createAlias(); - Alias alias2 = createAlias(); - assertEquals(0, comparator.compare(alias1,alias2)); - - alias1.setSubmodel(null); - assertTrue(comparator.compare(alias1, alias2) != 0); - assertTrue(comparator.compare(alias2, alias1) != 0); - - alias1 = createAlias(); - alias2 = createAlias(); - - alias1.getSubmodel().setName("Na"); - - assertTrue(comparator.compare(alias1, alias2) != 0); - assertTrue(comparator.compare(alias2, alias1) != 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - private Alias createAlias() { - Alias result = new SpeciesAlias("id2"); - AliasSubmodelConnection submodel = new AliasSubmodelConnection(getModel(), SubmodelType.DOWNSTREAM_TARGETS); - result.setSubmodel(submodel); - return result; - } - - private Model getModel() { - Model model = new ModelFullIndexed(null);; - model.setNotes("Some description"); - Protein protein = new Protein(); - protein.setName("ad"); - protein.setElementId("A"); - model.addElement(protein); - - SpeciesAlias alias = new SpeciesAlias(protein); - alias.setAliasId("a_id"); - model.addAlias(alias); - - Compartment compartment = new Compartment("default"); - model.addCompartment(compartment); - - Layer layer = new Layer(); - layer.setName("layer name"); - model.addLayer(layer); - - model.addReaction(new Reaction()); - return model; - } - -} +package lcsb.mapviewer.model.map.layout.alias; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.awt.Color; +import java.util.Collection; +import java.util.List; + +import lcsb.mapviewer.common.exception.InvalidClassException; +import lcsb.mapviewer.model.map.Element; +import lcsb.mapviewer.model.map.MiriamData; +import lcsb.mapviewer.model.map.agregator.Compartment; +import lcsb.mapviewer.model.map.layout.graphics.Layer; +import lcsb.mapviewer.model.map.model.AliasSubmodelConnection; +import lcsb.mapviewer.model.map.model.Model; +import lcsb.mapviewer.model.map.model.ModelFullIndexed; +import lcsb.mapviewer.model.map.model.SubmodelType; +import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.species.Protein; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class AliasComparatorTest { + + public class Mock extends Alias { + + /** + * + */ + private static final long serialVersionUID = 1L; + + @Override + public Alias copy() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Element getElement() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Collection<MiriamData> getMiriamData() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void addMiriamData(Collection<MiriamData> miriamData) { + // TODO Auto-generated method stub + + } + + @Override + public void addMiriamData(MiriamData md) { + // TODO Auto-generated method stub + + } + + @Override + public String getName() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getNotes() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getElementId() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setElementId(String id) { + // TODO Auto-generated method stub + + } + + @Override + public void setNotes(String notes) { + // TODO Auto-generated method stub + + } + + @Override + public String getSymbol() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setSymbol(String symbol) { + // TODO Auto-generated method stub + + } + + @Override + public List<String> getSynonyms() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setSynonyms(List<String> synonyms) { + // TODO Auto-generated method stub + + } + + @Override + public String getAbbreviation() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setAbbreviation(String abbreviation) { + // TODO Auto-generated method stub + + } + + @Override + public void setFormula(String formula) { + // TODO Auto-generated method stub + + } + + @Override + public String getFormula() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setName(String name) { + // TODO Auto-generated method stub + + } + + } + + AliasComparator comparator = new AliasComparator(); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testCompareException() throws Exception { + try { + comparator.compare(new Mock(), new Mock()); + + fail("Exception should occur"); + } catch (InvalidClassException e) { + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testEquals() throws Exception { + try { + assertEquals(0, comparator.compare(new SpeciesAlias("id2"), new SpeciesAlias("id2"))); + assertEquals(0, comparator.compare(new ComplexAlias(), new ComplexAlias())); + assertEquals(0, comparator.compare(null, null)); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testDifferent() throws Exception { + try { + assertTrue(comparator.compare(new SpeciesAlias("id2"), new SpeciesAlias("id1")) != 0); + + assertTrue(comparator.compare(null, new SpeciesAlias()) != 0); + assertTrue(comparator.compare(new SpeciesAlias(), null) != 0); + assertTrue(comparator.compare(new SpeciesAlias(), new ComplexAlias()) != 0); + + SpeciesAlias sa1 = new SpeciesAlias("id2"); + SpeciesAlias sa2 = new SpeciesAlias("id2"); + sa2.setY(2); + assertTrue(comparator.compare(sa1, sa2) != 0); + + sa1 = new SpeciesAlias("id2"); + sa2 = new SpeciesAlias("id2"); + sa2.setY(2); + assertTrue(comparator.compare(sa1, sa2) != 0); + + sa1 = new SpeciesAlias("id2"); + sa2 = new SpeciesAlias("id2"); + sa2.setHeight(2); + assertTrue(comparator.compare(sa1, sa2) != 0); + + sa1 = new SpeciesAlias("id2"); + sa2 = new SpeciesAlias("id2"); + sa2.setFontSize(2); + assertTrue(comparator.compare(sa1, sa2) != 0); + + sa1 = new SpeciesAlias("id2"); + sa2 = new SpeciesAlias("id2"); + sa2.setColor(Color.BLUE); + assertTrue(comparator.compare(sa1, sa2) != 0); + + sa1 = new SpeciesAlias("id2"); + sa2 = new SpeciesAlias("id2"); + sa2.setVisibilityLevel(6); + assertTrue(comparator.compare(sa1, sa2) != 0); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testCompareSubmodel() throws Exception { + try { + Alias alias1 = createAlias(); + Alias alias2 = createAlias(); + assertEquals(0, comparator.compare(alias1,alias2)); + + alias1.setSubmodel(null); + assertTrue(comparator.compare(alias1, alias2) != 0); + assertTrue(comparator.compare(alias2, alias1) != 0); + + alias1 = createAlias(); + alias2 = createAlias(); + + alias1.getSubmodel().setName("Na"); + + assertTrue(comparator.compare(alias1, alias2) != 0); + assertTrue(comparator.compare(alias2, alias1) != 0); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + private Alias createAlias() { + Alias result = new SpeciesAlias("id2"); + AliasSubmodelConnection submodel = new AliasSubmodelConnection(getModel(), SubmodelType.DOWNSTREAM_TARGETS); + result.setSubmodel(submodel); + return result; + } + + private Model getModel() { + Model model = new ModelFullIndexed(null);; + model.setNotes("Some description"); + Protein protein = new Protein(); + protein.setName("ad"); + protein.setElementId("A"); + model.addElement(protein); + + SpeciesAlias alias = new SpeciesAlias(protein); + alias.setAliasId("a_id"); + model.addAlias(alias); + + Compartment compartment = new Compartment("default"); + model.addCompartment(compartment); + + Layer layer = new Layer(); + layer.setName("layer name"); + model.addLayer(layer); + + model.addReaction(new Reaction()); + return model; + } + +} diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelFullIndexedTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelFullIndexedTest.java index 1732e11cac..0f5f9f0033 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelFullIndexedTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelFullIndexedTest.java @@ -1457,7 +1457,11 @@ public class ModelFullIndexedTest { Reaction reaction = new Reaction(); reaction.setIdReaction(reactionId); model.addReaction(reaction); - model.addElement(new Species("s")); + Species species =new Species("s"); + model.addElement(species); + SpeciesAlias alias = new SpeciesAlias(species); + alias.setAliasId("2"); + model.addAlias(alias); Collection<AnnotatedObject> obj = model.getAnnotatedObjects(); assertEquals(2, obj.size()); diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelTest.java index 97c1dc95ec..3c52371d25 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelTest.java @@ -258,16 +258,16 @@ public class ModelTest { assertNotNull(elements); assertEquals(1, elements.size()); AnnotatedObject element = elements.iterator().next(); - assertTrue(element instanceof Species); - Species species = (Species) element; + assertTrue(element instanceof SpeciesAlias); + SpeciesAlias species = (SpeciesAlias) element; assertEquals("s5", species.getName()); elements = model.getElementsByAnnotation(new MiriamData(MiriamRelationType.BQ_MODEL_IS, MiriamType.CHEBI, "CHEBI:12")); assertNotNull(elements); assertEquals(1, elements.size()); element = elements.iterator().next(); - assertTrue(element instanceof Compartment); - Compartment compartment = (Compartment) element; + assertTrue(element instanceof CompartmentAlias); + CompartmentAlias compartment = (CompartmentAlias) element; assertEquals("c1", compartment.getName()); elements = model.getElementsByAnnotation(new MiriamData(MiriamRelationType.BQ_MODEL_IS, MiriamType.CHEBI, "CHEBI:12234")); @@ -286,32 +286,50 @@ public class ModelTest { Protein protein = new Protein(); protein.setElementId("s1"); protein.setName("s1"); - + model.addElement(protein); + SpeciesAlias proteinAlias = new SpeciesAlias(protein); + proteinAlias.setAliasId("sa1"); + model.addAlias(proteinAlias); Protein protein2 = new Protein(); protein2.setElementId("s2"); protein2.setName("s1"); model.addElement(protein2); + SpeciesAlias proteinAlias2 = new SpeciesAlias(protein2); + proteinAlias2.setAliasId("sa2"); + model.addAlias(proteinAlias2); Protein protein3 = new Protein(); protein3.setElementId("s3"); protein3.setName("s1"); model.addElement(protein3); + + SpeciesAlias proteinAlias3 = new SpeciesAlias(protein3); + proteinAlias3.setAliasId("sa3"); + model.addAlias(proteinAlias3); Protein protein4 = new Protein(); protein4.setElementId("s5"); protein4.setName("s5"); protein4.addMiriamData(new MiriamData(MiriamRelationType.BQ_MODEL_IS, MiriamType.CHEMBL_TARGET, "CHEMBL12345")); + + SpeciesAlias proteinAlias4 = new SpeciesAlias(protein4); + proteinAlias4.setAliasId("sa4"); + model.addAlias(proteinAlias4); Compartment compartment = new Compartment(); compartment.setElementId("c1"); compartment.setName("c1"); compartment.addMiriamData(new MiriamData(MiriamRelationType.BQ_MODEL_IS, MiriamType.CHEBI, "CHEBI:12")); model.addCompartment(compartment); + + CompartmentAlias compartmentAlias = new CompartmentAlias(compartment); + compartmentAlias.setAliasId("cca"); model.addElement(protein4); + model.addAlias(compartmentAlias); return model; } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ModelContructor.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ModelContructor.java index 14660e14ad..b0fbdcacd5 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ModelContructor.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ModelContructor.java @@ -1067,10 +1067,10 @@ public class ModelContructor { ComplexAlias cAlias = (ComplexAlias) alias; if (cAlias.getSize() <= EPSILON && cAlias.getAllChildrenAliases().size() == 0) { if (aliasesInReaction.contains(alias)) { - logger.warn(eu.getElementTag(alias.getElement()) + "Empty element is invalid, but it's a part of reaction."); + logger.warn(eu.getElementTag(alias) + "Empty element is invalid, but it's a part of reaction."); } else { toRemove.add(alias); - logger.warn(eu.getElementTag(alias.getElement()) + "Empty element is invalid"); + logger.warn(eu.getElementTag(alias) + "Empty element is invalid"); } } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ModelToGPML.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ModelToGPML.java index d7afde1d03..601807c3eb 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ModelToGPML.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ModelToGPML.java @@ -592,10 +592,7 @@ public class ModelToGPML { gpml.append(getComparments(model)); gpml.append(groups); Set<MiriamData> set = new HashSet<>(); - for (AnnotatedObject element : model.getElements()) { - set.addAll(element.getMiriamData()); - } - for (AnnotatedObject element : model.getReactions()) { + for (AnnotatedObject element : model.getAnnotatedObjects()) { set.addAll(element.getMiriamData()); } diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/SearchService.java b/service/src/main/java/lcsb/mapviewer/services/impl/SearchService.java index 829ff6b30a..95083039b9 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/SearchService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/SearchService.java @@ -1,781 +1,783 @@ -package lcsb.mapviewer.services.impl; - -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.transaction.annotation.Transactional; - -import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidClassException; -import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.model.map.AnnotatedObject; -import lcsb.mapviewer.model.map.Element; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.layout.alias.Alias; -import lcsb.mapviewer.model.map.layout.alias.CompartmentAlias; -import lcsb.mapviewer.model.map.layout.alias.SearchIndex; -import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.ReactionNode; -import lcsb.mapviewer.model.map.species.ComplexSpecies; -import lcsb.mapviewer.model.map.species.Degraded; -import lcsb.mapviewer.model.map.species.Drug; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Unknown; -import lcsb.mapviewer.model.map.statistics.SearchType; -import lcsb.mapviewer.persist.dao.map.ModelDao; -import lcsb.mapviewer.services.interfaces.ISearchHistoryService; -import lcsb.mapviewer.services.interfaces.ISearchService; -import lcsb.mapviewer.services.overlay.IconManager; -import lcsb.mapviewer.services.overlay.IconType; -import lcsb.mapviewer.services.search.IHeavyView; -import lcsb.mapviewer.services.search.data.FullAliasView; -import lcsb.mapviewer.services.search.data.FullAliasViewFactory; -import lcsb.mapviewer.services.search.data.FullReactionView; -import lcsb.mapviewer.services.search.data.FullReactionViewFactory; -import lcsb.mapviewer.services.search.data.SearchElementResult; -import lcsb.mapviewer.services.utils.SearchIndexer; - -/** - * This is implementation of the service that returns information about species, - * paths etc in the model. - * - * - * @author Piotr Gawron - * - */ -@Transactional(value = "txManager") -public class SearchService implements ISearchService { - - /** - * Prefix used in search by name interface to limit results only to species. - */ - public static final String SPECIES_SEARCH_PREFIX = "species"; - - /** - * Prefix used in search by name interface to limit results only to reactions. - */ - public static final String REACTION_SEARCH_PREFIX = "reaction"; - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = Logger.getLogger(SearchService.class.getName()); - - /** - * Data access object for models. - */ - @Autowired - private ModelDao modelDao; - - /** - * Service used for managing search history. - */ - @Autowired - private ISearchHistoryService searchHistoryService; - - /** - * Factory object used to create {@link FullAliasView} objects. - */ - @Autowired - private FullAliasViewFactory fullAliasViewFactory; - - /** - * Factory object used to create {@link FullReactionView} objects. - */ - @Autowired - private FullReactionViewFactory fullReactionViewFactory; - - /** - * Object used for indexing elements on the map. - */ - private SearchIndexer searchIndexer = new SearchIndexer(); - - /** - * This object maps class of elements on the map into short string prefixes - * used in the search query. For instance elements of the - * {@link ComplexSpecies} class could be searched with the prefix "complex" - * (example query: "complex:alpha subcomplex"). - */ - private Map<Class<? extends Element>, String> speciesSearchPrefix = new HashMap<Class<? extends Element>, String>(); - - /** - * This object maps short string prefixes into class of elements on the map - * that will be searched. For instance prefix "complex" might refer to - * {@link ComplexSpecies} class and and example query would look like: - * "complex:alpha subcomplex". - */ - private Map<String, Class<? extends Element>> speciesSearchReversePrefix = new HashMap<String, Class<? extends Element>>(); - - /** - * Default constructor that set list of prefixes used in the search queries. - */ - public SearchService() { - addSearchPrefix("complex", ComplexSpecies.class); - addSearchPrefix("degrded", Degraded.class); - addSearchPrefix("drug", Drug.class); - addSearchPrefix("gene", Gene.class); - addSearchPrefix("ion", Ion.class); - addSearchPrefix("phenotype", Phenotype.class); - addSearchPrefix("protein", Protein.class); - addSearchPrefix("rna", Rna.class); - addSearchPrefix("molecule", SimpleMolecule.class); - addSearchPrefix("unknown", Unknown.class); - } - - /** - * Adds search prefix for an element class. - * - * @param prefix - * string prefix used in search queries - * @param clazz - * class for which this prefix stands - */ - private void addSearchPrefix(String prefix, Class<? extends Element> clazz) { - speciesSearchPrefix.put(clazz, prefix); - speciesSearchReversePrefix.put(prefix, clazz); - } - - /** - * Private class that defines internal search result element. Contains - * reference to original result and match score of the result. - * - * @author Piotr Gawron - * - */ - private class SearchResult implements Comparable<SearchResult> { - /** - * Reference to the original object. - */ - private Object obj; - - /** - * Score of the result. - */ - private double score; - - @Override - public int compareTo(SearchResult o) { - if (score == o.getScore()) { - return 0; - } else if (score < o.getScore()) { - return 1; - } else { - return -1; - } - } - - /** - * @return the obj - */ - public Object getObj() { - return obj; - } - - /** - * @param obj - * the obj to set - */ - public void setObj(Object obj) { - this.obj = obj; - } - - /** - * @return the score - */ - public double getScore() { - return score; - } - - /** - * @param score - * the score to set - */ - public void setScore(double score) { - this.score = score; - } - }; - - /** - * Return the list of elements that match the query (sorted by match score) - * limited to the element of class defined by type. - * - * @param model - * model where the search is performed - * @param query - * query string - * @param limit - * maximum number of elements that can be returned by the search - * engine - * @param perfectMatch - * should only perfect match be allowed - * @param type - * class type of the elements that limits the results - * @return list of object found for the query string sorted by the score value - */ - protected List<IHeavyView> searchByIndexedQuery(Model model, String query, int limit, Boolean perfectMatch, Class<? extends Element> type) { - List<IHeavyView> result = new ArrayList<>(); - if (query.startsWith(REACTION_SEARCH_PREFIX)) { - return getReactionById(model, query.replaceFirst(REACTION_SEARCH_PREFIX, "").toLowerCase()); - } else if (query.startsWith(SPECIES_SEARCH_PREFIX)) { - result.addAll(fullAliasViewFactory.createList(model.getAliasesBySpeciesId(query.replaceFirst(SPECIES_SEARCH_PREFIX, "")))); - } else { - Set<Alias> aliases = model.getAliases(); - - List<SearchResult> sortedResults = new ArrayList<SearchService.SearchResult>(); - for (Alias alias : aliases) { - Element element = alias.getElement(); - if (type.isAssignableFrom(element.getClass())) { - List<SearchIndex> indexes = alias.getSearchIndexes(); - if (indexes.size() == 0) { - indexes = searchIndexer.createIndexForAlias(alias); - alias.setSearchIndexes(indexes); - } - for (SearchIndex searchIndex : indexes) { - double score = searchIndexer.match(query, searchIndex); - if (perfectMatch != null && perfectMatch) { - if (query.equals(searchIndex.getValue())) { - SearchResult sResult = new SearchResult(); - sResult.setObj(alias); - sResult.setScore(1); - sortedResults.add(sResult); - break; - } - } else if (score > 0 || (query.equals("") && type != Element.class)) { - SearchResult sResult = new SearchResult(); - sResult.setObj(alias); - sResult.setScore(score); - if (score == 0) { - sResult.setScore(element.getId()); - } - sortedResults.add(sResult); - break; - } - } - } - if (result.size() >= limit) { - break; - - } - } - Collections.sort(sortedResults); - for (SearchResult searchResult : sortedResults) { - if (searchResult.getObj() instanceof Reaction) { - result.add(fullReactionViewFactory.create((Reaction) searchResult.getObj())); - } else if (searchResult.getObj() instanceof Alias) { - result.add(fullAliasViewFactory.create((Alias) searchResult.getObj())); - } else { - throw new InvalidStateException("Unknown class type: " + searchResult.getObj().getClass()); - } - if (result.size() >= limit) { - break; - } - } - } - return result; - } - - /** - * Returns list with the reaction with a given id. If reaction with such id - * doesn't exist then empty list is returned. - * - * @param model - * where the search is performed - * @param reactionId - * id of the reaction - * @return list that contains reaction with given id (or empty list if such - * reaction doesn't exist) - */ - private List<IHeavyView> getReactionById(Model model, String reactionId) { - Set<Reaction> reactions = model.getReactions(); - for (Reaction reaction : reactions) { - if (reaction.getIdReaction().toLowerCase().equals(reactionId)) { - return reactionToResultList(reaction); - } - } - return new ArrayList<>(); - } - - /** - * Transform {@link Reaction} into set of result entries. - * - * @param reaction - * reaction to be transformed - * @return set of result entries for all element of the {@link Reaction} - */ - private List<IHeavyView> reactionToResultList(Reaction reaction) { - List<IHeavyView> result = new ArrayList<>(); - result.add(fullReactionViewFactory.create(reaction)); - for (ReactionNode node : reaction.getReactionNodes()) { - result.add(fullAliasViewFactory.create(node.getAlias())); - } - return result; - } - - @Override - public SearchElementResult searchByCoordinates(CoordinatesSearchParams params) { - SearchElementResult result = new SearchElementResult(""); - boolean nested = params.isNested(); - - List<Object> results = new ArrayList<Object>(); - - Set<Alias> aliases = params.getModel().getAliases(); - Point2D point = new Point2D.Double(params.getX(), params.getY()); - for (Alias alias : aliases) { - if (alias instanceof SpeciesAlias) { - if (alias.contains(point)) { - if (isVisible(alias, params)) { - results.add(alias); - } - } - } - } - double dist = params.getDistance(); - if (results.size() == 0) { - Reaction r = null; - Set<Reaction> reactions = params.getModel().getReactions(); - for (Reaction reaction : reactions) { - double newDist = reaction.getDistanceFromPoint(point); - if (newDist < dist) { - if (isVisible(reaction, params)) { - r = reaction; - dist = reaction.getDistanceFromPoint(point); - } - } - } - if (r != null) { - result.addAll(reactionToResultList(r)); - return result; - } else if (nested) { - for (Alias alias : aliases) { - if (alias instanceof CompartmentAlias) { - if (alias.contains(point)) { - if (isVisible(alias, params)) { - results.add(alias); - } - } - } - } - } - } - - if (results.size() > 1) { - Alias alias = (Alias) results.get(0); - for (Object obj : results) { - if (((Alias) (obj)).getSize() < alias.getSize()) { - alias = (Alias) obj; - } - } - results.clear(); - results.add(alias); - } - if (results.size() == 0) { - return result; - } else { - Object obj = results.get(0); - if (obj instanceof Alias) { - result.add(fullAliasViewFactory.create((Alias) obj)); - return result; - } else if (obj instanceof Reaction) { - result.addAll(reactionToResultList((Reaction) obj)); - return result; - } else { - throw new InvalidStateException("Unknown class type: " + obj.getClass()); - } - } - } - - /** - * Check if reaction is visible for the user. Reaction is visible when at - * least one node of the reaction is visible. - * - * @param reaction - * which reaction is tested - * @param params - * params that determines the client search environment (zoom level, - * type of the layout) - * @return <code>true</code> if reaction is visible for the user, - * <code>false</code> otherwise - */ - private boolean isVisible(Reaction reaction, CoordinatesSearchParams params) { - if (params.getLevel() == null || params.getLayoutIdentfier() == null) { - return true; - } - if (!params.isNested()) { - return true; - } - for (ReactionNode node : reaction.getReactionNodes()) { - if (isVisible(node.getAlias(), params)) { - return true; - } - } - return false; - } - - /** - * Checks if alias is visible for the user. Alias is invisible when the search - * is performed on the hierarchical layout and the alias is hidden by the - * complex or compartment. - * - * @param alias - * alias to be checked for visibility - * @param params - * that determines the client search environment (zoom level, type of - * the layout) - * @return <code>true</code> if alias is visible for the user, - * <code>false</code> otherwise - */ - private boolean isVisible(Alias alias, CoordinatesSearchParams params) { - if (params.getLevel() == null || params.getLayoutIdentfier() == null) { - return true; - } - return (!params.isNested()) || alias.getVisibilityLevel() <= params.getLevel(); - } - - @Override - public SearchElementResult searchByQuery(Model model, String query, int limit, Boolean perfectMatch, String ipAddress) { - query = query.toLowerCase(); - SearchElementResult result = new SearchElementResult(query); - if (query == null) { - throw new InvalidArgumentException("Invalid query: null"); - } - - MiriamData mt = getMiriamTypeForQuery(query); - if (mt != null) { - result.addAll(searchByMiriam(model, mt, limit)); - } else { - String indexQuery = searchIndexer.getQueryStringForIndex(query, speciesSearchReversePrefix.keySet()); - Class<? extends Element> type = searchIndexer.getTypeForQuery(query, speciesSearchReversePrefix); - - List<IHeavyView> partResult = searchByIndexedQuery(model, indexQuery, limit, perfectMatch, type); - - for (ModelSubmodelConnection connection : model.getSubmodelConnections()) { - partResult.addAll(searchByIndexedQuery(connection.getSubmodel().getModel(), indexQuery, limit - partResult.size(), perfectMatch, type)); - if (partResult.size() >= limit) { - break; - } - } - - result.addAll(partResult); - } - if (model.getProject() != null && ipAddress != null) { - searchHistoryService.addQuery(query, SearchType.GENERAL, ipAddress, model.getProject().getProjectId()); - } - return result; - } - - /** - * Returns elements that are annotated with the given miriam data. - * - * @param model - * model where elements are looked for - * @param md - * miriam annotation to identifiy interesting elements - * @param limit - * max number of elements to find - * @return elements that are annotated with the given miriam data - */ - private List<IHeavyView> searchByMiriam(Model model, MiriamData md, int limit) { - List<IHeavyView> result = new ArrayList<>(); - for (AnnotatedObject obj : model.getElementsByAnnotation(md)) { - if (result.size() >= limit) { - break; - } - if (obj instanceof Element) { - result.addAll(fullAliasViewFactory.createList(model.getAliasesForElement((Element) obj))); - } else if (obj instanceof Reaction) { - result.addAll(reactionToResultList((Reaction) obj)); - } else { - throw new InvalidClassException("Unknown class: " + obj.getClass()); - } - } - return result; - } - - /** - * Tries to transform query into {@link MiriamData}. - * - * @param string - * query to transform - * @return {@link MiriamData} that described query or null if query cannot be - * converted - */ - protected MiriamData getMiriamTypeForQuery(String string) { - for (MiriamType mt : MiriamType.values()) { - if (string.startsWith(mt.toString().toLowerCase() + ":")) { - return new MiriamData(mt, string.substring(mt.toString().length() + 1)); - } - } - return null; - } - - @Override - public List<Object> getClosestElements(Model model, Point2D point, int numberOfElements) { - List<Object> result = new ArrayList<>(); - - // probably this could be improved algorithmitically, right now all objects - // are sorted by distance, and numberOfElements closest are chosen as a list - // of results - List<DistanceToObject> tmpList = new ArrayList<DistanceToObject>(); - for (Reaction reaction : model.getReactions()) { - tmpList.add(new DistanceToObject(reaction, point)); - } - for (Alias alias : model.getAliases()) { - if (alias instanceof SpeciesAlias) { - tmpList.add(new DistanceToObject(alias, point)); - } - } - Collections.sort(tmpList); - int size = Math.min(tmpList.size(), numberOfElements); - for (int i = 0; i < size; i++) { - result.add(tmpList.get(i).getReference()); - } - return result; - } - - /** - * This class represents distance between object and some point. It's designed - * to help sort objects by their distance to some point. It It contains two - * fields: object reference and distance. - * - * @author Piotr Gawron - * - */ - private class DistanceToObject implements Comparable<DistanceToObject> { - /** - * Reference to the object. - */ - private Object reference; - /** - * Distance between the object and some point. - */ - private double distance; - - /** - * Constructor for reaction objects. - * - * @param reaction - * reaction reference to store - * @param point - * point from which the distance will be computed - */ - DistanceToObject(Reaction reaction, Point2D point) { - reference = reaction; - distance = reaction.getDistanceFromPoint(point); - } - - /** - * Constructor for alias objects. - * - * @param alias - * alias reference to store - * @param point - * point from which the distance will be computed - */ - DistanceToObject(Alias alias, Point2D point) { - reference = alias; - distance = alias.getDistanceFromPoint(point); - - } - - @Override - public int compareTo(DistanceToObject arg0) { - if (arg0.getDistance() < getDistance()) { - return 1; - } else if (arg0.getDistance() > getDistance()) { - return -1; - } else { - return 0; - } - } - - /** - * @return the reference - * @see #reference - */ - public Object getReference() { - return reference; - } - - /** - * @return the distance - * @see #distance - */ - public double getDistance() { - return distance; - } - - } - - /** - * Object containing autocomplete lists for models. For every model the map - * between String and List is stored. The key in this map is incomplete typed - * word, and value list contains suggestions that should appear for this word. - */ - private Map<Model, Map<String, List<String>>> autoCompleteLists = new HashMap<Model, Map<String, List<String>>>(); - - @Override - public List<String> getAutocompleteList(Model model, String query) { - Map<String, List<String>> autoCompleteMap = autoCompleteLists.get(model); - if (autoCompleteMap == null) { - autoCompleteMap = createAutocompleteMap(model); - autoCompleteLists.put(model, autoCompleteMap); - } - List<String> result = autoCompleteMap.get(query.toLowerCase().trim()); - if (result == null) { - result = new ArrayList<String>(); - } - return result; - } - - /** - * Creates autocomplete map for a model. The key in this map is incomplete - * typed word, and value list contains suggestions that should appear for this - * word. - * - * @param model - * model for which the autocomplete map is created - * @return autocomplete map for a model. The key in this map is incomplete - * typed word, and value list contains suggestions that should appear - * for this word. - */ - private Map<String, List<String>> createAutocompleteMap(Model model) { - Map<String, List<String>> result = new HashMap<String, List<String>>(); - - Set<String> possibilities = new HashSet<String>(); - for (Alias alias : model.getAliases()) { - if (alias instanceof SpeciesAlias) { - possibilities.addAll(getSearchPossibilitiesForAlias(alias)); - } - } - for (ModelSubmodelConnection connection : model.getSubmodelConnections()) { - for (Alias alias : connection.getSubmodel().getModel().getAliases()) { - if (alias instanceof SpeciesAlias) { - possibilities.addAll(getSearchPossibilitiesForAlias(alias)); - } - } - } - String[] sortedPossibilites = new String[possibilities.size()]; - int index = 0; - for (String string : possibilities) { - sortedPossibilites[index++] = string; - } - Arrays.sort(sortedPossibilites); - for (int i = 0; i < index; i++) { - String mainString = sortedPossibilites[i]; - for (int j = 0; j < mainString.length(); j++) { - String substring = mainString.substring(0, j + 1); - if (result.get(substring) != null) { - continue; - } - - List<String> list = new ArrayList<String>(); - for (int k = 0; k < Configuration.getAutocompleteSize(); k++) { - if (k + i >= sortedPossibilites.length) { - break; - } else if (sortedPossibilites[k + i].startsWith(substring)) { - list.add(sortedPossibilites[k + i]); - } - } - - // by default, the selection in autocomplete is set on the first - // element, so if the first element is not equals to the query then add - // the element - if (!list.get(0).equalsIgnoreCase(substring)) { - list.add(0, substring); - } - - result.put(substring, list); - } - } - return result; - } - - /** - * Returns the list of all human readable search possibilities for alias. - * - * @param alias - * object for which we look for a list of searchable strings - * @return the list of all human readable search possibilities for alias - */ - private List<String> getSearchPossibilitiesForAlias(Alias alias) { - List<String> result = new ArrayList<String>(); - Element element = alias.getElement(); - result.add(element.getName().trim().toLowerCase().replace(",", "")); - for (String string : element.getSynonyms()) { - result.add(string.trim().toLowerCase().replace(",", "")); - } - for (String string : element.getFormerSymbols()) { - result.add(string.trim().toLowerCase().replace(",", "")); - } - String name = element.getFullName(); - if (name != null) { - result.add(name.trim().toLowerCase().replace(",", "")); - } - return result; - } - - /** - * @return the modelDao - */ - public ModelDao getModelDao() { - return modelDao; - } - - /** - * @param modelDao - * the modelDao to set - */ - public void setModelDao(ModelDao modelDao) { - this.modelDao = modelDao; - } - - /** - * @return the searchHistoryService - */ - public ISearchHistoryService getSearchHistoryService() { - return searchHistoryService; - } - - /** - * @param searchHistoryService - * the searchHistoryService to set - */ - public void setSearchHistoryService(ISearchHistoryService searchHistoryService) { - this.searchHistoryService = searchHistoryService; - } - - @Override - public void assignIcons(SearchElementResult results, int iconSet) { - int iconId = 0; - for (IHeavyView result : results.getElements()) { - if (result instanceof FullAliasView) { - ((FullAliasView) result).setIcon(IconManager.getInstance().getIconForIndex(iconId++, IconType.SEARCH, iconSet)); - } else if (result instanceof FullReactionView) { - continue; - } else { - throw new InvalidArgumentException("Unknown element of the result list: " + result.getClass()); - } - } - } - +package lcsb.mapviewer.services.impl; + +import java.awt.geom.Point2D; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.log4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +import lcsb.mapviewer.common.Configuration; +import lcsb.mapviewer.common.exception.InvalidArgumentException; +import lcsb.mapviewer.common.exception.InvalidClassException; +import lcsb.mapviewer.common.exception.InvalidStateException; +import lcsb.mapviewer.model.map.AnnotatedObject; +import lcsb.mapviewer.model.map.Element; +import lcsb.mapviewer.model.map.MiriamData; +import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.layout.alias.Alias; +import lcsb.mapviewer.model.map.layout.alias.CompartmentAlias; +import lcsb.mapviewer.model.map.layout.alias.SearchIndex; +import lcsb.mapviewer.model.map.layout.alias.SpeciesAlias; +import lcsb.mapviewer.model.map.model.Model; +import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; +import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.ReactionNode; +import lcsb.mapviewer.model.map.species.ComplexSpecies; +import lcsb.mapviewer.model.map.species.Degraded; +import lcsb.mapviewer.model.map.species.Drug; +import lcsb.mapviewer.model.map.species.Gene; +import lcsb.mapviewer.model.map.species.Ion; +import lcsb.mapviewer.model.map.species.Phenotype; +import lcsb.mapviewer.model.map.species.Protein; +import lcsb.mapviewer.model.map.species.Rna; +import lcsb.mapviewer.model.map.species.SimpleMolecule; +import lcsb.mapviewer.model.map.species.Unknown; +import lcsb.mapviewer.model.map.statistics.SearchType; +import lcsb.mapviewer.persist.dao.map.ModelDao; +import lcsb.mapviewer.services.interfaces.ISearchHistoryService; +import lcsb.mapviewer.services.interfaces.ISearchService; +import lcsb.mapviewer.services.overlay.IconManager; +import lcsb.mapviewer.services.overlay.IconType; +import lcsb.mapviewer.services.search.IHeavyView; +import lcsb.mapviewer.services.search.data.FullAliasView; +import lcsb.mapviewer.services.search.data.FullAliasViewFactory; +import lcsb.mapviewer.services.search.data.FullReactionView; +import lcsb.mapviewer.services.search.data.FullReactionViewFactory; +import lcsb.mapviewer.services.search.data.SearchElementResult; +import lcsb.mapviewer.services.utils.SearchIndexer; + +/** + * This is implementation of the service that returns information about species, + * paths etc in the model. + * + * + * @author Piotr Gawron + * + */ +@Transactional(value = "txManager") +public class SearchService implements ISearchService { + + /** + * Prefix used in search by name interface to limit results only to species. + */ + public static final String SPECIES_SEARCH_PREFIX = "species"; + + /** + * Prefix used in search by name interface to limit results only to reactions. + */ + public static final String REACTION_SEARCH_PREFIX = "reaction"; + + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = Logger.getLogger(SearchService.class.getName()); + + /** + * Data access object for models. + */ + @Autowired + private ModelDao modelDao; + + /** + * Service used for managing search history. + */ + @Autowired + private ISearchHistoryService searchHistoryService; + + /** + * Factory object used to create {@link FullAliasView} objects. + */ + @Autowired + private FullAliasViewFactory fullAliasViewFactory; + + /** + * Factory object used to create {@link FullReactionView} objects. + */ + @Autowired + private FullReactionViewFactory fullReactionViewFactory; + + /** + * Object used for indexing elements on the map. + */ + private SearchIndexer searchIndexer = new SearchIndexer(); + + /** + * This object maps class of elements on the map into short string prefixes + * used in the search query. For instance elements of the + * {@link ComplexSpecies} class could be searched with the prefix "complex" + * (example query: "complex:alpha subcomplex"). + */ + private Map<Class<? extends Element>, String> speciesSearchPrefix = new HashMap<Class<? extends Element>, String>(); + + /** + * This object maps short string prefixes into class of elements on the map + * that will be searched. For instance prefix "complex" might refer to + * {@link ComplexSpecies} class and and example query would look like: + * "complex:alpha subcomplex". + */ + private Map<String, Class<? extends Element>> speciesSearchReversePrefix = new HashMap<String, Class<? extends Element>>(); + + /** + * Default constructor that set list of prefixes used in the search queries. + */ + public SearchService() { + addSearchPrefix("complex", ComplexSpecies.class); + addSearchPrefix("degrded", Degraded.class); + addSearchPrefix("drug", Drug.class); + addSearchPrefix("gene", Gene.class); + addSearchPrefix("ion", Ion.class); + addSearchPrefix("phenotype", Phenotype.class); + addSearchPrefix("protein", Protein.class); + addSearchPrefix("rna", Rna.class); + addSearchPrefix("molecule", SimpleMolecule.class); + addSearchPrefix("unknown", Unknown.class); + } + + /** + * Adds search prefix for an element class. + * + * @param prefix + * string prefix used in search queries + * @param clazz + * class for which this prefix stands + */ + private void addSearchPrefix(String prefix, Class<? extends Element> clazz) { + speciesSearchPrefix.put(clazz, prefix); + speciesSearchReversePrefix.put(prefix, clazz); + } + + /** + * Private class that defines internal search result element. Contains + * reference to original result and match score of the result. + * + * @author Piotr Gawron + * + */ + private class SearchResult implements Comparable<SearchResult> { + /** + * Reference to the original object. + */ + private Object obj; + + /** + * Score of the result. + */ + private double score; + + @Override + public int compareTo(SearchResult o) { + if (score == o.getScore()) { + return 0; + } else if (score < o.getScore()) { + return 1; + } else { + return -1; + } + } + + /** + * @return the obj + */ + public Object getObj() { + return obj; + } + + /** + * @param obj + * the obj to set + */ + public void setObj(Object obj) { + this.obj = obj; + } + + /** + * @return the score + */ + public double getScore() { + return score; + } + + /** + * @param score + * the score to set + */ + public void setScore(double score) { + this.score = score; + } + }; + + /** + * Return the list of elements that match the query (sorted by match score) + * limited to the element of class defined by type. + * + * @param model + * model where the search is performed + * @param query + * query string + * @param limit + * maximum number of elements that can be returned by the search + * engine + * @param perfectMatch + * should only perfect match be allowed + * @param type + * class type of the elements that limits the results + * @return list of object found for the query string sorted by the score value + */ + protected List<IHeavyView> searchByIndexedQuery(Model model, String query, int limit, Boolean perfectMatch, Class<? extends Element> type) { + List<IHeavyView> result = new ArrayList<>(); + if (query.startsWith(REACTION_SEARCH_PREFIX)) { + return getReactionById(model, query.replaceFirst(REACTION_SEARCH_PREFIX, "").toLowerCase()); + } else if (query.startsWith(SPECIES_SEARCH_PREFIX)) { + result.addAll(fullAliasViewFactory.createList(model.getAliasesBySpeciesId(query.replaceFirst(SPECIES_SEARCH_PREFIX, "")))); + } else { + Set<Alias> aliases = model.getAliases(); + + List<SearchResult> sortedResults = new ArrayList<SearchService.SearchResult>(); + for (Alias alias : aliases) { + Element element = alias.getElement(); + if (type.isAssignableFrom(element.getClass())) { + List<SearchIndex> indexes = alias.getSearchIndexes(); + if (indexes.size() == 0) { + indexes = searchIndexer.createIndexForAlias(alias); + alias.setSearchIndexes(indexes); + } + for (SearchIndex searchIndex : indexes) { + double score = searchIndexer.match(query, searchIndex); + if (perfectMatch != null && perfectMatch) { + if (query.equals(searchIndex.getValue())) { + SearchResult sResult = new SearchResult(); + sResult.setObj(alias); + sResult.setScore(1); + sortedResults.add(sResult); + break; + } + } else if (score > 0 || (query.equals("") && type != Element.class)) { + SearchResult sResult = new SearchResult(); + sResult.setObj(alias); + sResult.setScore(score); + if (score == 0) { + sResult.setScore(element.getId()); + } + sortedResults.add(sResult); + break; + } + } + } + if (result.size() >= limit) { + break; + + } + } + Collections.sort(sortedResults); + for (SearchResult searchResult : sortedResults) { + if (searchResult.getObj() instanceof Reaction) { + result.add(fullReactionViewFactory.create((Reaction) searchResult.getObj())); + } else if (searchResult.getObj() instanceof Alias) { + result.add(fullAliasViewFactory.create((Alias) searchResult.getObj())); + } else { + throw new InvalidStateException("Unknown class type: " + searchResult.getObj().getClass()); + } + if (result.size() >= limit) { + break; + } + } + } + return result; + } + + /** + * Returns list with the reaction with a given id. If reaction with such id + * doesn't exist then empty list is returned. + * + * @param model + * where the search is performed + * @param reactionId + * id of the reaction + * @return list that contains reaction with given id (or empty list if such + * reaction doesn't exist) + */ + private List<IHeavyView> getReactionById(Model model, String reactionId) { + Set<Reaction> reactions = model.getReactions(); + for (Reaction reaction : reactions) { + if (reaction.getIdReaction().toLowerCase().equals(reactionId)) { + return reactionToResultList(reaction); + } + } + return new ArrayList<>(); + } + + /** + * Transform {@link Reaction} into set of result entries. + * + * @param reaction + * reaction to be transformed + * @return set of result entries for all element of the {@link Reaction} + */ + private List<IHeavyView> reactionToResultList(Reaction reaction) { + List<IHeavyView> result = new ArrayList<>(); + result.add(fullReactionViewFactory.create(reaction)); + for (ReactionNode node : reaction.getReactionNodes()) { + result.add(fullAliasViewFactory.create(node.getAlias())); + } + return result; + } + + @Override + public SearchElementResult searchByCoordinates(CoordinatesSearchParams params) { + SearchElementResult result = new SearchElementResult(""); + boolean nested = params.isNested(); + + List<Object> results = new ArrayList<Object>(); + + Set<Alias> aliases = params.getModel().getAliases(); + Point2D point = new Point2D.Double(params.getX(), params.getY()); + for (Alias alias : aliases) { + if (alias instanceof SpeciesAlias) { + if (alias.contains(point)) { + if (isVisible(alias, params)) { + results.add(alias); + } + } + } + } + double dist = params.getDistance(); + if (results.size() == 0) { + Reaction r = null; + Set<Reaction> reactions = params.getModel().getReactions(); + for (Reaction reaction : reactions) { + double newDist = reaction.getDistanceFromPoint(point); + if (newDist < dist) { + if (isVisible(reaction, params)) { + r = reaction; + dist = reaction.getDistanceFromPoint(point); + } + } + } + if (r != null) { + result.addAll(reactionToResultList(r)); + return result; + } else if (nested) { + for (Alias alias : aliases) { + if (alias instanceof CompartmentAlias) { + if (alias.contains(point)) { + if (isVisible(alias, params)) { + results.add(alias); + } + } + } + } + } + } + + if (results.size() > 1) { + Alias alias = (Alias) results.get(0); + for (Object obj : results) { + if (((Alias) (obj)).getSize() < alias.getSize()) { + alias = (Alias) obj; + } + } + results.clear(); + results.add(alias); + } + if (results.size() == 0) { + return result; + } else { + Object obj = results.get(0); + if (obj instanceof Alias) { + result.add(fullAliasViewFactory.create((Alias) obj)); + return result; + } else if (obj instanceof Reaction) { + result.addAll(reactionToResultList((Reaction) obj)); + return result; + } else { + throw new InvalidStateException("Unknown class type: " + obj.getClass()); + } + } + } + + /** + * Check if reaction is visible for the user. Reaction is visible when at + * least one node of the reaction is visible. + * + * @param reaction + * which reaction is tested + * @param params + * params that determines the client search environment (zoom level, + * type of the layout) + * @return <code>true</code> if reaction is visible for the user, + * <code>false</code> otherwise + */ + private boolean isVisible(Reaction reaction, CoordinatesSearchParams params) { + if (params.getLevel() == null || params.getLayoutIdentfier() == null) { + return true; + } + if (!params.isNested()) { + return true; + } + for (ReactionNode node : reaction.getReactionNodes()) { + if (isVisible(node.getAlias(), params)) { + return true; + } + } + return false; + } + + /** + * Checks if alias is visible for the user. Alias is invisible when the search + * is performed on the hierarchical layout and the alias is hidden by the + * complex or compartment. + * + * @param alias + * alias to be checked for visibility + * @param params + * that determines the client search environment (zoom level, type of + * the layout) + * @return <code>true</code> if alias is visible for the user, + * <code>false</code> otherwise + */ + private boolean isVisible(Alias alias, CoordinatesSearchParams params) { + if (params.getLevel() == null || params.getLayoutIdentfier() == null) { + return true; + } + return (!params.isNested()) || alias.getVisibilityLevel() <= params.getLevel(); + } + + @Override + public SearchElementResult searchByQuery(Model model, String query, int limit, Boolean perfectMatch, String ipAddress) { + query = query.toLowerCase(); + SearchElementResult result = new SearchElementResult(query); + if (query == null) { + throw new InvalidArgumentException("Invalid query: null"); + } + + MiriamData mt = getMiriamTypeForQuery(query); + if (mt != null) { + result.addAll(searchByMiriam(model, mt, limit)); + } else { + String indexQuery = searchIndexer.getQueryStringForIndex(query, speciesSearchReversePrefix.keySet()); + Class<? extends Element> type = searchIndexer.getTypeForQuery(query, speciesSearchReversePrefix); + + List<IHeavyView> partResult = searchByIndexedQuery(model, indexQuery, limit, perfectMatch, type); + + for (ModelSubmodelConnection connection : model.getSubmodelConnections()) { + partResult.addAll(searchByIndexedQuery(connection.getSubmodel().getModel(), indexQuery, limit - partResult.size(), perfectMatch, type)); + if (partResult.size() >= limit) { + break; + } + } + + result.addAll(partResult); + } + if (model.getProject() != null && ipAddress != null) { + searchHistoryService.addQuery(query, SearchType.GENERAL, ipAddress, model.getProject().getProjectId()); + } + return result; + } + + /** + * Returns elements that are annotated with the given miriam data. + * + * @param model + * model where elements are looked for + * @param md + * miriam annotation to identifiy interesting elements + * @param limit + * max number of elements to find + * @return elements that are annotated with the given miriam data + */ + private List<IHeavyView> searchByMiriam(Model model, MiriamData md, int limit) { + List<IHeavyView> result = new ArrayList<>(); + for (AnnotatedObject obj : model.getElementsByAnnotation(md)) { + if (result.size() >= limit) { + break; + } + if (obj instanceof Element) { + result.addAll(fullAliasViewFactory.createList(model.getAliasesForElement((Element) obj))); + } else if (obj instanceof Reaction) { + result.addAll(reactionToResultList((Reaction) obj)); + } else if (obj instanceof Alias) { + result.add(fullAliasViewFactory.create((Alias) obj)); + } else { + throw new InvalidClassException("Unknown class: " + obj.getClass()); + } + } + return result; + } + + /** + * Tries to transform query into {@link MiriamData}. + * + * @param string + * query to transform + * @return {@link MiriamData} that described query or null if query cannot be + * converted + */ + protected MiriamData getMiriamTypeForQuery(String string) { + for (MiriamType mt : MiriamType.values()) { + if (string.startsWith(mt.toString().toLowerCase() + ":")) { + return new MiriamData(mt, string.substring(mt.toString().length() + 1)); + } + } + return null; + } + + @Override + public List<Object> getClosestElements(Model model, Point2D point, int numberOfElements) { + List<Object> result = new ArrayList<>(); + + // probably this could be improved algorithmitically, right now all objects + // are sorted by distance, and numberOfElements closest are chosen as a list + // of results + List<DistanceToObject> tmpList = new ArrayList<DistanceToObject>(); + for (Reaction reaction : model.getReactions()) { + tmpList.add(new DistanceToObject(reaction, point)); + } + for (Alias alias : model.getAliases()) { + if (alias instanceof SpeciesAlias) { + tmpList.add(new DistanceToObject(alias, point)); + } + } + Collections.sort(tmpList); + int size = Math.min(tmpList.size(), numberOfElements); + for (int i = 0; i < size; i++) { + result.add(tmpList.get(i).getReference()); + } + return result; + } + + /** + * This class represents distance between object and some point. It's designed + * to help sort objects by their distance to some point. It It contains two + * fields: object reference and distance. + * + * @author Piotr Gawron + * + */ + private class DistanceToObject implements Comparable<DistanceToObject> { + /** + * Reference to the object. + */ + private Object reference; + /** + * Distance between the object and some point. + */ + private double distance; + + /** + * Constructor for reaction objects. + * + * @param reaction + * reaction reference to store + * @param point + * point from which the distance will be computed + */ + DistanceToObject(Reaction reaction, Point2D point) { + reference = reaction; + distance = reaction.getDistanceFromPoint(point); + } + + /** + * Constructor for alias objects. + * + * @param alias + * alias reference to store + * @param point + * point from which the distance will be computed + */ + DistanceToObject(Alias alias, Point2D point) { + reference = alias; + distance = alias.getDistanceFromPoint(point); + + } + + @Override + public int compareTo(DistanceToObject arg0) { + if (arg0.getDistance() < getDistance()) { + return 1; + } else if (arg0.getDistance() > getDistance()) { + return -1; + } else { + return 0; + } + } + + /** + * @return the reference + * @see #reference + */ + public Object getReference() { + return reference; + } + + /** + * @return the distance + * @see #distance + */ + public double getDistance() { + return distance; + } + + } + + /** + * Object containing autocomplete lists for models. For every model the map + * between String and List is stored. The key in this map is incomplete typed + * word, and value list contains suggestions that should appear for this word. + */ + private Map<Model, Map<String, List<String>>> autoCompleteLists = new HashMap<Model, Map<String, List<String>>>(); + + @Override + public List<String> getAutocompleteList(Model model, String query) { + Map<String, List<String>> autoCompleteMap = autoCompleteLists.get(model); + if (autoCompleteMap == null) { + autoCompleteMap = createAutocompleteMap(model); + autoCompleteLists.put(model, autoCompleteMap); + } + List<String> result = autoCompleteMap.get(query.toLowerCase().trim()); + if (result == null) { + result = new ArrayList<String>(); + } + return result; + } + + /** + * Creates autocomplete map for a model. The key in this map is incomplete + * typed word, and value list contains suggestions that should appear for this + * word. + * + * @param model + * model for which the autocomplete map is created + * @return autocomplete map for a model. The key in this map is incomplete + * typed word, and value list contains suggestions that should appear + * for this word. + */ + private Map<String, List<String>> createAutocompleteMap(Model model) { + Map<String, List<String>> result = new HashMap<String, List<String>>(); + + Set<String> possibilities = new HashSet<String>(); + for (Alias alias : model.getAliases()) { + if (alias instanceof SpeciesAlias) { + possibilities.addAll(getSearchPossibilitiesForAlias(alias)); + } + } + for (ModelSubmodelConnection connection : model.getSubmodelConnections()) { + for (Alias alias : connection.getSubmodel().getModel().getAliases()) { + if (alias instanceof SpeciesAlias) { + possibilities.addAll(getSearchPossibilitiesForAlias(alias)); + } + } + } + String[] sortedPossibilites = new String[possibilities.size()]; + int index = 0; + for (String string : possibilities) { + sortedPossibilites[index++] = string; + } + Arrays.sort(sortedPossibilites); + for (int i = 0; i < index; i++) { + String mainString = sortedPossibilites[i]; + for (int j = 0; j < mainString.length(); j++) { + String substring = mainString.substring(0, j + 1); + if (result.get(substring) != null) { + continue; + } + + List<String> list = new ArrayList<String>(); + for (int k = 0; k < Configuration.getAutocompleteSize(); k++) { + if (k + i >= sortedPossibilites.length) { + break; + } else if (sortedPossibilites[k + i].startsWith(substring)) { + list.add(sortedPossibilites[k + i]); + } + } + + // by default, the selection in autocomplete is set on the first + // element, so if the first element is not equals to the query then add + // the element + if (!list.get(0).equalsIgnoreCase(substring)) { + list.add(0, substring); + } + + result.put(substring, list); + } + } + return result; + } + + /** + * Returns the list of all human readable search possibilities for alias. + * + * @param alias + * object for which we look for a list of searchable strings + * @return the list of all human readable search possibilities for alias + */ + private List<String> getSearchPossibilitiesForAlias(Alias alias) { + List<String> result = new ArrayList<String>(); + Element element = alias.getElement(); + result.add(element.getName().trim().toLowerCase().replace(",", "")); + for (String string : element.getSynonyms()) { + result.add(string.trim().toLowerCase().replace(",", "")); + } + for (String string : element.getFormerSymbols()) { + result.add(string.trim().toLowerCase().replace(",", "")); + } + String name = element.getFullName(); + if (name != null) { + result.add(name.trim().toLowerCase().replace(",", "")); + } + return result; + } + + /** + * @return the modelDao + */ + public ModelDao getModelDao() { + return modelDao; + } + + /** + * @param modelDao + * the modelDao to set + */ + public void setModelDao(ModelDao modelDao) { + this.modelDao = modelDao; + } + + /** + * @return the searchHistoryService + */ + public ISearchHistoryService getSearchHistoryService() { + return searchHistoryService; + } + + /** + * @param searchHistoryService + * the searchHistoryService to set + */ + public void setSearchHistoryService(ISearchHistoryService searchHistoryService) { + this.searchHistoryService = searchHistoryService; + } + + @Override + public void assignIcons(SearchElementResult results, int iconSet) { + int iconId = 0; + for (IHeavyView result : results.getElements()) { + if (result instanceof FullAliasView) { + ((FullAliasView) result).setIcon(IconManager.getInstance().getIconForIndex(iconId++, IconType.SEARCH, iconSet)); + } else if (result instanceof FullReactionView) { + continue; + } else { + throw new InvalidArgumentException("Unknown element of the result list: " + result.getClass()); + } + } + } + } \ No newline at end of file diff --git a/service/src/main/java/lcsb/mapviewer/services/search/db/TargetViewFactory.java b/service/src/main/java/lcsb/mapviewer/services/search/db/TargetViewFactory.java index 617961809d..be65cf159e 100644 --- a/service/src/main/java/lcsb/mapviewer/services/search/db/TargetViewFactory.java +++ b/service/src/main/java/lcsb/mapviewer/services/search/db/TargetViewFactory.java @@ -88,12 +88,12 @@ public class TargetViewFactory extends AbstractViewFactory<Target, TargetView> { geneRow.setAnnotation(annotationViewFactory.create(md)); if (model != null) { Set<AnnotatedObject> list = new HashSet<>(); - list.addAll(model.getSpeciesByName(md.getResource())); + list.addAll(model.getAliasByName(md.getResource())); list.addAll(model.getElementsByAnnotation(md)); int countInTopModel = list.size(); for (ModelSubmodelConnection submodel : model.getSubmodelConnections()) { - list.addAll(submodel.getSubmodel().getModel().getSpeciesByName(md.getResource())); + list.addAll(submodel.getSubmodel().getModel().getAliasByName(md.getResource())); list.addAll(submodel.getSubmodel().getModel().getElementsByAnnotation(md)); } int counter = list.size(); diff --git a/service/src/main/java/lcsb/mapviewer/services/view/PubmedAnnotatedElementsView.java b/service/src/main/java/lcsb/mapviewer/services/view/PubmedAnnotatedElementsView.java index eb0cdf8ac2..53198e9f73 100644 --- a/service/src/main/java/lcsb/mapviewer/services/view/PubmedAnnotatedElementsView.java +++ b/service/src/main/java/lcsb/mapviewer/services/view/PubmedAnnotatedElementsView.java @@ -1,105 +1,108 @@ -package lcsb.mapviewer.services.view; - -import java.util.ArrayList; -import java.util.List; - -import lcsb.mapviewer.annotation.data.Article; -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.model.map.AnnotatedObject; -import lcsb.mapviewer.model.map.Element; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.services.impl.SearchService; - -/** - * View object for pubmed article for a given model. It contains information - * about article and list of elements annotated by this - * {@link lcsb.mapviewer.model.map.MiriamType#PUBMED article}. - * - * @author Piotr Gawron - * - */ -public class PubmedAnnotatedElementsView extends AbstractView<MiriamData> { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Article for which this pubmed summary is created. - */ - private Article article; - - /** - * List of elements that are annotated the publication. {@link Pair#left} - * refers to human readable name and {@link Pair#right} is search string that - * can be used to access element on the model. - */ - private List<Pair<String, String>> elements = new ArrayList<>(); - - /** - * Default constructor. - * - * @param element - * {@link MiriamData} that represents publication for this object. - * - * @see #article - */ - public PubmedAnnotatedElementsView(MiriamData element) { - super(element); - } - - /** - * @return the article - * @see #article - */ - public Article getArticle() { - return article; - } - - /** - * @param article - * the article to set - * @see #article - */ - public void setArticle(Article article) { - this.article = article; - } - - /** - * @return the elements - * @see #elements - */ - public List<Pair<String, String>> getElements() { - return elements; - } - - /** - * @param elements - * the elements to set - * @see #elements - */ - public void setElements(List<Pair<String, String>> elements) { - this.elements = elements; - } - - /** - * Adds element annotratd by {@link #article}. - * - * @param annotatedObject - * object to add - */ - public void addElement(AnnotatedObject annotatedObject) { - if (annotatedObject instanceof Element) { - elements.add(new Pair<String, String>(annotatedObject.getName(), SearchService.SPECIES_SEARCH_PREFIX + ":" + annotatedObject.getElementId())); - } else if (annotatedObject instanceof Reaction) { - elements.add(new Pair<String, String>(SearchService.REACTION_SEARCH_PREFIX + ":" + annotatedObject.getElementId(), SearchService.REACTION_SEARCH_PREFIX - + ":" + annotatedObject.getElementId())); - } else { - throw new InvalidStateException("Unknown subtype of " + AnnotatedObject.class.getName() + ": " + annotatedObject.getClass().getName()); - } - - } -} +package lcsb.mapviewer.services.view; + +import java.util.ArrayList; +import java.util.List; + +import lcsb.mapviewer.annotation.data.Article; +import lcsb.mapviewer.common.Pair; +import lcsb.mapviewer.common.exception.InvalidStateException; +import lcsb.mapviewer.model.map.AnnotatedObject; +import lcsb.mapviewer.model.map.Element; +import lcsb.mapviewer.model.map.MiriamData; +import lcsb.mapviewer.model.map.layout.alias.Alias; +import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.services.impl.SearchService; + +/** + * View object for pubmed article for a given model. It contains information + * about article and list of elements annotated by this + * {@link lcsb.mapviewer.model.map.MiriamType#PUBMED article}. + * + * @author Piotr Gawron + * + */ +public class PubmedAnnotatedElementsView extends AbstractView<MiriamData> { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Article for which this pubmed summary is created. + */ + private Article article; + + /** + * List of elements that are annotated the publication. {@link Pair#left} + * refers to human readable name and {@link Pair#right} is search string that + * can be used to access element on the model. + */ + private List<Pair<String, String>> elements = new ArrayList<>(); + + /** + * Default constructor. + * + * @param element + * {@link MiriamData} that represents publication for this object. + * + * @see #article + */ + public PubmedAnnotatedElementsView(MiriamData element) { + super(element); + } + + /** + * @return the article + * @see #article + */ + public Article getArticle() { + return article; + } + + /** + * @param article + * the article to set + * @see #article + */ + public void setArticle(Article article) { + this.article = article; + } + + /** + * @return the elements + * @see #elements + */ + public List<Pair<String, String>> getElements() { + return elements; + } + + /** + * @param elements + * the elements to set + * @see #elements + */ + public void setElements(List<Pair<String, String>> elements) { + this.elements = elements; + } + + /** + * Adds element annotratd by {@link #article}. + * + * @param annotatedObject + * object to add + */ + public void addElement(AnnotatedObject annotatedObject) { + if (annotatedObject instanceof Alias) { + elements.add(new Pair<String, String>(annotatedObject.getName(), SearchService.SPECIES_SEARCH_PREFIX + ":" + annotatedObject.getElementId())); + } else if (annotatedObject instanceof Reaction) { + elements.add( + new Pair<String, String>( + SearchService.REACTION_SEARCH_PREFIX + ":" + annotatedObject.getElementId(), + SearchService.REACTION_SEARCH_PREFIX + ":" + annotatedObject.getElementId())); + } else { + throw new InvalidStateException("Unknown subtype of " + AnnotatedObject.class.getName() + ": " + annotatedObject.getClass().getName()); + } + + } +} -- GitLab