From 40e5fa55754ba2a55ca009ded817707f9a7ba25c Mon Sep 17 00:00:00 2001 From: Piotr Gawron <p.gawron@atcomp.pl> Date: Fri, 14 Mar 2025 10:09:14 +0100 Subject: [PATCH] export mapping file with connections between submaps --- .../copypaste/CopyPasteAbstractAction.java | 45 +- .../cdplugin/copypaste/PasteAction.java | 22 +- .../services/MiriamConnectorImpl.java | 2 +- converter-CellDesigner/pom.xml | 152 ++--- .../celldesigner/CellDesignerXmlParser.java | 10 +- .../model/celldesigner/CommonXmlParser.java | 78 +-- .../model/celldesigner/LayerXmlParser.java | 2 +- .../alias/AliasCollectionXmlParser.java | 82 ++- .../compartment/CompartmentXmlParser.java | 48 +- .../reaction/ReactionFromXml.java | 131 ++-- .../celldesigner/reaction/ReactionToXml.java | 335 +++++----- .../species/AbstractElementXmlParser.java | 76 +-- .../species/SpeciesCollectionXmlParser.java | 7 +- .../species/SpeciesSbmlParser.java | 9 +- .../CellDesignerXmlParserTest.java | 21 +- .../CopyCommandForCellDesignerFilesTest.java | 116 ++++ ...eHierarchyCommandForProblematicCDTest.java | 300 +++++++++ .../model/celldesigner/ProjectExportTest.java | 29 +- ...bModelCommandForCellDesignerFilesTest.java | 61 +- .../model/sbgnml/SbgnmlXmlExporter.java | 2 +- .../model/sbgnml/SbgnmlXmlParser.java | 4 +- .../model/sbgnml/parser/ElementParser.java | 2 +- .../model/sbgnml/parser/NotesConverter.java | 2 +- .../converter/model/sbml/NotesUtility.java | 2 +- .../model/sbml/SbmlBioEntityParser.java | 2 +- .../converter/model/sbml/SbmlExporter.java | 2 +- .../converter/model/sbml/SbmlParser.java | 40 +- .../sbml/GeneratedSbmlValidationTests.java | 27 +- converter/pom.xml | 79 +-- .../mapviewer/converter/ProjectFactory.java | 99 ++- .../converter/ZIndexPopulatorTest.java | 1 + .../annotation/XmlAnnotationParserTest.java | 1 + model-command/pom.xml | 110 ++-- .../commands/CreateHierarchyCommand.java | 4 +- .../commands/MoveElementsCommand.java | 192 ------ .../layout/ApplySimpleLayoutModelCommand.java | 4 +- .../lcsb/mapviewer/utils}/ImportOnly.java | 8 +- .../java/lcsb/mapviewer/utils}/NoteField.java | 28 +- .../utils}/RestAnnotationParser.java | 217 +++---- .../mapviewer/utils}/XmlAnnotationParser.java | 2 +- .../mapviewer/utils}/ZIndexPopulator.java | 30 +- .../commands/ColorModelCommandTest.java | 573 ++++++++++-------- .../commands/CommandTestFunctions.java | 70 +-- .../mapviewer/commands/CopyCommandTest.java | 86 --- .../commands/CreateHierarchyCommandTest.java | 298 +-------- .../commands/MoveElementsCommandTest.java | 241 -------- .../lcsb/mapviewer/utils}/NoteFieldTest.java | 8 +- .../utils}/RestAnnotationParserTest.java | 57 +- .../WikipathwaysTestFunctions.java | 2 +- 49 files changed, 1673 insertions(+), 2046 deletions(-) create mode 100644 converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CopyCommandForCellDesignerFilesTest.java create mode 100644 converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CreateHierarchyCommandForProblematicCDTest.java rename model-command/src/test/java/lcsb/mapviewer/commands/SubModelCommandTest.java => converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/SubModelCommandForCellDesignerFilesTest.java (87%) delete mode 100644 model-command/src/main/java/lcsb/mapviewer/commands/MoveElementsCommand.java rename {converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation => model-command/src/main/java/lcsb/mapviewer/utils}/ImportOnly.java (80%) rename {converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation => model-command/src/main/java/lcsb/mapviewer/utils}/NoteField.java (91%) rename {converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation => model-command/src/main/java/lcsb/mapviewer/utils}/RestAnnotationParser.java (88%) rename {converter/src/main/java/lcsb/mapviewer/converter/annotation => model-command/src/main/java/lcsb/mapviewer/utils}/XmlAnnotationParser.java (99%) rename {converter/src/main/java/lcsb/mapviewer/converter => model-command/src/main/java/lcsb/mapviewer/utils}/ZIndexPopulator.java (91%) delete mode 100644 model-command/src/test/java/lcsb/mapviewer/commands/MoveElementsCommandTest.java rename {converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation => model-command/src/test/java/lcsb/mapviewer/utils}/NoteFieldTest.java (85%) rename {converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation => model-command/src/test/java/lcsb/mapviewer/utils}/RestAnnotationParserTest.java (85%) diff --git a/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/CopyPasteAbstractAction.java b/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/CopyPasteAbstractAction.java index 9df84096a2..ab44805c4f 100644 --- a/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/CopyPasteAbstractAction.java +++ b/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/CopyPasteAbstractAction.java @@ -1,24 +1,22 @@ package lcsb.mapviewer.cdplugin.copypaste; -import java.util.HashSet; -import java.util.Set; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamRelationType; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.utils.XmlAnnotationParser; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.HashSet; +import java.util.Set; /** * This abstract class defines common function for {@link CopyAction} and * {@link PasteAction}. - * + * * @author Piotr Gawron - * */ public class CopyPasteAbstractAction { /** @@ -35,9 +33,8 @@ public class CopyPasteAbstractAction { /** * Serializes {@link MiriamData} into string that will be stored into system * clipboard. - * - * @param md - * object to serialize + * + * @param md object to serialize * @return string representation of {@link MiriamData} */ protected String serialize(final MiriamData md) { @@ -48,9 +45,8 @@ public class CopyPasteAbstractAction { /** * Deserialize {@link MiriamData} from string creted by * {@link #serialize(MiriamData)} method. - * - * @param string - * string representation of {@link MiriamData} + * + * @param string string representation of {@link MiriamData} * @return {@link MiriamData} obtained from input string */ protected MiriamData deserialize(final String string) { @@ -77,14 +73,11 @@ public class CopyPasteAbstractAction { /** * Returns serialized string of annotations and notes. - * - * @param annotationString - * xml string representing annotations in CellDesigner - * @param notesString - * flat notes String + * + * @param annotationString xml string representing annotations in CellDesigner + * @param notesString flat notes String * @return serialized string - * @throws InvalidXmlSchemaException - * thrown when xmlString is invalid + * @throws InvalidXmlSchemaException thrown when xmlString is invalid */ protected String getCopyString(final String annotationString, final String notesString) throws InvalidXmlSchemaException { XmlAnnotationParser xap = new XmlAnnotationParser(); @@ -100,10 +93,8 @@ public class CopyPasteAbstractAction { /** * Deserialize string created by {@link #getCopyString(String, String)} * method. Used to create {@link MiriamData} set and notes from clipboard. - * - * @param value - * string for deserialization - * + * + * @param value string for deserialization * @return {@link Pair} of {@link MiriamData} set and notes string */ protected Pair<Set<MiriamData>, String> getAnnotationDataFromClipboardString(final String value) { @@ -112,7 +103,7 @@ public class CopyPasteAbstractAction { } String[] rows = value.split("\n"); - StringBuilder sb = new StringBuilder(""); + StringBuilder sb = new StringBuilder(); boolean miriam = true; diff --git a/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/PasteAction.java b/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/PasteAction.java index 7d0ba23e86..332181c519 100644 --- a/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/PasteAction.java +++ b/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/PasteAction.java @@ -1,25 +1,23 @@ package lcsb.mapviewer.cdplugin.copypaste; -import java.util.Set; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import jp.sbi.celldesigner.plugin.PluginListOf; import jp.sbi.celldesigner.plugin.PluginReaction; import jp.sbi.celldesigner.plugin.PluginSBase; import jp.sbi.celldesigner.plugin.PluginSpecies; import jp.sbi.celldesigner.plugin.PluginSpeciesAlias; import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.model.map.MiriamData; +import lcsb.mapviewer.utils.XmlAnnotationParser; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.Set; /** * CD Plugin action responsible for translating annotation stored in notes to * xml format stored in annotations. - * + * * @author Piotr Gawron - * */ public class PasteAction extends CopyPasteAbstractAction { /** @@ -30,11 +28,9 @@ public class PasteAction extends CopyPasteAbstractAction { /** * Method that perform annotation of a CellDesigner species listed in * speciesList. - * - * @param plug - * - a plugin object - * @param speciesList - * - list of species to annotate + * + * @param plug - a plugin object + * @param speciesList - list of species to annotate */ public void performAnnotation(final CopyPastePlugin plug, final PluginListOf speciesList) { XmlAnnotationParser xap = new XmlAnnotationParser(); diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiriamConnectorImpl.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiriamConnectorImpl.java index fcf345ef25..39cb26152e 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiriamConnectorImpl.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiriamConnectorImpl.java @@ -4,9 +4,9 @@ import lcsb.mapviewer.annotation.cache.CachableInterface; import lcsb.mapviewer.annotation.cache.QueryCacheInterface; import lcsb.mapviewer.annotation.cache.SourceNotAvailable; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.utils.XmlAnnotationParser; import org.apache.http.HttpStatus; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/converter-CellDesigner/pom.xml b/converter-CellDesigner/pom.xml index 5a0a9c557e..4327db604e 100644 --- a/converter-CellDesigner/pom.xml +++ b/converter-CellDesigner/pom.xml @@ -1,86 +1,92 @@ <project xmlns="http://maven.apache.org/POM/4.0.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <parent> - <groupId>lcsb.mapviewer</groupId> - <artifactId>parent</artifactId> - <version>19.0.0~alpha.0</version> - </parent> - <artifactId>converter-CellDesigner</artifactId> - <name>CellDesigner converter</name> - <description>CellDesigner converter for model</description> + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>lcsb.mapviewer</groupId> + <artifactId>parent</artifactId> + <version>19.0.0~alpha.0</version> + </parent> + <artifactId>converter-CellDesigner</artifactId> + <name>CellDesigner converter</name> + <description>CellDesigner converter for model</description> - <dependencies> + <dependencies> - <!-- dependency from the MapViewer model --> - <dependency> - <groupId>lcsb.mapviewer</groupId> - <artifactId>model</artifactId> - <version>19.0.0~alpha.0</version> - </dependency> + <!-- dependency from the MapViewer model --> + <dependency> + <groupId>lcsb.mapviewer</groupId> + <artifactId>model</artifactId> + <version>19.0.0~alpha.0</version> + </dependency> - <dependency> - <groupId>lcsb.mapviewer</groupId> - <artifactId>converter</artifactId> - <version>19.0.0~alpha.0</version> - </dependency> + <dependency> + <groupId>lcsb.mapviewer</groupId> + <artifactId>model-command</artifactId> + <version>19.0.0~alpha.0</version> + </dependency> - <!-- Log4J2 --> - <dependency> - <groupId>org.apache.logging.log4j</groupId> - <artifactId>log4j-api</artifactId> - <version>${log4j2.version}</version> - </dependency> - <dependency> - <groupId>org.apache.logging.log4j</groupId> - <artifactId>log4j-core</artifactId> - <version>${log4j2.version}</version> - </dependency> + <dependency> + <groupId>lcsb.mapviewer</groupId> + <artifactId>converter</artifactId> + <version>19.0.0~alpha.0</version> + </dependency> - <!-- mockito used for testing --> - <dependency> - <groupId>org.mockito</groupId> - <artifactId>mockito-core</artifactId> - <version>${mockito.version}</version> - <scope>test</scope> - </dependency> + <!-- Log4J2 --> + <dependency> + <groupId>org.apache.logging.log4j</groupId> + <artifactId>log4j-api</artifactId> + <version>${log4j2.version}</version> + </dependency> + <dependency> + <groupId>org.apache.logging.log4j</groupId> + <artifactId>log4j-core</artifactId> + <version>${log4j2.version}</version> + </dependency> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <version>${junit.version}</version> - <scope>test</scope> - </dependency> + <!-- mockito used for testing --> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <version>${mockito.version}</version> + <scope>test</scope> + </dependency> - <!-- Utils used for connection via http for SBML validation --> - <dependency> - <groupId>org.apache.httpcomponents</groupId> - <artifactId>httpclient</artifactId> - <version>${apache.httpcomponents.version}</version> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.apache.httpcomponents</groupId> - <artifactId>httpmime</artifactId> - <version>${apache.httpcomponents.version}</version> - <scope>compile</scope> - </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>${junit.version}</version> + <scope>test</scope> + </dependency> - <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> - <dependency> - <groupId>org.springframework</groupId> - <artifactId>spring-context</artifactId> - <version>${springframework.version}</version> - </dependency> + <!-- Utils used for connection via http for SBML validation --> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>${apache.httpcomponents.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpmime</artifactId> + <version>${apache.httpcomponents.version}</version> + <scope>compile</scope> + </dependency> - <!-- spring module used for testing --> - <dependency> - <groupId>org.springframework</groupId> - <artifactId>spring-test</artifactId> - <version>${springframework.version}</version> - </dependency> + <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-context</artifactId> + <version>${springframework.version}</version> + </dependency> - </dependencies> + <!-- spring module used for testing --> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-test</artifactId> + <version>${springframework.version}</version> + </dependency> + + </dependencies> </project> \ No newline at end of file diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerXmlParser.java index 545ba73da2..a732c0d83e 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerXmlParser.java @@ -8,10 +8,7 @@ import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.Converter; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.InvalidInputDataExecption; -import lcsb.mapviewer.converter.ZIndexPopulator; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.alias.AliasCollectionXmlParser; -import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.compartment.CompartmentCollectionXmlParser; import lcsb.mapviewer.converter.model.celldesigner.function.FunctionCollectionXmlParser; import lcsb.mapviewer.converter.model.celldesigner.parameter.ParameterCollectionXmlParser; @@ -41,6 +38,9 @@ import lcsb.mapviewer.model.map.species.Protein; import lcsb.mapviewer.model.map.species.Rna; import lcsb.mapviewer.model.map.species.Species; import lcsb.mapviewer.modelutils.map.LogFormatter; +import lcsb.mapviewer.utils.RestAnnotationParser; +import lcsb.mapviewer.utils.XmlAnnotationParser; +import lcsb.mapviewer.utils.ZIndexPopulator; import org.apache.commons.io.FilenameUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.logging.log4j.LogManager; @@ -406,7 +406,7 @@ public class CellDesignerXmlParser extends Converter { private void processModelRdfNode(final Model model, final Node node) throws InvalidXmlSchemaException { final XmlAnnotationParser xmlAnnotationParser = new XmlAnnotationParser( - CommonXmlParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); + RestAnnotationParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); model.addMiriamData(xmlAnnotationParser.parseRdfNode(node, null)); model.addAuthors(xmlAnnotationParser.getAuthorsFromRdf(node)); model.setCreationDate(xmlAnnotationParser.getCreateDateFromRdf(node)); @@ -739,7 +739,7 @@ public class CellDesignerXmlParser extends Converter { result.append("</celldesigner:extension>\n"); final XmlAnnotationParser xmlAnnotationParser = new XmlAnnotationParser( - CommonXmlParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); + RestAnnotationParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); result.append(xmlAnnotationParser.dataSetToXmlString(model.getMiriamData(), model.getAuthors(), model.getCreationDate(), model.getModificationDates(), model.getIdModel())); result.append("</annotation>\n"); diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/CommonXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/CommonXmlParser.java index 0eef92bcf2..a10c2acd55 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/CommonXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/CommonXmlParser.java @@ -1,56 +1,34 @@ package lcsb.mapviewer.converter.model.celldesigner; -import java.awt.Color; -import java.awt.geom.Dimension2D; -import java.awt.geom.Point2D; -import java.io.ByteArrayInputStream; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - +import lcsb.mapviewer.common.XmlParser; +import lcsb.mapviewer.common.exception.InvalidStateException; +import lcsb.mapviewer.common.geometry.DoubleDimension; +import lcsb.mapviewer.converter.model.celldesigner.structure.fields.SingleLine; +import lcsb.mapviewer.converter.model.celldesigner.structure.fields.View; import org.apache.commons.lang3.StringUtils; import org.w3c.dom.Node; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; -import lcsb.mapviewer.common.XmlParser; -import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.common.geometry.DoubleDimension; -import lcsb.mapviewer.converter.model.celldesigner.structure.fields.SingleLine; -import lcsb.mapviewer.converter.model.celldesigner.structure.fields.View; -import lcsb.mapviewer.model.map.MiriamRelationType; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import java.awt.Color; +import java.awt.geom.Dimension2D; +import java.awt.geom.Point2D; +import java.io.ByteArrayInputStream; /** * Class with parsers for common CellDesigner objects. - * + * * @author Piotr Gawron - * */ public class CommonXmlParser { - public static final Set<MiriamRelationType> RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER; - - static { - Set<MiriamRelationType> types = new HashSet<>(); - types.addAll(Arrays.asList(MiriamRelationType.values())); - types.remove(MiriamRelationType.BQ_MODEL_IS_DERIVED_FROM); - types.remove(MiriamRelationType.BQ_BIOL_HAS_PROPERTY); - types.remove(MiriamRelationType.BQ_BIOL_IS_PROPERTY_OF); - types.remove(MiriamRelationType.BQ_MODEL_IS_INSTANCE_OF); - types.remove(MiriamRelationType.BQ_MODEL_HAS_INSTANCE); - types.remove(MiriamRelationType.BQ_BIOL_HAS_TAXON); - RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER = Collections.unmodifiableSet(types); - } - - private DocumentBuilderFactory dbFactory; - private DocumentBuilder documentBuilder; + private final DocumentBuilderFactory dbFactory; + private final DocumentBuilder documentBuilder; public CommonXmlParser() { try { @@ -59,7 +37,6 @@ public class CommonXmlParser { documentBuilder.setErrorHandler(new ErrorHandler() { @Override public void warning(final SAXParseException e) throws SAXException { - ; } @Override @@ -80,9 +57,8 @@ public class CommonXmlParser { /** * Parse xml representation of position into Poin2D object. - * - * @param node - * xml node to parse + * + * @param node xml node to parse * @return Point2D object */ public Point2D getPosition(final Node node) { @@ -94,9 +70,8 @@ public class CommonXmlParser { /** * Parse xml representation of dimension. - * - * @param node - * xml node to parse + * + * @param node xml node to parse * @return dimension (with width and height fields) */ public Dimension2D getDimension(final Node node) { @@ -108,9 +83,8 @@ public class CommonXmlParser { /** * Parse xml representation of CellDesigner SingleLine. - * - * @param node - * xml node to parse + * + * @param node xml node to parse * @return single line object (with width field) */ public SingleLine getSingleLine(final Node node) { @@ -121,9 +95,8 @@ public class CommonXmlParser { /** * Parse xml representation of CellDesigner color. - * - * @param node - * xml node to parse + * + * @param node xml node to parse * @return Color value stored in xml */ public Color getColor(final Node node) { @@ -137,9 +110,8 @@ public class CommonXmlParser { /** * Parse xml representation of CellDesigner view. - * - * @param node - * xml node to parse + * + * @param node xml node to parse * @return view parsed from xml * @see View */ diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/LayerXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/LayerXmlParser.java index 59a5aaf0a5..4195ae9f81 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/LayerXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/LayerXmlParser.java @@ -3,7 +3,6 @@ package lcsb.mapviewer.converter.model.celldesigner; import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.common.geometry.ColorParser; -import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; import lcsb.mapviewer.model.graphics.ArrowType; import lcsb.mapviewer.model.graphics.LineType; import lcsb.mapviewer.model.graphics.PolylineData; @@ -15,6 +14,7 @@ import lcsb.mapviewer.model.map.layout.graphics.LayerRect; import lcsb.mapviewer.model.map.layout.graphics.LayerText; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; +import lcsb.mapviewer.utils.RestAnnotationParser; import org.apache.commons.lang3.math.NumberUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/AliasCollectionXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/AliasCollectionXmlParser.java index f5804daed3..1d34142150 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/AliasCollectionXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/AliasCollectionXmlParser.java @@ -1,31 +1,29 @@ package lcsb.mapviewer.converter.model.celldesigner.alias; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; -import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerElement; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.compartment.PathwayCompartment; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Complex; import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.utils.RestAnnotationParser; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; /** * This class contains function to parse CellDesigner xml nodes containing * collection of aliases. It also contains functionality to do reverse operation * - transform set of aliases into xml node. - * + * * @author Piotr Gawron - * */ public class AliasCollectionXmlParser { @@ -33,7 +31,7 @@ public class AliasCollectionXmlParser { * Default class logger. */ @SuppressWarnings("unused") - private Logger logger = LogManager.getLogger(); + private final Logger logger = LogManager.getLogger(); /** * Single SpeciesAlias parser for CellDesigner node. @@ -53,19 +51,17 @@ public class AliasCollectionXmlParser { /** * Annotation parser. */ - private RestAnnotationParser rap = new RestAnnotationParser(); + private final RestAnnotationParser rap = new RestAnnotationParser(); /** - * Default parser. As an parameter model object for which parsing is done is + * Default parser. As a parameter model object for which parsing is done is * required. This is due to the fact that CellDesigner model is very tangled and * very often data are distributed in many different places and in other places * they are missing... - * - * @param model - * map model for which parsing is performed - * @param elements - * collection of {@link CellDesignerElement cell designer elements} - * parsed from xml + * + * @param model map model for which parsing is performed + * @param elements collection of {@link CellDesignerElement cell designer elements} + * parsed from xml */ public AliasCollectionXmlParser(final CellDesignerElementCollection elements, final Model model) { speciesAliasParser = new SpeciesAliasXmlParser(elements, model); @@ -76,12 +72,10 @@ public class AliasCollectionXmlParser { /** * Parses xml node containing list of species aliases into collection of * SpeciesAlias. - * - * @param aliasListNode - * xml node to be parsed + * + * @param aliasListNode xml node to be parsed * @return collection of SpeciesAlias obtained from xml node - * @throws InvalidXmlSchemaException - * thrown when there is a problem with xml + * @throws InvalidXmlSchemaException thrown when there is a problem with xml */ public List<Species> parseXmlSpeciesAliasCollection(final Node aliasListNode) throws InvalidXmlSchemaException { List<Species> result = new ArrayList<Species>(); @@ -104,9 +98,8 @@ public class AliasCollectionXmlParser { /** * Creates xml string representing collection of SpeciesAlias. - * - * @param collection - * collection of SpeciesAlias + * + * @param collection collection of SpeciesAlias * @return xml string representing collection of SpeciesAlias */ public String speciesAliasCollectionToXmlString(final Collection<Species> collection) { @@ -121,12 +114,10 @@ public class AliasCollectionXmlParser { /** * Parses xml node containing list of complex aliases into collection of * ComplexAlias. - * - * @param aliasListNode - * xml node to be parsed + * + * @param aliasListNode xml node to be parsed * @return collection of ComplexAlias obtained from xml node - * @throws InvalidXmlSchemaException - * thrown when xmlString is invalid + * @throws InvalidXmlSchemaException thrown when xmlString is invalid */ public List<Complex> parseXmlComplexAliasCollection(final Node aliasListNode) throws InvalidXmlSchemaException { List<Complex> result = new ArrayList<Complex>(); @@ -151,9 +142,8 @@ public class AliasCollectionXmlParser { /** * Creates xml string representing collection of ComplexAlias. - * - * @param collection - * collection of ComplexAlias + * + * @param collection collection of ComplexAlias * @return xml string representing collection of ComplexAlias */ public String complexAliasCollectionToXmlString(final Collection<Complex> collection) { @@ -168,12 +158,10 @@ public class AliasCollectionXmlParser { /** * Parses xml node containing list of compartment aliases into collection of * CompartmentAlias. - * - * @param aliasListNode - * xml node to be parsed + * + * @param aliasListNode xml node to be parsed * @return collection of CompartmentAlias obtained from xml node - * @throws InvalidXmlSchemaException - * thrown when xmlString is invalid + * @throws InvalidXmlSchemaException thrown when xmlString is invalid */ public List<Compartment> parseXmlCompartmentAliasCollection(final Node aliasListNode) throws InvalidXmlSchemaException { List<Compartment> result = new ArrayList<>(); @@ -197,9 +185,8 @@ public class AliasCollectionXmlParser { /** * Assing compartment parents for list of compartments. - * - * @param compartments - * compartments that are looking for parents + * + * @param compartments compartments that are looking for parents */ private void assignParents(final List<Compartment> compartments) { Compartment nullParent = new Compartment("null"); @@ -225,9 +212,8 @@ public class AliasCollectionXmlParser { /** * Creates xml string representing collection of CompartmentAlias. - * - * @param collection - * collection of CompartmentAlias + * + * @param collection collection of CompartmentAlias * @return xml string representing collection of CompartmentAlias */ public String compartmentAliasCollectionToXmlString(final Collection<Compartment> collection) { diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentXmlParser.java index 826126c061..64ae60ab25 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentXmlParser.java @@ -1,15 +1,9 @@ package lcsb.mapviewer.converter.model.celldesigner.compartment; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; -import lcsb.mapviewer.converter.model.celldesigner.CommonXmlParser; -import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.species.AbstractElementXmlParser; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerCompartment; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerElement; @@ -17,41 +11,43 @@ import lcsb.mapviewer.model.LogMarker; import lcsb.mapviewer.model.ProjectLogEntryType; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.compartment.PathwayCompartment; +import lcsb.mapviewer.utils.RestAnnotationParser; +import lcsb.mapviewer.utils.XmlAnnotationParser; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; /** * Parser of CellDesginer xml nodes for compartment elements. - * + * * @author Piotr Gawron - * */ public class CompartmentXmlParser extends AbstractElementXmlParser<CellDesignerCompartment, Compartment> { /** * Parser used to retrieve Miriam data for the element. */ - private XmlAnnotationParser xmlAnnotationParser; + private final XmlAnnotationParser xmlAnnotationParser; /** * Collection of {@link CellDesignerElement cell designer elements} parsed * from xml. */ - private CellDesignerElementCollection elements; + private final CellDesignerElementCollection elements; /** * Xml parser used for processing notes into structured data. */ - private RestAnnotationParser rap = new RestAnnotationParser(); + private final RestAnnotationParser rap = new RestAnnotationParser(); /** * Default constructor. - * - * @param elements - * collection of {@link CellDesignerElement cell designer elements} - * parsed from xml + * + * @param elements collection of {@link CellDesignerElement cell designer elements} + * parsed from xml */ public CompartmentXmlParser(final CellDesignerElementCollection elements) { this.elements = elements; - xmlAnnotationParser = new XmlAnnotationParser(CommonXmlParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); + xmlAnnotationParser = new XmlAnnotationParser(lcsb.mapviewer.utils.RestAnnotationParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); } @Override @@ -83,7 +79,7 @@ public class CompartmentXmlParser extends AbstractElementXmlParser<CellDesignerC @Override public String toXml(final Compartment compartment) { - StringBuilder sb = new StringBuilder(""); + StringBuilder sb = new StringBuilder(); sb.append("<compartment "); sb.append("metaid=\"" + elements.getElementId(compartment) + "\" "); sb.append("id=\"" + elements.getElementId(compartment) + "\" "); @@ -125,12 +121,9 @@ public class CompartmentXmlParser extends AbstractElementXmlParser<CellDesignerC /** * Process annotation part of the xml node. * - * @param compartment - * object that we create - * @param xmlNode - * annotation xml node - * @throws InvalidXmlSchemaException - * thrown when there is a problem with xml + * @param compartment object that we create + * @param xmlNode annotation xml node + * @throws InvalidXmlSchemaException thrown when there is a problem with xml */ private void parseAnnotationNode(final CellDesignerCompartment compartment, final Node xmlNode) throws InvalidXmlSchemaException { NodeList annotationNodes = xmlNode.getChildNodes(); @@ -156,12 +149,9 @@ public class CompartmentXmlParser extends AbstractElementXmlParser<CellDesignerC /** * Process extension part of the xml node. * - * @param compartment - * object that we create - * @param xmlNode - * annotation xml node - * @throws InvalidXmlSchemaException - * thrown when xmlNode is invalid + * @param compartment object that we create + * @param xmlNode annotation xml node + * @throws InvalidXmlSchemaException thrown when xmlNode is invalid */ private void parseExtensionNode(final CellDesignerCompartment compartment, final Node xmlNode) throws InvalidXmlSchemaException { NodeList annotationNodes = xmlNode.getChildNodes(); diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionFromXml.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionFromXml.java index 3cd4a8e526..bea9a303b2 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionFromXml.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionFromXml.java @@ -4,10 +4,7 @@ import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidStateException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; -import lcsb.mapviewer.converter.model.celldesigner.CommonXmlParser; -import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.geometry.CellDesignerAliasConverter; import lcsb.mapviewer.converter.model.celldesigner.geometry.ReactionCellDesignerConverter; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; @@ -49,6 +46,8 @@ import lcsb.mapviewer.model.map.species.Complex; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; import lcsb.mapviewer.modelutils.map.ElementUtils; +import lcsb.mapviewer.utils.RestAnnotationParser; +import lcsb.mapviewer.utils.XmlAnnotationParser; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.w3c.dom.Node; @@ -81,60 +80,60 @@ public class ReactionFromXml { * Product lines in cell designer starts in the 3/5 of the center line. */ private static final double PRODUCT_START_RATIO = 0.6; - private CellDesignerElementCollection elements; + private final CellDesignerElementCollection elements; /** * Stores information about {@link CellDesignerAnchor} for a node. */ - private Map<ReactionNode, CellDesignerAnchor> anchorsByNodes = new HashMap<>(); + private final Map<ReactionNode, CellDesignerAnchor> anchorsByNodes = new HashMap<>(); /** * Stores information about operator type that should be used for a modifier * node. */ - private Map<ReactionNode, String> typeByModifier = new HashMap<>(); + private final Map<ReactionNode, String> typeByModifier = new HashMap<>(); /** * Stores information to which point on the central rectangle modifier should * be connected. */ - private Map<ReactionNode, String> lineTypeByModifier = new HashMap<>(); + private final Map<ReactionNode, String> lineTypeByModifier = new HashMap<>(); /** * Stores information about list of points that create line describing * modifier. */ - private Map<ReactionNode, List<Point2D>> pointsByModifier = new HashMap<>(); + private final Map<ReactionNode, List<Point2D>> pointsByModifier = new HashMap<>(); /** * Stores information about list of points that create line describing * modifier. */ - private Map<ReactionNode, LineProperties> linePropertiesByModifier = new HashMap<>(); + private final Map<ReactionNode, LineProperties> linePropertiesByModifier = new HashMap<>(); /** * Helps to determine if the key Modifier should be treats as part of * NodeOperator (value in the map). */ - private Map<Modifier, Modifier> modifierParentOperator = new HashMap<>(); + private final Map<Modifier, Modifier> modifierParentOperator = new HashMap<>(); /** * Identifies central line segment in {@link TwoProductReactionInterface} and * {@link TwoReactantReactionInterface} reactions. */ - private Map<ReactionNode, Integer> indexByComplexReaction = new HashMap<>(); + private final Map<ReactionNode, Integer> indexByComplexReaction = new HashMap<>(); /** * Default class logger. */ - private Logger logger = LogManager.getLogger(); + private final Logger logger = LogManager.getLogger(); /** * Xml parser used for processing notes into structured data. */ - private RestAnnotationParser rap = new RestAnnotationParser(); + private final RestAnnotationParser rap = new RestAnnotationParser(); /** * Helper object used for manipulation on the point coordinates in * CellDesigner format. */ - private CellDesignerPointTransformation pointTransformation = new CellDesignerPointTransformation(); + private final CellDesignerPointTransformation pointTransformation = new CellDesignerPointTransformation(); /** * Should SBGN standard be used. */ - private boolean sbgn; + private final boolean sbgn; - private boolean oldCellDesignerVersion; + private final boolean oldCellDesignerVersion; /** * Default constructor. @@ -217,7 +216,7 @@ public class ReactionFromXml { // with reversible flag (even though it cannot be reversible) if (result.isReversible()) { logger.warn( - new ElementUtils().getElementTag(result) + "Reacion was marked as reversible but it cannot be reversible"); + new ElementUtils().getElementTag(result) + "Reacion was marked as reversible but it cannot be reversible"); result.setReversible(false); } } @@ -328,7 +327,7 @@ public class ReactionFromXml { * @throws InvalidXmlSchemaException thrown when annotationNode is invalid xml */ private Reaction parseReactionAnnotation(final Node annotationNode, final Reaction reaction, final Model model) - throws ReactionParserException { + throws ReactionParserException { Reaction result = reaction; NodeList nodes = annotationNode.getChildNodes(); if (oldCellDesignerVersion) { @@ -342,9 +341,9 @@ public class ReactionFromXml { } else if (node.getNodeName().equalsIgnoreCase("rdf:RDF")) { try { XmlAnnotationParser xmlParser = new XmlAnnotationParser( - CommonXmlParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); + RestAnnotationParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); result.addMiriamData(xmlParser.parseRdfNode(node, new LogMarker(ProjectLogEntryType.PARSING_ISSUE, - result.getClass().getSimpleName(), result.getElementId(), model.getName()))); + result.getClass().getSimpleName(), result.getElementId(), model.getName()))); } catch (final InvalidXmlSchemaException e) { throw new ReactionParserException("Problem with parsing RDF", result, e); } @@ -394,7 +393,7 @@ public class ReactionFromXml { result.addReactant(parseBaseReactant(reactantNode, model)); } else { throw new ReactionParserException( - "Unknown element of celldesigner:baseReactants: " + node.getNodeName(), result); + "Unknown element of celldesigner:baseReactants: " + node.getNodeName(), result); } } } @@ -407,7 +406,7 @@ public class ReactionFromXml { result.addProduct(parseBaseProduct(model, reactantNode)); } else { throw new ReactionParserException( - "Unknown element of celldesigner:baseProducts: " + node.getNodeName(), result); + "Unknown element of celldesigner:baseProducts: " + node.getNodeName(), result); } } } @@ -429,7 +428,7 @@ public class ReactionFromXml { gateMembers = nodeReaction; } else { throw new ReactionParserException( - "Unknown element of reaction/celldesigner:extension: " + nodeReaction.getNodeName(), result); + "Unknown element of reaction/celldesigner:extension: " + nodeReaction.getNodeName(), result); } } } @@ -456,7 +455,7 @@ public class ReactionFromXml { createOperatorsForTwoProductReaction(result); } else { throw new ReactionParserException( - "Problem with parsing lines. Unknown reaction: " + type + "; " + result.getClass().getName(), result); + "Problem with parsing lines. Unknown reaction: " + type + "; " + result.getClass().getName(), result); } for (final AbstractNode reactionNode : result.getNodes()) { @@ -503,7 +502,7 @@ public class ReactionFromXml { if (result.isReversible()) { for (final Reactant reactant : result.getReactants()) { reactant.getLine().getBeginAtd() - .setArrowType(result.getProducts().get(0).getLine().getEndAtd().getArrowType()); + .setArrowType(result.getProducts().get(0).getLine().getEndAtd().getArrowType()); } } @@ -559,7 +558,7 @@ public class ReactionFromXml { * schema */ private EditPoints gateMembersToPoints(final Reaction reaction, final Node gateMembers) - throws InvalidXmlSchemaException, ReactionParserException { + throws InvalidXmlSchemaException, ReactionParserException { Node lastMember = null; EditPoints result = new EditPoints(); for (int i = 0; i < gateMembers.getChildNodes().getLength(); i++) { @@ -622,9 +621,9 @@ public class ReactionFromXml { ModifierTypeUtils modifierTypeUtils = new ModifierTypeUtils(); Point2D p = modifierTypeUtils.getAnchorPointOnReactionRect(modifier.getReaction(), - lineTypeByModifier.get(modifier)); + lineTypeByModifier.get(modifier)); PolylineData line = PolylineDataFactory.createPolylineDataFromEditPoints(startPoint, p, - pointsByModifier.get(modifier)); + pointsByModifier.get(modifier)); startPoint = converter.getAnchorPointCoordinates(element, anchorsByNodes.get(modifier), line); line.setStartPoint(startPoint); @@ -696,8 +695,8 @@ public class ReactionFromXml { result.addNode(operator); PolylineData centerLine = new PolylineData( - pointTransformation.copyPoint(reactant.getLine().getEndPoint()), - pointTransformation.copyPoint(operator.getLine().getEndPoint())); + pointTransformation.copyPoint(reactant.getLine().getEndPoint()), + pointTransformation.copyPoint(operator.getLine().getEndPoint())); centerLine.setType(reactant.getLine().getType()); result.setLine(centerLine); @@ -711,7 +710,7 @@ public class ReactionFromXml { private void createOperators(final Reaction result) { // central line points Point2D p1 = result.getReactants().get(0).getLine().getLines() - .get(result.getReactants().get(0).getLine().getLines().size() - 1).getP1(); + .get(result.getReactants().get(0).getLine().getLines().size() - 1).getP1(); Point2D p2 = result.getProducts().get(0).getLine().getLines().get(0).getP2(); Point2D tmp = result.getProducts().get(0).getLine().getStartPoint(); Point2D productSplitOperatorBeginPoint = new Point2D.Double(tmp.getX(), tmp.getY()); @@ -743,7 +742,7 @@ public class ReactionFromXml { double dy = p2.getY() - p1.getY(); Point2D reactantAndOperatorBeginPoint = new Point2D.Double(p1.getX() + dx * REACTANT_END_RATIO, - p1.getY() + dy * REACTANT_END_RATIO); + p1.getY() + dy * REACTANT_END_RATIO); PolylineData ld = new PolylineData(reactantAndOperatorBeginPoint, reactantAndOperatorEndPoint); @@ -787,7 +786,7 @@ public class ReactionFromXml { } Point2D productSplitOperatorEndPoint = new Point2D.Double(p1.getX() + dx * PRODUCT_START_RATIO, - p1.getY() + dy * PRODUCT_START_RATIO); + p1.getY() + dy * PRODUCT_START_RATIO); ld = new PolylineData(productSplitOperatorEndPoint, productSplitOperatorBeginPoint); @@ -812,7 +811,7 @@ public class ReactionFromXml { if (!toExclude.contains(product)) { // outputOperator.addOutput(product); product.getLine().setStartPoint(productSplitOperatorEndPoint.getX(), - productSplitOperatorEndPoint.getY()); + productSplitOperatorEndPoint.getY()); } } if (lineType != null) { @@ -905,7 +904,7 @@ public class ReactionFromXml { result.addNode(andOperator); PolylineData centerLine = new PolylineData(pointTransformation.copyPoint(andOperator.getLine().getEndPoint()), - pointTransformation.copyPoint(product.getLine().getStartPoint())); + pointTransformation.copyPoint(product.getLine().getStartPoint())); centerLine.setType(product.getLine().getType()); result.setLine(centerLine); @@ -939,7 +938,7 @@ public class ReactionFromXml { types += string + ", "; } throw new ReactionParserException( - "Couldn't find type of BOOLEAN_LOGIC_GATE. Unknown types identified: " + types, result); + "Couldn't find type of BOOLEAN_LOGIC_GATE. Unknown types identified: " + types, result); } operator.addInputs(andOperator.getInputs()); @@ -947,18 +946,18 @@ public class ReactionFromXml { // operator line Point2D secondPoint = pointTransformation.getPointOnLine(product.getLine().getLines().get(0).getP1(), - product.getLine().getLines().get(0).getP2(), 0.4); + product.getLine().getLines().get(0).getP2(), 0.4); Point2D thirdPoint = pointTransformation.getPointOnLine(product.getLine().getLines().get(0).getP1(), - product.getLine().getLines().get(0).getP2(), 0.6); + product.getLine().getLines().get(0).getP2(), 0.6); PolylineData line = new PolylineData(pointTransformation.copyPoint( - product.getLine().getStartPoint()), - pointTransformation.copyPoint(secondPoint)); + product.getLine().getStartPoint()), + pointTransformation.copyPoint(secondPoint)); line.setType(product.getLine().getType()); operator.setLine(line); // center line PolylineData centerLine = new PolylineData(pointTransformation.copyPoint(secondPoint), - pointTransformation.copyPoint(thirdPoint)); + pointTransformation.copyPoint(thirdPoint)); centerLine.setType(product.getLine().getType()); result.setLine(centerLine); @@ -1022,7 +1021,7 @@ public class ReactionFromXml { Point2D p3 = product2Converter.getPointCoordinates(product2.getElement(), anchorsByNodes.get(product2)); Point2D centerPoint = pointTransformation.getCoordinatesInNormalBase(product1.getElement().getCenter(), - product2.getElement().getCenter(), reactant.getElement().getCenter(), p); + product2.getElement().getCenter(), reactant.getElement().getCenter(), p); int startId0 = 0; int num0 = points.getLineStartingPoints().get(0); @@ -1041,15 +1040,15 @@ public class ReactionFromXml { PolylineData reactantLine = PolylineDataFactory.createPolylineDataFromEditPoints(centerPoint, p1, linePoints1); p1 = product2Converter.getAnchorPointCoordinates(product2.getElement(), anchorsByNodes.get(product2), - product2Line.reverse()); + product2Line.reverse()); product2Line.setEndPoint(p1); p1 = product1Converter.getAnchorPointCoordinates(product1.getElement(), anchorsByNodes.get(product1), - product1Line.reverse()); + product1Line.reverse()); product1Line.setEndPoint(p1); p1 = reactantConverter.getAnchorPointCoordinates(reactant.getElement(), anchorsByNodes.get(reactant), - reactantLine.reverse()); + reactantLine.reverse()); reactantLine.setEndPoint(p1); product2Line.getEndAtd().setArrowType(ArrowType.FULL); @@ -1071,7 +1070,7 @@ public class ReactionFromXml { * @throws ReactionParserException thrown when data for reaction is invalid */ private void createLinesForTwoReactantReaction(final Reaction reaction, final EditPoints points) - throws ReactionParserException { + throws ReactionParserException { ReactionLineData rld = null; if (!(reaction instanceof HeterodimerAssociationReaction)) { rld = ReactionLineData.getByReactionType(reaction.getClass()); @@ -1129,7 +1128,7 @@ public class ReactionFromXml { } p1 = reactantConverter.getAnchorPointCoordinates(reactant.getElement(), anchorsByNodes.get(reactant), - reactantLine.reverse()); + reactantLine.reverse()); reactantLine.setEndPoint(p1); reactantLine = reactantLine.reverse(); @@ -1138,9 +1137,9 @@ public class ReactionFromXml { int productEndId = productStartId + points.getLineStartingPoints().get(reaction.getReactants().size()); List<Point2D> linePoints3 = new ArrayList<>(points.getPoints().subList(productStartId, productEndId)); PolylineData productLine = PolylineDataFactory.createPolylineDataFromEditPoints(centerPoint, - productConverter.getPointCoordinates(product.getElement(), anchorsByNodes.get(product)), linePoints3); + productConverter.getPointCoordinates(product.getElement(), anchorsByNodes.get(product)), linePoints3); Point2D p1 = productConverter.getAnchorPointCoordinates(product.getElement(), anchorsByNodes.get(product), - productLine.reverse()); + productLine.reverse()); productLine.setEndPoint(p1); if (rld != null) { productLine.setType(rld.getLineType()); @@ -1171,7 +1170,7 @@ public class ReactionFromXml { Point2D startPoint = reactantConverter.getPointCoordinates(reactant.getElement(), anchorsByNodes.get(reactant)); PolylineData ld = PolylineDataFactory.createPolylineDataFromEditPoints(startPoint, endPoint, - editPoints.getPoints()); + editPoints.getPoints()); // first place where the index of rectangle is kept Integer index = editPoints.getReactionCenterLineIndex(); @@ -1194,7 +1193,7 @@ public class ReactionFromXml { } startPoint = reactantConverter.getAnchorPointCoordinates(reactant.getElement(), anchorsByNodes.get(reactant), ld); endPoint = productConverter.getAnchorPointCoordinates(product.getElement(), anchorsByNodes.get(product), - ld.reverse()); + ld.reverse()); ld.setStartPoint(startPoint); ld.setEndPoint(endPoint); @@ -1229,7 +1228,7 @@ public class ReactionFromXml { productLine.trimEnd(rld.getProductLineTrim()); PolylineData reactionLine = new PolylineData(pointTransformation.copyPoint(reactantLine.getEndPoint()), - pointTransformation.copyPoint(productLine.getStartPoint())); + pointTransformation.copyPoint(productLine.getStartPoint())); reactionLine.setType(reactantLine.getType()); reaction.setLine(reactionLine); } @@ -1294,7 +1293,7 @@ public class ReactionFromXml { Point2D point = new Point2D.Double(posX, posY); if (!pointTransformation.isValidPoint(point)) { throw new InvalidArgumentException( - "Invalid point parsed from input string: " + string + ". Result point: " + point); + "Invalid point parsed from input string: " + string + ". Result point: " + point); } points2.add(point); } @@ -1323,7 +1322,7 @@ public class ReactionFromXml { result.addReactant(newReactant); } else { throw new ReactionParserException( - "Unknown element of celldesigner:listOfReactantLinks: " + node.getNodeName(), result); + "Unknown element of celldesigner:listOfReactantLinks: " + node.getNodeName(), result); } } } @@ -1366,7 +1365,7 @@ public class ReactionFromXml { points = parseEditPoints(node); } else { throw new ReactionParserException("Unknown element of celldesigner:reactantLink: " + node.getNodeName(), - reaction); + reaction); } } } @@ -1402,7 +1401,7 @@ public class ReactionFromXml { // central line points Point2D p1 = reaction.getReactants().get(0).getLine().getLines() - .get(reaction.getReactants().get(0).getLine().getLines().size() - 1).getP1(); + .get(reaction.getReactants().get(0).getLine().getLines().size() - 1).getP1(); Point2D p2 = reaction.getProducts().get(0).getLine().getLines().get(0).getP2(); Set<AbstractNode> toExclude = new HashSet<AbstractNode>(); @@ -1446,7 +1445,7 @@ public class ReactionFromXml { result.addProduct(link); } else { throw new ReactionParserException("Unknown element of celldesigner:listOfProductLinks: " + node.getNodeName(), - result); + result); } } } @@ -1490,7 +1489,7 @@ public class ReactionFromXml { points = parseEditPoints(node); } else { throw new ReactionParserException("Unknown element of celldesigner:reactantLink: " + node.getNodeName(), - reaction); + reaction); } } } @@ -1547,7 +1546,7 @@ public class ReactionFromXml { parseModificationReaction(result, node, model); } else { throw new ReactionParserException("Unknown element of celldesigner:listOfModification: " + node.getNodeName(), - result); + result); } } } @@ -1593,7 +1592,7 @@ public class ReactionFromXml { ModifierType modifierType = modifierTypeUtils.getModifierTypeForStringType(type); if (modifierType == null) { String errorInfo = "[" + reaction.getClass().getSimpleName() + "\t" + reaction.getIdReaction() - + "]\tUnknown modifier type: " + type; + + "]\tUnknown modifier type: " + type; if (ReactionLineData.getByCellDesignerString(type) != null) { errorInfo += ".\tThis type can be applied to reaction type only, not modifier."; } @@ -1630,7 +1629,7 @@ public class ReactionFromXml { } } else { throw new ReactionParserException("Unknown element of celldesigner:listOfModification: " + node.getNodeName(), - reaction); + reaction); } } @@ -1666,7 +1665,7 @@ public class ReactionFromXml { startPoint = reactantConverter.getPointCoordinates(param.getElement(), anchorsByNodes.get(param)); PolylineData polyline = PolylineDataFactory.createPolylineDataFromEditPoints(startPoint, endPoint, - pointsByModifier.get(param)); + pointsByModifier.get(param)); startPoint = reactantConverter.getAnchorPointCoordinates(param.getElement(), anchorsByNodes.get(param), polyline); polyline.setStartPoint(startPoint); @@ -1723,7 +1722,7 @@ public class ReactionFromXml { result.setLineDirections(getlineDirectionMapForReactions(reactantNode)); } else { throw new InvalidXmlSchemaException( - "Unknown element of celldesigner:connectScheme: " + nodeReaction.getNodeName()); + "Unknown element of celldesigner:connectScheme: " + nodeReaction.getNodeName()); } } } @@ -1750,7 +1749,7 @@ public class ReactionFromXml { result.put(index, value); } else { throw new InvalidXmlSchemaException( - "Unknown element of reaction/celldesigner:baseReactant: " + node.getNodeName()); + "Unknown element of reaction/celldesigner:baseReactant: " + node.getNodeName()); } } } @@ -1781,7 +1780,7 @@ public class ReactionFromXml { anchorsByNodes.put(reactant, CellDesignerAnchor.valueOf(XmlParser.getNodeAttr("position", node))); } else { throw new InvalidXmlSchemaException( - "Unknown element of reaction/celldesigner:baseReactant: " + node.getNodeName()); + "Unknown element of reaction/celldesigner:baseReactant: " + node.getNodeName()); } } } @@ -1812,7 +1811,7 @@ public class ReactionFromXml { anchorsByNodes.put(product, CellDesignerAnchor.valueOf(XmlParser.getNodeAttr("position", node))); } else { throw new InvalidXmlSchemaException( - "Unknown element of reaction/celldesigner:baseProduct: " + node.getNodeName()); + "Unknown element of reaction/celldesigner:baseProduct: " + node.getNodeName()); } } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionToXml.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionToXml.java index 7e7311cbad..953b8ff4fb 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionToXml.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionToXml.java @@ -1,25 +1,9 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; -import lcsb.mapviewer.converter.model.celldesigner.CommonXmlParser; import lcsb.mapviewer.converter.model.celldesigner.geometry.CellDesignerAliasConverter; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerLineTransformation; @@ -47,60 +31,70 @@ import lcsb.mapviewer.model.map.reaction.type.TwoReactantReactionInterface; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; import lcsb.mapviewer.modelutils.map.ElementUtils; +import lcsb.mapviewer.utils.RestAnnotationParser; +import lcsb.mapviewer.utils.XmlAnnotationParser; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.awt.geom.Line2D; +import java.awt.geom.Point2D; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * This is a part of {@link ReactionXmlParser} class functionality that allows * to export reaction into CellDesigner xml node. - * + * * @author Piotr Gawron - * */ public class ReactionToXml { /** * Default class logger. */ - private static Logger logger = LogManager.getLogger(); + private static final Logger logger = LogManager.getLogger(); /** * Helper object used for manipulation on the point coordinates in * CellDesigner format. */ - private CellDesignerPointTransformation pointTransformation = new CellDesignerPointTransformation(); + private final CellDesignerPointTransformation pointTransformation = new CellDesignerPointTransformation(); /** * Helper object used for manipulation on the line structures in CellDesigner * format. */ - private CellDesignerLineTransformation lineTransformation = new CellDesignerLineTransformation(); + private final CellDesignerLineTransformation lineTransformation = new CellDesignerLineTransformation(); /** * Collection of {@link CellDesignerElement cell designer elements} parsed * from xml. */ - private CellDesignerElementCollection elements; + private final CellDesignerElementCollection elements; /** * Helps in providing human readable identifiers of elements for logging. */ - private ElementUtils eu = new ElementUtils(); - - private int metaIdCounter = 0; - + private final ElementUtils eu = new ElementUtils(); /** * Defines if SBGN standard should be used. */ - private boolean sbgn; + private final boolean sbgn; + private int metaIdCounter = 0; /** * Default constructor. Model is required because some nodes require access to * other parts of the model. - * - * @param sbgn - * Should the converter use SBGN standard - * @param elements - * collection of {@link CellDesignerElement cell designer elements} - * parsed from xml + * + * @param sbgn Should the converter use SBGN standard + * @param elements collection of {@link CellDesignerElement cell designer elements} + * parsed from xml */ public ReactionToXml(final CellDesignerElementCollection elements, final boolean sbgn) { this.elements = elements; @@ -109,9 +103,8 @@ public class ReactionToXml { /** * Transform reaction into CellDesigner xml representation. - * - * @param reaction - * reaction to transform + * + * @param reaction reaction to transform * @return xml representation of reaction */ public String toXml(final Reaction reaction) throws InconsistentModelException { @@ -160,9 +153,8 @@ public class ReactionToXml { /** * Returns xml node with list of modification. - * - * @param reaction - * reaction for which list is generated + * + * @param reaction reaction for which list is generated * @return xml node with list of modification */ private String getListOfModificationsXmlStringForReaction(final Reaction reaction) throws InconsistentModelException { @@ -202,9 +194,8 @@ public class ReactionToXml { /** * Returns SBML node with list of modifications. - * - * @param reaction - * reaction for which list is generated + * + * @param reaction reaction for which list is generated * @return SBML node with list of modifications */ private String getSbmlListOfModificationsXmlStringForReaction(final Reaction reaction) { @@ -222,9 +213,8 @@ public class ReactionToXml { /** * Creates modifierSpeciesReference SBML node for given modifier. - * - * @param modifier - * modifier to be transformed + * + * @param modifier modifier to be transformed * @return modifierSpeciesReference SBML node for given modifier */ private String getModifierReferenceXmlString(final Modifier modifier) { @@ -258,9 +248,8 @@ public class ReactionToXml { /** * Creates xml node for given modifier operator. - * - * @param modifierOperator - * modifier operator to be transformed + * + * @param modifierOperator modifier operator to be transformed * @return xml node for given modifier operator */ private String getModifierXmlString(final NodeOperator modifierOperator) { @@ -306,7 +295,7 @@ public class ReactionToXml { sb.append("\""); sb.append(">\n"); - PolylineData[] lines = new PolylineData[] { modifierOperator.getLine() }; + PolylineData[] lines = new PolylineData[]{modifierOperator.getLine()}; sb.append(getConnectSchemeXmlStringForLines(lines)); sb.append(getLineXmlStringForLines(modifierOperator.getLine())); @@ -317,11 +306,9 @@ public class ReactionToXml { /** * Creates xml node for given modifier. - * - * @param modifier - * modifier to be transformed - * @param gate - * operator to which modifier is connected (if any) + * + * @param modifier modifier to be transformed + * @param gate operator to which modifier is connected (if any) * @return xml node for given modifier */ private String getModifierXmlString(final Modifier modifier, final NodeOperator gate) throws InconsistentModelException { @@ -367,7 +354,7 @@ public class ReactionToXml { } sb.append(">\n"); - PolylineData[] lines = new PolylineData[] { modifier.getLine() }; + PolylineData[] lines = new PolylineData[]{modifier.getLine()}; sb.append(getConnectSchemeXmlStringForLines(lines)); sb.append(getLinkTargetXmlString(modifier)); @@ -378,37 +365,34 @@ public class ReactionToXml { } private String getLineXmlStringForLines(final PolylineData line) { - StringBuilder sb = new StringBuilder(); - sb.append("<celldesigner:line "); - sb.append("width=\"" + line.getWidth() + "\" "); - sb.append("color=\"" + XmlParser.colorToString(line.getColor()) + "\" "); - sb.append("type=\"Straight\" "); - sb.append("/>\n"); - return sb.toString(); + String sb = "<celldesigner:line " + + "width=\"" + line.getWidth() + "\" " + + "color=\"" + XmlParser.colorToString(line.getColor()) + "\" " + + "type=\"Straight\" " + + "/>\n"; + return sb; } /** * Gets target link string for given modifier. - * - * @param modifier - * modifier to be transformed + * + * @param modifier modifier to be transformed * @return anchor xml node representing modifier connection to reaction */ private String getLinkTargetXmlString(final ReactionNode modifier) { - StringBuilder sb = new StringBuilder(); - sb.append("<celldesigner:linkTarget species=\"" + elements.getElementId(modifier.getElement()) + "\" alias=\"" - + modifier.getElement().getElementId() + "\">\n"); - sb.append(getAnchorXml(modifier.getElement(), modifier.getLine().getStartPoint())); - sb.append("</celldesigner:linkTarget>\n"); + String sb = "<celldesigner:linkTarget species=\"" + + elements.getElementId(modifier.getElement()) + "\" alias=\"" + + modifier.getElement().getElementId() + "\">\n" + + getAnchorXml(modifier.getElement(), modifier.getLine().getStartPoint()) + + "</celldesigner:linkTarget>\n"; - return sb.toString(); + return sb; } /** * Creates SBML node for list of products. - * - * @param reaction - * reaction from which products are taken + * + * @param reaction reaction from which products are taken * @return SBML node representing list of products */ private String getListOfProductsXmlStringForReaction(final Reaction reaction) { @@ -449,9 +433,8 @@ public class ReactionToXml { /** * Creates sbml node for list of reactants. - * - * @param reaction - * reaction from which products are taken + * + * @param reaction reaction from which products are taken * @return sbml node representing list of reactants */ private String getListOfReactantsXmlStringForReaction(final Reaction reaction) { @@ -490,34 +473,31 @@ public class ReactionToXml { /** * Creates annotation xml node for reaction. - * - * @param reaction - * reaction to be processed + * + * @param reaction reaction to be processed * @return xml node representing annotation part */ private String getAnnotationXmlStringForReaction(final Reaction reaction) throws InconsistentModelException { String reactionClassString = getCellDesignerReactionTypeString(reaction); - StringBuilder sb = new StringBuilder(); - sb.append("<annotation>\n"); - sb.append("<celldesigner:extension>\n"); - sb.append("<celldesigner:reactionType>" + reactionClassString + "</celldesigner:reactionType>\n"); - sb.append(getBaseReactantsXmlStringForReaction(reaction)); - sb.append(getBaseProductsXmlStringForReaction(reaction)); - sb.append(getListOfReactantLinksXmlStringForReaction(reaction)); - sb.append(getListOfProductLinksXmlStringForReaction(reaction)); - sb.append(getConnectSchemeXmlStringForReaction(reaction)); - sb.append(getEditPointsXmlStringForReaction(reaction)); - sb.append(getListOfModificationsXmlStringForReaction(reaction)); - sb.append(getListOfGateMembersXmlStringForReaction(reaction)); - - sb.append(getLineXmlStringForLines(reaction.getLine())); XmlAnnotationParser xmlAnnotationParser = new XmlAnnotationParser( - CommonXmlParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); - sb.append("</celldesigner:extension>\n"); - sb.append(xmlAnnotationParser.dataSetToXmlString(reaction.getMiriamData(), reaction.getIdReaction())); - sb.append("</annotation>\n"); - return sb.toString(); + RestAnnotationParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); + String sb = "<annotation>\n" + + "<celldesigner:extension>\n" + + "<celldesigner:reactionType>" + reactionClassString + "</celldesigner:reactionType>\n" + + getBaseReactantsXmlStringForReaction(reaction) + + getBaseProductsXmlStringForReaction(reaction) + + getListOfReactantLinksXmlStringForReaction(reaction) + + getListOfProductLinksXmlStringForReaction(reaction) + + getConnectSchemeXmlStringForReaction(reaction) + + getEditPointsXmlStringForReaction(reaction) + + getListOfModificationsXmlStringForReaction(reaction) + + getListOfGateMembersXmlStringForReaction(reaction) + + getLineXmlStringForLines(reaction.getLine()) + + "</celldesigner:extension>\n" + + xmlAnnotationParser.dataSetToXmlString(reaction.getMiriamData(), reaction.getIdReaction()) + + "</annotation>\n"; + return sb; } String getCellDesignerReactionTypeString(final Reaction reaction) { @@ -564,9 +544,8 @@ public class ReactionToXml { /** * Returns xml node with a list of gate members for reaction. For now only * {@link TwoReactantReactionInterface} is supported. - * - * @param reaction - * reaction for which the xml will be returned + * + * @param reaction reaction for which the xml will be returned * @return xml string with list of gate members for reaction */ private StringBuilder getListOfGateMembersXmlStringForReaction(final Reaction reaction) { @@ -645,9 +624,8 @@ public class ReactionToXml { /** * Creates xml node (listOfProductLinks) with list of products. - * - * @param reaction - * reaction for which list of products is created + * + * @param reaction reaction for which list of products is created * @return xml node (listOfProductLinks) with list of products */ private String getListOfProductLinksXmlStringForReaction(final Reaction reaction) { @@ -666,9 +644,8 @@ public class ReactionToXml { /** * Creates xml node (listOfReactantLinks) with list of reactants. - * - * @param reaction - * reaction for which list of reactants is created + * + * @param reaction reaction for which list of reactants is created * @return xml node (listOfReactantLinks) with list of reactants */ private String getListOfReactantLinksXmlStringForReaction(final Reaction reaction) { @@ -689,63 +666,54 @@ public class ReactionToXml { /** * Creates rectantLink xml node for reactant. - * - * @param reactant - * reactant to be transformed + * + * @param reactant reactant to be transformed * @return xml node describing reactantLink */ private String getReactantLinkXmlString(final Reactant reactant) { Element alias = reactant.getElement(); - StringBuilder sb = new StringBuilder(); - sb.append("<celldesigner:reactantLink "); - sb.append("reactant=\"" + elements.getElementId(alias) + "\" "); - sb.append("alias=\"" + alias.getElementId() + "\" "); - // targetLineIndex is missing (maybe it's unimportant :)) - sb.append(">\n"); - - sb.append(getAnchorXml(alias, reactant.getLine().getStartPoint())); - sb.append(getConnectSchemeXmlStringForLines(new PolylineData[] { reactant.getLine() })); - sb.append(getEditPointsXmlStringForLine(new PolylineData[] { reactant.getLine() }, 0)); - sb.append(getLineXmlStringForLines(reactant.getLine())); - sb.append("</celldesigner:reactantLink>\n"); - return sb.toString(); + String sb = "<celldesigner:reactantLink " + + "reactant=\"" + elements.getElementId(alias) + "\" " + + "alias=\"" + alias.getElementId() + "\" " + // targetLineIndex is missing (maybe it's unimportant :)) + + ">\n" + + getAnchorXml(alias, reactant.getLine().getStartPoint()) + + getConnectSchemeXmlStringForLines(new PolylineData[]{reactant.getLine()}) + + getEditPointsXmlStringForLine(new PolylineData[]{reactant.getLine()}, 0) + + getLineXmlStringForLines(reactant.getLine()) + + "</celldesigner:reactantLink>\n"; + return sb; } /** * Creates productLink xml node for product. - * - * @param product - * product to be transformed + * + * @param product product to be transformed * @return xml node describing productLink */ private String getProductLinkXmlString(final Product product) { Element alias = product.getElement(); - PolylineData[] lines = new PolylineData[] { getLineBeforeTrimming(product) }; - - StringBuilder sb = new StringBuilder(); - sb.append("<celldesigner:productLink "); - sb.append("product=\"" + elements.getElementId(alias) + "\" "); - sb.append("alias=\"" + alias.getElementId() + "\" "); - // targetLineIndex is missing (maybe it's unimportant :)) - sb.append(">\n"); - - sb.append(getAnchorXml(alias, getLineBeforeTrimming(product).getEndPoint())); - - sb.append(getConnectSchemeXmlStringForLines(lines)); - - sb.append(getEditPointsXmlStringForLine(lines, 0)); - sb.append(getLineXmlStringForLines(product.getLine())); - sb.append("</celldesigner:productLink>\n"); - return sb.toString(); + PolylineData[] lines = new PolylineData[]{getLineBeforeTrimming(product)}; + + String sb = "<celldesigner:productLink " + + "product=\"" + elements.getElementId(alias) + "\" " + + "alias=\"" + alias.getElementId() + "\" " + // targetLineIndex is missing (maybe it's unimportant :)) + + ">\n" + + getAnchorXml(alias, getLineBeforeTrimming(product).getEndPoint()) + + getConnectSchemeXmlStringForLines(lines) + + getEditPointsXmlStringForLine(lines, 0) + + getLineXmlStringForLines(product.getLine()) + + "</celldesigner:productLink>\n"; + return sb; } /** * Creates valid xml node with connectScheme for the set of lines. - * - * @param lines - * list of lines to be included in connectScheme. As far as I - * remember only one or three lines could be provided. + * + * @param lines list of lines to be included in connectScheme. As far as I + * remember only one or three lines could be provided. * @return xml node with connectScheme */ String getConnectSchemeXmlStringForLines(final PolylineData[] lines) { @@ -774,13 +742,11 @@ public class ReactionToXml { * Creates * {@link lcsb.mapviewer.converter.model.celldesigner.structure.fields.EditPoints} * structure representing lines in CellDesigner. - * - * @param lines - * lines to be transformed into single - * {@link lcsb.mapviewer.converter.model.celldesigner.structure.fields.EditPoints} - * structure - * @param centerIndex - * where the central line is positioned + * + * @param lines lines to be transformed into single + * {@link lcsb.mapviewer.converter.model.celldesigner.structure.fields.EditPoints} + * structure + * @param centerIndex where the central line is positioned * @return xml node */ private String getEditPointsXmlStringForLine(final PolylineData[] lines, final Integer centerIndex) { @@ -791,15 +757,12 @@ public class ReactionToXml { * Creates * {@link lcsb.mapviewer.converter.model.celldesigner.structure.fields.EditPoints} * structure representing lines in CellDesigner. - * - * @param lines - * lines to be transformed into single - * {@link lcsb.mapviewer.converter.model.celldesigner.structure.fields.EditPoints} - * structure - * @param centerPoint - * central point when list of lines is greater than 1 - * @param centerIndex - * where the central line is positioned + * + * @param lines lines to be transformed into single + * {@link lcsb.mapviewer.converter.model.celldesigner.structure.fields.EditPoints} + * structure + * @param centerPoint central point when list of lines is greater than 1 + * @param centerIndex where the central line is positioned * @return xml node */ private String getEditPointsXmlStringForLine(final PolylineData[] lines, final Point2D centerPoint, final Integer centerIndex) { @@ -851,12 +814,9 @@ public class ReactionToXml { * Returns xml node representing * {@link lcsb.mapviewer.converter.model.celldesigner.structure.fields.EditPoints} * structure. - * - * @param reaction - * reaction for which xml node is generated - * @return xml node representing - * {@link lcsb.mapviewer.converter.model.celldesigner.structure.fields.EditPoints} - * structure + * + * @param reaction reaction for which xml node is generated + * @return xml node representing {@link lcsb.mapviewer.converter.model.celldesigner.structure.fields.EditPoints} structure */ String getEditPointsXmlStringForReaction(final Reaction reaction) { if (getCellDesignerReactionTypeString(reaction).equals("BOOLEAN_LOGIC_GATE")) { @@ -896,6 +856,7 @@ public class ReactionToXml { for (final AbstractNode node : operator.getOutputs()) { if (!(node instanceof Product)) { process = false; + break; } } if (process) { @@ -920,7 +881,7 @@ public class ReactionToXml { Point2D centerPoint = pointTransformation.getCoordinatesInCellDesignerBase(pointA, pointB, pointC, pointO); - return getEditPointsXmlStringForLine(new PolylineData[] { line1.reverse(), line2, line3 }, centerPoint, index); + return getEditPointsXmlStringForLine(new PolylineData[]{line1.reverse(), line2, line3}, centerPoint, index); } private String getEditPointsXmlStringForTwoReactantReaction(final Reaction reaction) { @@ -935,6 +896,7 @@ public class ReactionToXml { for (final AbstractNode node : operator.getInputs()) { if (!(node instanceof Reactant)) { process = false; + break; } } if (process) { @@ -970,7 +932,7 @@ public class ReactionToXml { Point2D centerPoint = pointTransformation.getCoordinatesInCellDesignerBase(pointA, pointB, pointC, pointO); return getEditPointsXmlStringForLine( - new PolylineData[] { line1.reverse(), line2.reverse(), line3.reverse().reverse() }, centerPoint, + new PolylineData[]{line1.reverse(), line2.reverse(), line3.reverse().reverse()}, centerPoint, line3.getLines().size() - product.getLine().getLines().size()); } @@ -978,7 +940,7 @@ public class ReactionToXml { Reactant r = reaction.getReactants().get(0); Point2D centerPoint = r.getLine().getEndPoint(); return getEditPointsXmlStringForLine( - new PolylineData[] { reaction.getProducts().get(0).getLine() }, centerPoint, + new PolylineData[]{reaction.getProducts().get(0).getLine()}, centerPoint, 0); } @@ -1012,7 +974,7 @@ public class ReactionToXml { PolylineData pd = new PolylineData(points); pd.setStartPoint(getAnchorPoint(reactant.getElement(), reactant.getLine().getStartPoint())); pd.setEndPoint(getAnchorPoint(product.getElement(), productLine.getEndPoint())); - return getEditPointsXmlStringForLine(new PolylineData[] { pd }, centerPosition); + return getEditPointsXmlStringForLine(new PolylineData[]{pd}, centerPosition); } private Point2D getAnchorPoint(final Element element, final Point2D originalPoint) { @@ -1024,9 +986,8 @@ public class ReactionToXml { /** * Creates valid xml node with connectScheme for the reaction. - * - * @param reaction - * reaction for which the connectSchema is going to be created + * + * @param reaction reaction for which the connectSchema is going to be created * @return xml node with connectScheme */ String getConnectSchemeXmlStringForReaction(final Reaction reaction) { @@ -1086,9 +1047,8 @@ public class ReactionToXml { /** * Returns xml node with list of base products. - * - * @param reaction - * reaction for which the node is created + * + * @param reaction reaction for which the node is created * @return xml node with list of base products */ private String getBaseProductsXmlStringForReaction(final Reaction reaction) { @@ -1116,9 +1076,8 @@ public class ReactionToXml { /** * Returns xml node with list of base reactants. - * - * @param reaction - * reaction for which the node is created + * + * @param reaction reaction for which the node is created * @return xml node with list of base reactants */ private String getBaseReactantsXmlStringForReaction(final Reaction reaction) { @@ -1150,12 +1109,10 @@ public class ReactionToXml { /** * Returns xml node that describes anchor point. - * - * @param alias - * alias on which we are looking for anchor - * @param point - * point on the alias that should be aligned to the closest anchor - * point + * + * @param alias alias on which we are looking for anchor + * @param point point on the alias that should be aligned to the closest anchor + * point * @return xml node with anchor point */ private String getAnchorXml(final Element alias, final Point2D point) { diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/AbstractElementXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/AbstractElementXmlParser.java index 0ca1fe6f73..afd8025635 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/AbstractElementXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/AbstractElementXmlParser.java @@ -1,32 +1,28 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import java.util.ArrayList; -import java.util.List; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerParserException; -import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerElement; import lcsb.mapviewer.model.map.InconsistentModelException; import lcsb.mapviewer.model.map.species.Element; +import lcsb.mapviewer.utils.RestAnnotationParser; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import java.util.ArrayList; +import java.util.List; /** * Abstract class with the interface to parse element in CellDesigner file. - * + * + * @param <T> type of the CellDesigner object to parse + * @param <S> type of the model object to be obtained * @author Piotr Gawron - * - * @param <T> - * type of the CellDesigner object to parse - * @param <S> - * type of the model object to be obtained */ public abstract class AbstractElementXmlParser<T extends CellDesignerElement<?>, S extends Element> { @@ -36,13 +32,13 @@ public abstract class AbstractElementXmlParser<T extends CellDesignerElement<?>, * List of special strings in CellDesigner that should be translated into some * UTF characters. */ - private List<Pair<String, String>> encodedStrings = new ArrayList<>(); + private final List<Pair<String, String>> encodedStrings = new ArrayList<>(); /** * Parser of the notes that allows to extract additional structured data for * the object. */ - private RestAnnotationParser rap = new RestAnnotationParser(); + private final RestAnnotationParser rap = new RestAnnotationParser(); /** * Default constructor. @@ -110,29 +106,21 @@ public abstract class AbstractElementXmlParser<T extends CellDesignerElement<?>, * Returns a {@link Pair} containing CellDesigner identifier in * {@link Pair#getLeft()} and element in {@link Pair#getRight()}. * - * @param node - * xml node be parsed - * @return {@link Pair} containing CellDesigner identifier in - * {@link Pair#getLeft()} and element parsed from xml node in - * {@link Pair#getRight()}. - * @throws InvalidXmlSchemaException - * thrown when xml is invalid + * @param node xml node be parsed + * @return {@link Pair} containing CellDesigner identifier in {@link Pair#getLeft()} and element parsed from xml node in {@link Pair#getRight()}. + * @throws InvalidXmlSchemaException thrown when xml is invalid */ public abstract Pair<String, T> parseXmlElement(final Node node) throws InvalidXmlSchemaException, CellDesignerParserException; /** - * Parses CellDEsigner xml node that is given as a plain text into element. + * Parses CellDesigner xml node that is given as a plain text into element. * Returns a {@link Pair} containing CellDesigner identifier in * {@link Pair#getLeft()} and element in {@link Pair#getRight()}. - * - * @param xmlString - * node to parse - * @return {@link Pair} containing CellDesigner identifier in - * {@link Pair#getLeft()} and element parsed from xml node in - * {@link Pair#getRight()}. - * @throws InvalidXmlSchemaException - * thrown when xmlString is invalid + * + * @param xmlString node to parse + * @return {@link Pair} containing CellDesigner identifier in {@link Pair#getLeft()} and element parsed from xml node in {@link Pair#getRight()}. + * @throws InvalidXmlSchemaException thrown when xmlString is invalid */ public Pair<String, T> parseXmlElement(final String xmlString) throws InvalidXmlSchemaException, CellDesignerParserException { @@ -143,22 +131,19 @@ public abstract class AbstractElementXmlParser<T extends CellDesignerElement<?>, /** * Method transforms element into CellDesigner xml string. - * - * @param element - * object to be transformed + * + * @param element object to be transformed * @return CellDesigner xml string representing element - * @throws InconsistentModelException - * thrown when xml cannot be generated because structure of objects - * is invalid + * @throws InconsistentModelException thrown when xml cannot be generated because structure of objects + * is invalid */ public abstract String toXml(S element) throws InconsistentModelException; /** * This method decodes CellDesigner string with all known CellDesigner special * tokens. - * - * @param name - * string to be decoded + * + * @param name string to be decoded * @return decoded string */ protected String decodeName(final String name) { @@ -171,9 +156,8 @@ public abstract class AbstractElementXmlParser<T extends CellDesignerElement<?>, /** * This method encodes {@link String} using CellDesigner special tokens. - * - * @param name - * string to be decoded + * + * @param name string to be decoded * @return decoded string */ protected String encodeName(final String name) { 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 7ee2005cbe..4c1da26a41 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 @@ -4,10 +4,7 @@ import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; -import lcsb.mapviewer.converter.model.celldesigner.CommonXmlParser; -import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerAntisenseRna; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerElement; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerGene; @@ -23,6 +20,8 @@ import lcsb.mapviewer.model.map.species.Gene; import lcsb.mapviewer.model.map.species.Protein; import lcsb.mapviewer.model.map.species.Rna; import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.utils.RestAnnotationParser; +import lcsb.mapviewer.utils.XmlAnnotationParser; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.w3c.dom.Node; @@ -128,7 +127,7 @@ public class SpeciesCollectionXmlParser { rnaParser = new RnaXmlParser(elements); geneParser = new GeneXmlParser(elements); antisenseRnaParser = new AntisenseRnaXmlParser(elements); - xap = new XmlAnnotationParser(CommonXmlParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); + xap = new XmlAnnotationParser(lcsb.mapviewer.utils.RestAnnotationParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); } /** 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 6edd9a584b..77d3d0a6e5 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 @@ -6,10 +6,7 @@ import lcsb.mapviewer.common.comparator.DoubleComparator; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; -import lcsb.mapviewer.converter.model.celldesigner.CommonXmlParser; -import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerAntisenseRna; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerCompartment; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerComplexSpecies; @@ -37,6 +34,8 @@ import lcsb.mapviewer.model.map.species.Rna; import lcsb.mapviewer.model.map.species.Species; import lcsb.mapviewer.model.map.species.field.ModificationState; import lcsb.mapviewer.model.map.species.field.PositionToCompartment; +import lcsb.mapviewer.utils.RestAnnotationParser; +import lcsb.mapviewer.utils.XmlAnnotationParser; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -234,7 +233,7 @@ public class SpeciesSbmlParser extends AbstractElementXmlParser<CellDesignerSpec if (rdfNode != null) { final XmlAnnotationParser xmlAnnotationParser = new XmlAnnotationParser( - CommonXmlParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); + RestAnnotationParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); species.addMiriamData(xmlAnnotationParser.parseRdfNode(rdfNode, new LogMarker(ProjectLogEntryType.PARSING_ISSUE, species.getClass().getSimpleName(), species.getElementId(), ""))); } @@ -325,7 +324,7 @@ public class SpeciesSbmlParser extends AbstractElementXmlParser<CellDesignerSpec builder.append("</celldesigner:extension>\n"); final XmlAnnotationParser xmlAnnotationParser = new XmlAnnotationParser( - CommonXmlParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); + RestAnnotationParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); builder.append(xmlAnnotationParser.dataSetToXmlString(species.getMiriamData(), elements.getElementId(species))); builder.append("</annotation>\n"); 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 9b9e082d38..b72982513f 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 @@ -5,10 +5,11 @@ import lcsb.mapviewer.common.comparator.PointComparator; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.InvalidInputDataExecption; -import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; import lcsb.mapviewer.model.graphics.LineType; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.BioEntity; +import lcsb.mapviewer.model.map.MiriamData; +import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.kinetics.SbmlKinetics; import lcsb.mapviewer.model.map.kinetics.SbmlParameter; @@ -37,6 +38,7 @@ import lcsb.mapviewer.model.map.species.Gene; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.SimpleMolecule; import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.utils.RestAnnotationParser; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -1044,4 +1046,21 @@ public class CellDesignerXmlParserTest extends CellDesignerTestFunctions { assertEquals("", model.getNotes()); } + @Test + public void testMoveAnnotationsFromNotes() throws Exception { + Model model = CellDesignerTestFunctions.getModelForFile("testFiles/copyingAnnotationModel.xml"); + + Set<Element> elements = model.getElements(); + for (final Element element : elements) { + if (element.getName().equals("blabla")) { + assertEquals(2, element.getMiriamData().size()); + element.getMiriamData() + .add(new MiriamData(MiriamType.PUBMED, "12345")); + element.getMiriamData() + .add(new MiriamData(MiriamType.PUBMED, "333666")); + assertEquals(2, element.getMiriamData().size()); + } + assertFalse(element.getNotes().contains("rdf:RDF")); + } + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CopyCommandForCellDesignerFilesTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CopyCommandForCellDesignerFilesTest.java new file mode 100644 index 0000000000..4c4c32c882 --- /dev/null +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CopyCommandForCellDesignerFilesTest.java @@ -0,0 +1,116 @@ +package lcsb.mapviewer.converter.model.celldesigner; + +import lcsb.mapviewer.commands.CopyCommand; +import lcsb.mapviewer.commands.CreateHierarchyCommand; +import lcsb.mapviewer.model.Project; +import lcsb.mapviewer.model.map.kinetics.SbmlFunction; +import lcsb.mapviewer.model.map.kinetics.SbmlParameter; +import lcsb.mapviewer.model.map.model.Model; +import lcsb.mapviewer.model.map.model.ModelComparator; +import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.species.Element; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +public class CopyCommandForCellDesignerFilesTest extends CellDesignerTestFunctions { + + private final ModelComparator comparator = new ModelComparator(); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + private final int counter = 0; + + @Test + public void testCopyModel() throws Exception { + Model model = getModelForFile("testFiles/sample.xml"); + Model copy = new CopyCommand(model).execute(); + + assertEquals(0, comparator.compare(model, copy)); + } + + @Test + public void testCopyModelWithKinetics() throws Exception { + Model model = getModelForFile("testFiles/kinetics_with_compartment.xml"); + Model copy = new CopyCommand(model).execute(); + + assertEquals(0, comparator.compare(model, copy)); + for (final Reaction reaction : copy.getReactions()) { + if (reaction.getKinetics() != null) { + for (final Element element : reaction.getKinetics().getElements()) { + assertTrue("Element in the copy doesn't belong to copy", copy.getElements().contains(element)); + } + for (final SbmlFunction function : reaction.getKinetics().getFunctions()) { + assertTrue("Function in the copy doesn't belong to copy", copy.getFunctions().contains(function)); + } + for (final SbmlParameter parameter : reaction.getKinetics().getParameters()) { + if (parameter.getParameterId().equals("k2")) { + assertTrue("Global parameter in the function copy doesn't belong to copy", + copy.getParameters().contains(parameter)); + } + } + } + } + } + + @Test + public void testCopyModel3() throws Exception { + Model model = getModelForFile("testFiles/complex_with_state.xml"); + + Model copy = new CopyCommand(model).execute(); + + Model copy2 = serializeModel(copy); + + // check if after conversion to xml everything works + assertEquals(0, comparator.compare(copy, copy2)); + } + + @Test + public void testCopyModel4() throws Exception { + Model model = getModelForFile("testFiles/problematic_description.xml"); + + Model copy = new CopyCommand(model).execute(); + + Model copy2 = serializeModel(copy); + + // check if after conversion to xml everything works + assertEquals(0, comparator.compare(copy, copy2)); + } + + @Test + public void testCopyModelWithArtificialAliases() throws Exception { + Model model = getModelForFile("testFiles/artifitial_compartments.xml"); + new CreateHierarchyCommand(model, 2, 2).execute(); + + Model copy = new CopyCommand(model).execute(); + + Model copy2 = serializeModel(copy); + + new CreateHierarchyCommand(copy2, 2, 2).execute(); + + // check if after conversion to xml everything works + assertEquals(0, comparator.compare(copy, copy2)); + } + + @Test + public void testCopyModelWithProject() throws Exception { + Model originalModel = getModelForFile("testFiles/sample.xml"); + Project project = new Project(); + project.addModel(originalModel); + + Model colorModel = new CopyCommand(originalModel).execute(); + + assertNotEquals(originalModel.getProject(), colorModel.getProject()); + } + +} diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CreateHierarchyCommandForProblematicCDTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CreateHierarchyCommandForProblematicCDTest.java new file mode 100644 index 0000000000..b09534c889 --- /dev/null +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CreateHierarchyCommandForProblematicCDTest.java @@ -0,0 +1,300 @@ +package lcsb.mapviewer.converter.model.celldesigner; + +import lcsb.mapviewer.commands.CreateHierarchyCommand; +import lcsb.mapviewer.common.exception.InvalidStateException; +import lcsb.mapviewer.converter.ConverterParams; +import lcsb.mapviewer.model.map.compartment.Compartment; +import lcsb.mapviewer.model.map.compartment.PathwayCompartment; +import lcsb.mapviewer.model.map.model.Model; +import lcsb.mapviewer.model.map.species.Element; +import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.modelutils.map.ElementUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class CreateHierarchyCommandForProblematicCDTest extends CellDesignerTestFunctions { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testCyclicComplexes() throws Exception { + Model model = getModelForFile("testFiles/cyclic_hierarchy_problem.xml"); + + new CreateHierarchyCommand(model, 8, 80).execute(); + + Species alias = model.getElementByElementId("sa5033"); + + Set<Element> parents = new HashSet<Element>(); + while (alias.getComplex() != null) { + assertFalse("Cyclic nesting", parents.contains(alias.getComplex())); + alias = alias.getComplex(); + parents.add(alias); + } + + Set<String> levels = new HashSet<>(); + for (final Element a : model.getElements()) { + levels.add(a.getVisibilityLevel()); + } + assertTrue(levels.size() > 2); + } + + @Test + public void testCreateHierarchy() throws Exception { + Model model = getModelForFile("testFiles/artifitial_compartments.xml"); + + new CreateHierarchyCommand(model, 2, 2).execute(); + // check if second call will throw an exception... + new CreateHierarchyCommand(model, 2, 2).execute(); + } + + @Test + public void testCreateHierarchy2() throws Exception { + Model model = getModelForFile("testFiles/artifitial_compartments.xml"); + + new CreateHierarchyCommand(model, 2, 2).execute(); + + boolean artifitial = false; + for (final Compartment a : model.getCompartments()) { + if (a instanceof PathwayCompartment) { + artifitial = true; + break; + } + } + assertTrue("No hierarchical structure element found", artifitial); + } + + @Test + public void testRecreateHierachy() throws Exception { + Model model = getModelForFile("testFiles/artifitial_compartments.xml"); + + int aliasSize0 = model.getCompartments().size(); + + new CreateHierarchyCommand(model, 2, 2).execute(); + + int aliasSize = model.getCompartments().size(); + + assertTrue(aliasSize0 != aliasSize); + new CreateHierarchyCommand(model, 2, 2).execute(); + + int aliasSize2 = model.getCompartments().size(); + + assertEquals(aliasSize, aliasSize2); + } + + @Test + public void testParenting() throws Exception { + Model model = getModelForFile("testFiles/artifitial_compartments.xml"); + + new CreateHierarchyCommand(model, 2, 2).execute(); + + assertFalse(model.getElementByElementId("sa1").getCompartment() instanceof PathwayCompartment); + } + + @Test + public void testCreateComponentsMinVisibility() throws Exception { + double zoomFactor = 39.0625; + int levels = 6; + + Model model = getModelForFile("testFiles/other_full/GSTP1 subnetwork_220214.xml"); + + new CreateHierarchyCommand(model, levels, zoomFactor).execute(); + + for (final Compartment compartment : model.getCompartments()) { + if (compartment.getCompartment() == null) { + int visibilityLevel = Integer.valueOf(compartment.getVisibilityLevel()); + assertTrue("Alias " + compartment.getElementId() + " is not visible at levels highers than " + + compartment.getVisibilityLevel(), visibilityLevel <= 1); + } + } + + for (final Species species : model.getSpeciesList()) { + if (species.getCompartment() == null) { + int visibilityLevel = Integer.valueOf(species.getVisibilityLevel()); + assertTrue("Alias " + species.getElementId() + " is not visible at levels highers than " + + species.getVisibilityLevel(), visibilityLevel <= 1); + } + } + } + + @Test + public void testCreateComponentsMaxVisibility() throws Exception { + double zoomFactor = 39.0625; + int levels = 6; + + Model model = getModelForFile("testFiles/other_full/GSTP1 subnetwork_220214.xml"); + + new CreateHierarchyCommand(model, levels, zoomFactor).execute(); + + for (final Element element : model.getElements()) { + int visibilityLevel = Integer.valueOf(element.getVisibilityLevel()); + assertTrue("Alias " + element.getElementId() + " is not visible even at the bottom level (visibility: " + + element.getVisibilityLevel() + ") ", visibilityLevel <= levels); + } + } + + @Test + public void testCompactComplexesInNestedView() throws Exception { + Model model = getModelForFile("testFiles/problematic/compact_complex_view_problem.xml"); + Element alias = model.getElementByElementId("sa1"); + Object parent1 = alias.getCompartment(); + new CreateHierarchyCommand(model, 3, 16).execute(); + Object parent2 = alias.getCompartment(); + assertEquals(parent1, parent2); + } + + @Test(expected = InvalidStateException.class) + public void testRecallHierachyCreation() throws Exception { + Model model = getModelForFile("testFiles/artifitial_compartments.xml"); + + CreateHierarchyCommand command = new CreateHierarchyCommand(model, 2, 2); + command.execute(); + command.execute(); + } + + @Test + public void testClear() throws Exception { + Model model = getModelForFile("testFiles/artifitial_compartments.xml"); + + CreateHierarchyCommand command = new CreateHierarchyCommand(model, 2, 2); + command.clean(); + for (final Element alias : model.getElements()) { + assertNull(alias.getCompartment()); + } + for (final Compartment alias : model.getCompartments()) { + assertNull(alias.getCompartment()); + assertTrue(alias.getElements().isEmpty()); + } + } + + @Test + public void testNestedProblem() throws Exception { + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = parser + .createModel(new ConverterParams().filename("testFiles/nested_test.xml").sizeAutoAdjust(true)); + + double zoomFactor = Math.max(model.getHeight(), model.getWidth()) / (256); + int zoomLevels = (int) Math.ceil(Math.log(zoomFactor) / Math.log(2)); + + CreateHierarchyCommand command = new CreateHierarchyCommand(model, zoomLevels, zoomFactor); + command.execute(); + + for (final Element alias : model.getElements()) { + Element parentAlias = alias.getCompartment(); + if (parentAlias != null) { + int parentVisibilityLevel = Integer.valueOf(parentAlias.getVisibilityLevel()); + int aliasVisibilityLevel = Integer.valueOf(alias.getVisibilityLevel()); + assertTrue(aliasVisibilityLevel >= parentVisibilityLevel); + } + if (alias instanceof Species) { + parentAlias = ((Species) alias).getComplex(); + if (parentAlias != null) { + int parentVisibilityLevel = Integer.valueOf(parentAlias.getVisibilityLevel()); + int aliasVisibilityLevel = Integer.valueOf(alias.getVisibilityLevel()); + assertTrue(aliasVisibilityLevel >= parentVisibilityLevel); + } + } + } + } + + @Test + public void testDisconnectedChildInComplex() throws Exception { + Model model = getModelForFile("testFiles/problematic/disconnected_child_in_complex.xml"); + + new CreateHierarchyCommand(model, 8, 80).execute(); + + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + String xmlString = parser.model2String(model); + + InputStream stream = new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8)); + + parser.createModel(new ConverterParams().inputStream(stream)); + } + + @Test + public void testHierarchyWithCustomSemanticZooming() throws Exception { + Model model = getModelForFile("testFiles/custom_semantic_zooming.xml"); + + Map<Element, String> visibilityLevels = new HashMap<>(); + for (final Element element : model.getElements()) { + if (element.getVisibilityLevel() != null && !element.getVisibilityLevel().isEmpty()) { + visibilityLevels.put(element, element.getVisibilityLevel()); + } + } + + new CreateHierarchyCommand(model, 4, 80).execute(); + + for (final Element element : model.getElements()) { + if (visibilityLevels.get(element) != null) { + assertEquals("Visibility level changed, but shouldn't", visibilityLevels.get(element), + element.getVisibilityLevel()); + } + } + } + + @Test + public void testHierarchyWithCustomSemanticZoomingPathwayLevels() throws Exception { + ElementUtils eu = new ElementUtils(); + Model model = getModelForFile("testFiles/custom_semantic_zooming.xml"); + + Map<Element, String> visibilityLevels = new HashMap<>(); + for (final Element element : model.getElements()) { + if (element.getVisibilityLevel() != null && !element.getVisibilityLevel().isEmpty()) { + visibilityLevels.put(element, element.getVisibilityLevel()); + } + } + + new CreateHierarchyCommand(model, 4, 80).execute(); + + for (final Element element : model.getElements()) { + if (visibilityLevels.get(element) == null) { + int visibilityLevel = Integer.parseInt(element.getVisibilityLevel()); + if (element.getCompartment() != null) { + int parentTransparency = Integer.parseInt(element.getCompartment().getTransparencyLevel()); + assertEquals( + eu.getElementTag(element) + eu.getElementTag(element.getCompartment()) + + "Element should be directly visible when parent is transparent", + parentTransparency, visibilityLevel); + } else if (element instanceof Species) { + int parentTransparency = Integer.parseInt(((Species) element).getComplex().getTransparencyLevel()); + assertEquals( + eu.getElementTag(element) + eu.getElementTag(((Species) element).getComplex()) + + "Element should be directly visible when parent is transparent", + parentTransparency, visibilityLevel); + } + } + } + } + + @Test + public void testLayerWithNotes() throws Exception { + Model model = getModelForFile("testFiles/layer_text_with_notes.xml"); + + new CreateHierarchyCommand(model, 4, 80).execute(); + + PathwayCompartment pathway = (PathwayCompartment) model.getCompartments().get(0); + + assertEquals("test", pathway.getName()); + assertEquals("5", pathway.getVisibilityLevel()); + assertEquals((Integer) 11, pathway.getZ()); + } +} diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ProjectExportTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ProjectExportTest.java index 8b04264dc6..dded4298bd 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ProjectExportTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ProjectExportTest.java @@ -2,18 +2,18 @@ package lcsb.mapviewer.converter.model.celldesigner; import lcsb.mapviewer.converter.ComplexZipConverter; import lcsb.mapviewer.converter.ComplexZipConverterParams; -import lcsb.mapviewer.converter.ConverterException; -import lcsb.mapviewer.converter.InvalidInputDataExecption; import lcsb.mapviewer.converter.ProjectFactory; import lcsb.mapviewer.converter.zip.ZipEntryFile; import lcsb.mapviewer.converter.zip.ZipEntryFileFactory; import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.ProjectComparator; -import lcsb.mapviewer.model.map.InconsistentModelException; +import lcsb.mapviewer.model.map.model.ElementSubmodelConnection; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelData; import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; import lcsb.mapviewer.model.map.model.SubmodelType; +import lcsb.mapviewer.model.map.species.Element; +import lcsb.mapviewer.model.map.species.Protein; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -70,7 +70,24 @@ public class ProjectExportTest extends CellDesignerTestFunctions { testSerializationOverZip(project); } - private void testSerializationOverZip(final Project project) throws IOException, ConverterException, InconsistentModelException, InvalidInputDataExecption { + @Test + public void testLinkToSubmodel() throws Exception { + Project project = createProject(); + Model model = createEmptyModel(); + model.setWidth(260); + Protein protein = createProtein(); + model.addElement(protein); + project.addModel(model); + + Model model2 = createEmptyModel(); + project.addModel(model2); + model.addSubmodelConnection(new ModelSubmodelConnection(model2, SubmodelType.UNKNOWN, model2.getName())); + protein.setSubmodel(new ElementSubmodelConnection(model2, SubmodelType.DOWNSTREAM_TARGETS, model2.getName())); + + testSerializationOverZip(project); + } + + private void testSerializationOverZip(final Project project) throws Exception { File tempFile = File.createTempFile("CD-", ".zip"); try (FileOutputStream outputStream = new FileOutputStream(tempFile)) { byte[] data = projectFactory.project2zip(project); @@ -84,6 +101,10 @@ public class ProjectExportTest extends CellDesignerTestFunctions { } for (ModelData model : project2.getModels()) { clearModelFromZ(model); + + for (Element element : model.getElements()) { + logger.debug(element.getSubmodel()); + } } assertEquals(0, projectComparator.compare(project, project2)); diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/SubModelCommandTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/SubModelCommandForCellDesignerFilesTest.java similarity index 87% rename from model-command/src/test/java/lcsb/mapviewer/commands/SubModelCommandTest.java rename to converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/SubModelCommandForCellDesignerFilesTest.java index 4086e83e14..4fc3887937 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/SubModelCommandTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/SubModelCommandForCellDesignerFilesTest.java @@ -1,25 +1,26 @@ -package lcsb.mapviewer.commands; +package lcsb.mapviewer.converter.model.celldesigner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import lcsb.mapviewer.commands.MoveCommand; +import lcsb.mapviewer.commands.SubModelCommand; +import lcsb.mapviewer.model.map.layout.graphics.Layer; +import lcsb.mapviewer.model.map.layout.graphics.LayerText; +import lcsb.mapviewer.model.map.model.Model; +import lcsb.mapviewer.model.map.model.ModelComparator; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import java.awt.geom.Path2D; import java.awt.geom.Rectangle2D; -import java.util.Arrays; +import java.util.Collections; import java.util.HashSet; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import lcsb.mapviewer.model.map.layout.graphics.Layer; -import lcsb.mapviewer.model.map.layout.graphics.LayerText; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelComparator; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; -public class SubModelCommandTest extends CommandTestFunctions { +public class SubModelCommandForCellDesignerFilesTest extends CellDesignerTestFunctions { - private ModelComparator comparator = new ModelComparator(); + private final ModelComparator comparator = new ModelComparator(); @Before public void setUp() throws Exception { @@ -31,7 +32,7 @@ public class SubModelCommandTest extends CommandTestFunctions { @Test public void testGetSubmodel1() throws Exception { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", true); + Model model = getModelForFile("testFiles/spliting_test_Case.xml"); Path2D polygon = new Path2D.Double(); polygon.moveTo(0, 0); @@ -48,7 +49,7 @@ public class SubModelCommandTest extends CommandTestFunctions { @Test public void testGetSubmodel2() throws Exception { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", true); + Model model = getModelForFile("testFiles/spliting_test_Case.xml"); Path2D polygon = new Path2D.Double(); polygon.moveTo(50, 50); @@ -65,7 +66,7 @@ public class SubModelCommandTest extends CommandTestFunctions { @Test public void testGetSubmodelWithDisableStrictCutoof() throws Exception { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", true); + Model model = getModelForFile("testFiles/spliting_test_Case.xml"); Path2D polygon = new Path2D.Double(); polygon.moveTo(50, 50); @@ -82,7 +83,7 @@ public class SubModelCommandTest extends CommandTestFunctions { @Test public void testGetSubmodel3() throws Exception { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", true); + Model model = getModelForFile("testFiles/spliting_test_Case.xml"); Path2D polygon = new Path2D.Double(); polygon.moveTo(0, 200); @@ -108,7 +109,7 @@ public class SubModelCommandTest extends CommandTestFunctions { assertEquals(model.getReactionByReactionId("re3").getLines().get(0).getY2(), copy.getReactionByReactionId("re3").getLines().get(0).getY2() - dy, EPSILON); - Model copy2 = serializeViaCellDesigner(copy); + Model copy2 = serializeModel(copy); // check if after conversion to xml everything works assertEquals(0, comparator.compare(copy, copy2)); @@ -116,7 +117,7 @@ public class SubModelCommandTest extends CommandTestFunctions { @Test public void testGetSubmodelWithoutCompartments() throws Exception { - Model model = getModelForFile("testFiles/compartments.xml", true); + Model model = getModelForFile("testFiles/compartments.xml"); Path2D polygon = new Path2D.Double(); polygon.moveTo(0, 10); @@ -128,13 +129,13 @@ public class SubModelCommandTest extends CommandTestFunctions { Model copy = new SubModelCommand(model, polygon).execute(); // we should cut off some of compartments - assertFalse(model.getLayers().iterator().next().getTexts().size() == copy.getLayers().iterator().next().getTexts() + assertNotEquals(model.getLayers().iterator().next().getTexts().size(), copy.getLayers().iterator().next().getTexts() .size()); } @Test public void testGetSubmodelWithoutCompartments2() throws Exception { - Model model = getModelForFile("testFiles/problematic/cutting_without_compartment.xml", true); + Model model = getModelForFile("testFiles/problematic/cutting_without_compartment.xml"); Path2D polygon = new Path2D.Double(); polygon.moveTo(0, 0); @@ -145,14 +146,14 @@ public class SubModelCommandTest extends CommandTestFunctions { Model copy = new SubModelCommand(model, polygon).execute(); - Model model2 = serializeViaCellDesigner(copy); + Model model2 = serializeModel(copy); assertEquals(0, comparator.compare(copy, model2)); } @Test public void testGetSubmodelWithElementIds() throws Exception { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); + Model model = getModelForFile("testFiles/spliting_test_Case.xml"); Path2D polygon = new Path2D.Double(); polygon.moveTo(0, 0); @@ -162,7 +163,7 @@ public class SubModelCommandTest extends CommandTestFunctions { polygon.closePath(); model.getElementByElementId("sa2").setId(-2); - Model copy = new SubModelCommand(model, polygon, new HashSet<>(Arrays.asList(-2)), new HashSet<>()).execute(); + Model copy = new SubModelCommand(model, polygon, new HashSet<>(Collections.singletonList(-2)), new HashSet<>()).execute(); assertEquals(1, copy.getElements().size()); assertEquals(0, copy.getReactions().size()); @@ -170,7 +171,7 @@ public class SubModelCommandTest extends CommandTestFunctions { @Test public void testGetSubmodelWithElementIdsAndTextArea() throws Exception { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); + Model model = getModelForFile("testFiles/spliting_test_Case.xml"); Path2D polygon = new Path2D.Double(); polygon.moveTo(0, 0); @@ -185,7 +186,7 @@ public class SubModelCommandTest extends CommandTestFunctions { layer.addLayerText(text); model.addLayer(layer); - Model copy = new SubModelCommand(model, polygon, new HashSet<>(Arrays.asList(-2)), new HashSet<>()).execute(); + Model copy = new SubModelCommand(model, polygon, new HashSet<>(Collections.singletonList(-2)), new HashSet<>()).execute(); assertEquals(1, copy.getElements().size()); assertEquals(0, copy.getReactions().size()); @@ -195,7 +196,7 @@ public class SubModelCommandTest extends CommandTestFunctions { @Test public void testGetSubmodelWithEmptyElementIds() throws Exception { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", true); + Model model = getModelForFile("testFiles/spliting_test_Case.xml"); Path2D polygon = new Path2D.Double(); polygon.moveTo(0, 0); @@ -212,7 +213,7 @@ public class SubModelCommandTest extends CommandTestFunctions { @Test public void testGetSubmodelWithReactionIds() throws Exception { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); + Model model = getModelForFile("testFiles/spliting_test_Case.xml"); Path2D polygon = new Path2D.Double(); polygon.moveTo(0, 0); @@ -222,7 +223,7 @@ public class SubModelCommandTest extends CommandTestFunctions { polygon.closePath(); model.getReactions().iterator().next().setId(-2); - Model copy = new SubModelCommand(model, polygon, new HashSet<>(), new HashSet<>(Arrays.asList(-2)), true).execute(); + Model copy = new SubModelCommand(model, polygon, new HashSet<>(), new HashSet<>(Collections.singletonList(-2)), true).execute(); assertEquals(1, copy.getReactions().size()); } diff --git a/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlExporter.java b/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlExporter.java index 62c8aadb93..8584db5f3c 100644 --- a/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlExporter.java +++ b/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlExporter.java @@ -4,7 +4,6 @@ import lcsb.mapviewer.common.comparator.DoubleComparator; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.geometry.ColorParser; import lcsb.mapviewer.converter.ConverterException; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.converter.graphics.bioentity.reaction.ReactionConverter; import lcsb.mapviewer.converter.model.sbgnml.parser.NotesConverter; import lcsb.mapviewer.model.LogMarker; @@ -69,6 +68,7 @@ import lcsb.mapviewer.model.map.species.field.AbstractSiteModification; import lcsb.mapviewer.model.map.species.field.ModificationResidue; import lcsb.mapviewer.model.map.species.field.StructuralState; import lcsb.mapviewer.modelutils.map.ElementUtils; +import lcsb.mapviewer.utils.XmlAnnotationParser; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; diff --git a/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlParser.java b/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlParser.java index c179bc2dcc..5c0f2292db 100644 --- a/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlParser.java +++ b/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlParser.java @@ -3,8 +3,6 @@ package lcsb.mapviewer.converter.model.sbgnml; import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.InvalidInputDataExecption; -import lcsb.mapviewer.converter.ZIndexPopulator; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.converter.model.sbgnml.parser.ElementParser; import lcsb.mapviewer.converter.model.sbgnml.parser.NotesConverter; import lcsb.mapviewer.converter.model.sbgnml.parser.ReactionParser; @@ -22,6 +20,8 @@ import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Complex; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.utils.XmlAnnotationParser; +import lcsb.mapviewer.utils.ZIndexPopulator; import org.apache.commons.io.FilenameUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/parser/ElementParser.java b/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/parser/ElementParser.java index 012543645c..4a21fe5899 100644 --- a/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/parser/ElementParser.java +++ b/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/parser/ElementParser.java @@ -3,7 +3,6 @@ package lcsb.mapviewer.converter.model.sbgnml.parser; import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.geometry.CellDesignerAliasConverter; import lcsb.mapviewer.converter.model.sbgnml.SbgnLogMarker; import lcsb.mapviewer.converter.model.sbgnml.parser.newt.NewtExtension; @@ -32,6 +31,7 @@ import lcsb.mapviewer.model.map.species.field.SpeciesWithModificationResidue; import lcsb.mapviewer.model.map.species.field.SpeciesWithResidue; import lcsb.mapviewer.model.map.species.field.SpeciesWithStructuralState; import lcsb.mapviewer.model.map.species.field.StructuralState; +import lcsb.mapviewer.utils.XmlAnnotationParser; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.sbgn.GlyphClazz; diff --git a/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/parser/NotesConverter.java b/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/parser/NotesConverter.java index 4db5742a0d..199aafcf86 100644 --- a/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/parser/NotesConverter.java +++ b/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/parser/NotesConverter.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.converter.model.sbgnml.parser; import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.converter.model.celldesigner.CommonXmlParser; -import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; +import lcsb.mapviewer.utils.RestAnnotationParser; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.sbgn.bindings.SBGNBase; diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/NotesUtility.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/NotesUtility.java index d1a5d04b3c..5940cbddd4 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/NotesUtility.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/NotesUtility.java @@ -1,8 +1,8 @@ package lcsb.mapviewer.converter.model.sbml; import lcsb.mapviewer.converter.InvalidInputDataExecption; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.model.map.MiriamData; +import lcsb.mapviewer.utils.XmlAnnotationParser; import org.apache.commons.text.StringEscapeUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlBioEntityParser.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlBioEntityParser.java index e59598fdee..c43d706b5f 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlBioEntityParser.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlBioEntityParser.java @@ -3,7 +3,6 @@ package lcsb.mapviewer.converter.model.sbml; import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.InvalidInputDataExecption; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.converter.model.sbml.species.ElementColorEnum; import lcsb.mapviewer.model.LogMarker; import lcsb.mapviewer.model.ProjectLogEntryType; @@ -13,6 +12,7 @@ import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.model.Author; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; +import lcsb.mapviewer.utils.XmlAnnotationParser; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.sbml.jsbml.AbstractNamedSBase; diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlExporter.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlExporter.java index 62f06b1aac..da0478b878 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlExporter.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlExporter.java @@ -2,13 +2,13 @@ package lcsb.mapviewer.converter.model.sbml; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.converter.model.sbml.compartment.SbmlCompartmentExporter; import lcsb.mapviewer.converter.model.sbml.reaction.SbmlReactionExporter; import lcsb.mapviewer.converter.model.sbml.species.SbmlSpeciesExporter; import lcsb.mapviewer.converter.model.sbml.units.SbmlUnitExporter; import lcsb.mapviewer.model.map.InconsistentModelException; import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.utils.XmlAnnotationParser; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlParser.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlParser.java index 5258d5f7ed..6e22fcf407 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlParser.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlParser.java @@ -1,24 +1,5 @@ package lcsb.mapviewer.converter.model.sbml; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.xml.stream.XMLStreamException; - -import org.apache.commons.io.FilenameUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.sbml.jsbml.SBMLDocument; -import org.sbml.jsbml.SBMLReader; -import org.sbml.jsbml.ext.SBasePlugin; -import org.sbml.jsbml.ext.layout.Layout; -import org.sbml.jsbml.ext.layout.LayoutModelPlugin; -import org.sbml.jsbml.ext.multi.MultiModelPlugin; -import org.springframework.stereotype.Component; - import lcsb.mapviewer.commands.CommandExecutionException; import lcsb.mapviewer.commands.layout.ApplySimpleLayoutModelCommand; import lcsb.mapviewer.common.Configuration; @@ -27,7 +8,6 @@ import lcsb.mapviewer.converter.Converter; import lcsb.mapviewer.converter.ConverterException; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.InvalidInputDataExecption; -import lcsb.mapviewer.converter.ZIndexPopulator; import lcsb.mapviewer.converter.model.sbml.compartment.SbmlCompartmentParser; import lcsb.mapviewer.converter.model.sbml.reaction.SbmlReactionParser; import lcsb.mapviewer.converter.model.sbml.species.SbmlSpeciesParser; @@ -45,6 +25,24 @@ import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; import lcsb.mapviewer.model.map.species.field.ModificationResidue; import lcsb.mapviewer.model.map.species.field.SpeciesWithModificationResidue; +import lcsb.mapviewer.utils.ZIndexPopulator; +import org.apache.commons.io.FilenameUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.sbml.jsbml.SBMLDocument; +import org.sbml.jsbml.SBMLReader; +import org.sbml.jsbml.ext.SBasePlugin; +import org.sbml.jsbml.ext.layout.Layout; +import org.sbml.jsbml.ext.layout.LayoutModelPlugin; +import org.sbml.jsbml.ext.multi.MultiModelPlugin; +import org.springframework.stereotype.Component; + +import javax.xml.stream.XMLStreamException; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; @Component public class SbmlParser extends Converter { @@ -52,7 +50,7 @@ public class SbmlParser extends Converter { /** * Default class logger. */ - private static Logger logger = LogManager.getLogger(); + private static final Logger logger = LogManager.getLogger(); private boolean provideDefaults = true; diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GeneratedSbmlValidationTests.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GeneratedSbmlValidationTests.java index d265f40ca6..ab64ae9b16 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GeneratedSbmlValidationTests.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GeneratedSbmlValidationTests.java @@ -1,28 +1,27 @@ package lcsb.mapviewer.converter.model.sbml; -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - import lcsb.mapviewer.commands.layout.ApplySimpleLayoutModelCommand; -import lcsb.mapviewer.converter.ZIndexPopulator; import lcsb.mapviewer.model.map.layout.graphics.Layer; import lcsb.mapviewer.model.map.layout.graphics.LayerText; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.utils.ZIndexPopulator; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +import java.awt.geom.Rectangle2D; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; @RunWith(Parameterized.class) public class GeneratedSbmlValidationTests extends SbmlTestFunctions { - private Model model; + private final Model model; public GeneratedSbmlValidationTests(final Model model, final String name) { this.model = model; @@ -57,7 +56,7 @@ public class GeneratedSbmlValidationTests extends SbmlTestFunctions { private static Object[] createRow(final Model model) { new ZIndexPopulator().populateZIndex(model); - return new Object[] { model, model.getName() }; + return new Object[]{model, model.getName()}; } private static Model createModelWithSingleSpecies() throws Exception { diff --git a/converter/pom.xml b/converter/pom.xml index 79f569c122..942e233f0e 100644 --- a/converter/pom.xml +++ b/converter/pom.xml @@ -1,41 +1,46 @@ <?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <modelVersion>4.0.0</modelVersion> - <parent> - <groupId>lcsb.mapviewer</groupId> - <artifactId>parent</artifactId> - <version>19.0.0~alpha.0</version> - </parent> - - <artifactId>converter</artifactId> - <name>converter</name> - - <dependencies> - <dependency> - <groupId>lcsb.mapviewer</groupId> - <artifactId>model</artifactId> - <version>19.0.0~alpha.0</version> - </dependency> - <dependency> - <groupId>xerces</groupId> - <artifactId>xercesImpl</artifactId> - <version>${xercesImp.version}</version> - </dependency> - <!-- mockito used for testing --> - <dependency> - <groupId>org.mockito</groupId> - <artifactId>mockito-core</artifactId> - <version>${mockito.version}</version> - <scope>test</scope> - </dependency> + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>lcsb.mapviewer</groupId> + <artifactId>parent</artifactId> + <version>19.0.0~alpha.0</version> + </parent> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <version>${junit.version}</version> - <scope>test</scope> - </dependency> - - </dependencies> + <artifactId>converter</artifactId> + <name>converter</name> + + <dependencies> + <dependency> + <groupId>lcsb.mapviewer</groupId> + <artifactId>model</artifactId> + <version>19.0.0~alpha.0</version> + </dependency> + <dependency> + <groupId>lcsb.mapviewer</groupId> + <artifactId>model-command</artifactId> + <version>19.0.0~alpha.0</version> + </dependency> + <dependency> + <groupId>xerces</groupId> + <artifactId>xercesImpl</artifactId> + <version>${xercesImp.version}</version> + </dependency> + <!-- mockito used for testing --> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <version>${mockito.version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>${junit.version}</version> + <scope>test</scope> + </dependency> + + </dependencies> </project> diff --git a/converter/src/main/java/lcsb/mapviewer/converter/ProjectFactory.java b/converter/src/main/java/lcsb/mapviewer/converter/ProjectFactory.java index 812e84783a..b42db99a4b 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/ProjectFactory.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/ProjectFactory.java @@ -1,5 +1,6 @@ package lcsb.mapviewer.converter; +import lcsb.mapviewer.commands.layout.ApplySimpleLayoutModelCommand; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.converter.zip.GlyphZipEntryFile; import lcsb.mapviewer.converter.zip.ImageZipEntryFile; @@ -10,10 +11,19 @@ import lcsb.mapviewer.model.map.InconsistentModelException; import lcsb.mapviewer.model.map.layout.graphics.Glyph; import lcsb.mapviewer.model.map.layout.graphics.Layer; import lcsb.mapviewer.model.map.layout.graphics.LayerText; +import lcsb.mapviewer.model.map.model.ElementSubmodelConnection; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelData; +import lcsb.mapviewer.model.map.model.ModelFullIndexed; import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; +import lcsb.mapviewer.model.map.reaction.Product; +import lcsb.mapviewer.model.map.reaction.Reactant; +import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.type.TransportReaction; +import lcsb.mapviewer.model.map.species.Complex; import lcsb.mapviewer.model.map.species.Element; +import lcsb.mapviewer.model.map.species.GenericProtein; +import lcsb.mapviewer.model.map.species.Species; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -44,6 +54,15 @@ public class ProjectFactory { this.converter = converter; } + private static void addModelFileToZip(final Model model, final String filename, final Converter converter, final ZipOutputStream zos) + throws IOException, InconsistentModelException, ConverterException { + ZipEntry entry = new ZipEntry(filename); + zos.putNextEntry(entry); + String topModelContent = converter.model2String(model); + zos.write(topModelContent.getBytes()); + zos.closeEntry(); + } + public Project create(final ComplexZipConverterParams params) throws InvalidInputDataExecption, ConverterException { return create(params, new Project()); } @@ -164,17 +183,85 @@ public class ProjectFactory { addModelFileToZip(model.getModel(), "submaps/" + model.getName() + "." + converter.getFileExtensions().get(0), converter, zos); } } + Model mapping = createMappingModel(project.getModels()); + + addModelFileToZip(mapping, "submaps/mapping." + converter.getFileExtensions().get(0), converter, zos); + } catch (IOException ioe) { throw new ConverterException(ioe); } return byteArrayOutputStream.toByteArray(); } - private static void addModelFileToZip(final Model model, final String filename, final Converter converter, final ZipOutputStream zos) throws IOException, InconsistentModelException, ConverterException { - ZipEntry entry = new ZipEntry(filename); - zos.putNextEntry(entry); - String topModelContent = converter.model2String(model); - zos.write(topModelContent.getBytes()); - zos.closeEntry(); + private int idCounter = 0; + + private Model createMappingModel(final Set<ModelData> models) { + Model mapping = new ModelFullIndexed(null); + for (ModelData parentModel : models) { + for (Element parentElement : parentModel.getElements()) { + ElementSubmodelConnection connection = parentElement.getSubmodel(); + if (connection != null) { + ModelData childModel = connection.getSubmodel(); + + Complex mappingParentElement = getComplexForConnection(parentModel.getName(), mapping); + + Species sourceElement = getComplexChildForConnection(parentElement.getElementId(), mappingParentElement); + + Complex mappingChildElement = getComplexForConnection(childModel.getName(), mapping); + + Species targetElement; + if (connection.getToElement() != null) { + targetElement = getComplexChildForConnection(connection.getToElement().getElementId(), mappingChildElement); + } else { + targetElement = mappingChildElement; + } + + Reaction reaction = new TransportReaction("re" + idCounter++); + reaction.addReactant(new Reactant(sourceElement)); + reaction.addProduct(new Product(targetElement)); + mapping.addReaction(reaction); + } + } + } + try { + new ApplySimpleLayoutModelCommand(mapping).execute(); + } catch (Exception e) { + logger.error("Problem with preparing mapping file", e); + } + return mapping; + } + + private Species getComplexChildForConnection(final String elementId, final Complex mappingParentElement) { + Species sourceElement = null; + for (Species child : mappingParentElement.getAllChildren()) { + if (child.getName().equals(elementId)) { + sourceElement = child; + } + } + + if (sourceElement == null) { + sourceElement = new GenericProtein("sa" + idCounter++); + sourceElement.setName(elementId); + mappingParentElement.addSpecies(sourceElement); + mappingParentElement.getModel().addElement(sourceElement); + } + return sourceElement; + } + + private Complex getComplexForConnection(final String modelName, final Model mapping) { + List<Element> mappingParentElements = mapping.getElementsByName(modelName); + + Complex mappingParentElement = null; + for (Element mappingElement : mappingParentElements) { + if (mappingElement instanceof Complex) { + mappingParentElement = (Complex) mappingElement; + } + } + if (mappingParentElement == null) { + mappingParentElement = new Complex("ca" + idCounter++); + mappingParentElement.setName(modelName); + mapping.addElement(mappingParentElement); + } + return mappingParentElement; } } diff --git a/converter/src/test/java/lcsb/mapviewer/converter/ZIndexPopulatorTest.java b/converter/src/test/java/lcsb/mapviewer/converter/ZIndexPopulatorTest.java index d64ce0e7a4..2691ea3723 100644 --- a/converter/src/test/java/lcsb/mapviewer/converter/ZIndexPopulatorTest.java +++ b/converter/src/test/java/lcsb/mapviewer/converter/ZIndexPopulatorTest.java @@ -10,6 +10,7 @@ import lcsb.mapviewer.model.map.species.Complex; import lcsb.mapviewer.model.map.species.Protein; import lcsb.mapviewer.model.map.species.Species; import lcsb.mapviewer.model.map.species.field.StructuralState; +import lcsb.mapviewer.utils.ZIndexPopulator; import org.junit.Test; import static org.junit.Assert.assertNotNull; diff --git a/converter/src/test/java/lcsb/mapviewer/converter/annotation/XmlAnnotationParserTest.java b/converter/src/test/java/lcsb/mapviewer/converter/annotation/XmlAnnotationParserTest.java index 5c03c95b12..89ccd70f00 100644 --- a/converter/src/test/java/lcsb/mapviewer/converter/annotation/XmlAnnotationParserTest.java +++ b/converter/src/test/java/lcsb/mapviewer/converter/annotation/XmlAnnotationParserTest.java @@ -5,6 +5,7 @@ import lcsb.mapviewer.converter.ConverterTestFunctions; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamRelationType; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.utils.XmlAnnotationParser; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/model-command/pom.xml b/model-command/pom.xml index 0dd05cf739..419bcff884 100644 --- a/model-command/pom.xml +++ b/model-command/pom.xml @@ -1,60 +1,54 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <parent> - <groupId>lcsb.mapviewer</groupId> - <artifactId>parent</artifactId> - <version>19.0.0~alpha.0</version> - </parent> - <artifactId>model-command</artifactId> - <name>Model commands</name> - <description>Tool with (undoable) commands that can be performed on model</description> - - - <dependencies> - - <!-- the MapViewer model --> - <dependency> - <groupId>lcsb.mapviewer</groupId> - <artifactId>model</artifactId> - <version>19.0.0~alpha.0</version> - </dependency> - - - <!-- the MapViewer CellDEsigner converter --> - <dependency> - <groupId>lcsb.mapviewer</groupId> - <artifactId>converter-CellDesigner</artifactId> - <version>19.0.0~alpha.0</version> - </dependency> - - <!-- Log4J2--> - <dependency> - <groupId>org.apache.logging.log4j</groupId> - <artifactId>log4j-api</artifactId> - <version>${log4j2.version}</version> - </dependency> - <dependency> - <groupId>org.apache.logging.log4j</groupId> - <artifactId>log4j-core</artifactId> - <version>${log4j2.version}</version> - </dependency> - - <!-- mockito used for testing --> - <dependency> - <groupId>org.mockito</groupId> - <artifactId>mockito-core</artifactId> - <version>${mockito.version}</version> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <version>${junit.version}</version> - <scope>test</scope> - </dependency> - - - </dependencies> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>lcsb.mapviewer</groupId> + <artifactId>parent</artifactId> + <version>19.0.0~alpha.0</version> + </parent> + <artifactId>model-command</artifactId> + <name>Model commands</name> + <description>Tool with (undoable) commands that can be performed on model</description> + + + <dependencies> + + <!-- the MapViewer model --> + <dependency> + <groupId>lcsb.mapviewer</groupId> + <artifactId>model</artifactId> + <version>19.0.0~alpha.0</version> + </dependency> + + + <!-- Log4J2--> + <dependency> + <groupId>org.apache.logging.log4j</groupId> + <artifactId>log4j-api</artifactId> + <version>${log4j2.version}</version> + </dependency> + <dependency> + <groupId>org.apache.logging.log4j</groupId> + <artifactId>log4j-core</artifactId> + <version>${log4j2.version}</version> + </dependency> + + <!-- mockito used for testing --> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <version>${mockito.version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>${junit.version}</version> + <scope>test</scope> + </dependency> + + + </dependencies> </project> \ No newline at end of file diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/CreateHierarchyCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/CreateHierarchyCommand.java index 9f43ffdc9d..9a6046aa98 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/CreateHierarchyCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/CreateHierarchyCommand.java @@ -3,7 +3,6 @@ package lcsb.mapviewer.commands; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidStateException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; import lcsb.mapviewer.model.graphics.HorizontalAlign; import lcsb.mapviewer.model.graphics.VerticalAlign; import lcsb.mapviewer.model.map.compartment.Compartment; @@ -15,6 +14,7 @@ import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Complex; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.utils.RestAnnotationParser; import org.apache.commons.lang3.math.NumberUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -127,7 +127,7 @@ public class CreateHierarchyCommand extends ModelCommand { /** * Cleans hierarchical information from the model. */ - protected void clean() { + public void clean() { for (final Element alias : getModel().getElements()) { alias.setCompartment(null); alias.setPathway(null); diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/MoveElementsCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/MoveElementsCommand.java deleted file mode 100644 index 65f7649584..0000000000 --- a/model-command/src/main/java/lcsb/mapviewer/commands/MoveElementsCommand.java +++ /dev/null @@ -1,192 +0,0 @@ -package lcsb.mapviewer.commands; - -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.reaction.AbstractNode; -import lcsb.mapviewer.model.map.reaction.Modifier; -import lcsb.mapviewer.model.map.reaction.NodeOperator; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.ReactionNode; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.SpeciesWithModificationResidue; - -/** - * Command which moves elements in model by dx, dy coordinates. - * - * @author Piotr Gawron - * - */ -public class MoveElementsCommand extends ModelCommand { - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(); - - /** - * Delta x. - */ - private double dx; - - /** - * Delta y. - */ - private double dy; - - /** - * List of objects to move. - */ - private List<Object> objectsToMove = new ArrayList<>(); - - /** - * Default constructor. - * - * @param model - * model to move - * @param elements - * elements that should be moved - * @param dx - * delta x - * @param dy - * delta y - */ - public MoveElementsCommand(final Model model, final Collection<? extends BioEntity> elements, final double dx, final double dy) { - super(model); - this.dx = dx; - this.dy = dy; - for (final Object object : elements) { - if (object instanceof Element) { - if (((Element) object).getModel() != model) { - throw new InvalidArgumentException("Object doesnt belong to specified model: " + object); - } - } else if (object instanceof Reaction) { - if (((Reaction) object).getModel() != model) { - throw new InvalidArgumentException("Object doesnt belong to specified model: " + object); - } - } else { - throw new InvalidArgumentException("Cannot move element: " + object); - } - } - objectsToMove.addAll(elements); - } - - @Override - protected void undoImplementation() { - dx = -dx; - dy = -dy; - executeImplementation(); - dx = -dx; - dy = -dy; - setStatus(ModelCommandStatus.UNDONE); - } - - @Override - protected void redoImplementation() { - executeImplementation(); - setStatus(ModelCommandStatus.EXECUTED); - } - - @Override - protected void executeImplementation() { - Set<Element> aliases = new HashSet<>(); - - for (final Object object : objectsToMove) { - if (object instanceof Element) { - Element alias = (Element) object; - - includeInAffectedRegion(alias); - - alias.setX(alias.getX() + dx); - alias.setY(alias.getY() + dy); - alias.setNameX(alias.getNameX() + dx); - alias.setNameY(alias.getNameY() + dy); - - if (alias instanceof SpeciesWithModificationResidue) { - for (final ModificationResidue mr : ((SpeciesWithModificationResidue) alias).getModificationResidues()) { - mr.setX(mr.getX() + dx); - mr.setY(mr.getY() + dy); - } - } - includeInAffectedRegion(alias); - - aliases.add(alias); - } else if (object instanceof Reaction) { - Reaction reaction = (Reaction) object; - for (final Reactant node : reaction.getReactants()) { - Point2D startPoint = node.getLine().getStartPoint(); - moveNode(node); - node.getLine().setStartPoint(startPoint); - } - for (final Product node : reaction.getProducts()) { - Point2D endPoint = node.getLine().getEndPoint(); - moveNode(node); - node.getLine().setEndPoint(endPoint); - } - for (final Modifier node : reaction.getModifiers()) { - Point2D startPoint = node.getLine().getStartPoint(); - moveNode(node); - node.getLine().setStartPoint(startPoint); - } - for (final NodeOperator node : reaction.getOperators()) { - moveNode(node); - } - includeInAffectedRegion(reaction); - } else { - throw new InvalidStateException("Unknown class type: " + object); - } - } - if (aliases.size() > 0) { - // TODO this must be improved, we cannot do full search on every move - for (final Reaction reaction : getModel().getReactions()) { - for (final ReactionNode node : reaction.getReactionNodes()) { - if (aliases.contains(node.getElement())) { - if (node instanceof Reactant) { - Point2D point = node.getLine().getStartPoint(); - node.getLine().setStartPoint(point.getX() + dx, point.getY() + dy); - - // we don't have to include point that we change as it's already - // on the border of the element - includeInAffectedRegion(node.getLine().getLines().get(0).getP2()); - } else if (node instanceof Modifier) { - Point2D point = node.getLine().getStartPoint(); - node.getLine().setStartPoint(point.getX() + dx, point.getY() + dy); - // we don't have to include point that we change as it's already - // on the border of the element - includeInAffectedRegion(node.getLine().getLines().get(0).getP2()); - } else if (node instanceof Product) { - Point2D point = node.getLine().getEndPoint(); - node.getLine().setEndPoint(point.getX() + dx, point.getY() + dy); - // we don't have to include point that we change as it's already - // on the border of the element - includeInAffectedRegion(node.getLine().getEndPoint()); - } - } - } - } - } - } - - private void moveNode(final AbstractNode node) { - for (int i = 0; i < node.getLine().getLines().size(); i++) { - Line2D line = node.getLine().getLines().get(i); - node.getLine().setLine(i, line.getX1() + dx, line.getY1() + dy, line.getX2() + dx, line.getY2() + dy); - } - } -} diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/layout/ApplySimpleLayoutModelCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/layout/ApplySimpleLayoutModelCommand.java index 46a9798be3..9afa407aeb 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/layout/ApplySimpleLayoutModelCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/layout/ApplySimpleLayoutModelCommand.java @@ -7,8 +7,6 @@ import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.common.geometry.DoubleDimension; import lcsb.mapviewer.common.geometry.LineTransformation; import lcsb.mapviewer.common.geometry.PointTransformation; -import lcsb.mapviewer.converter.ZIndexPopulator; -import lcsb.mapviewer.converter.model.celldesigner.types.ModifierTypeUtils; import lcsb.mapviewer.model.LogMarker; import lcsb.mapviewer.model.ProjectLogEntryType; import lcsb.mapviewer.model.graphics.ArrowType; @@ -31,6 +29,7 @@ import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; import lcsb.mapviewer.model.map.species.field.ModificationResidue; import lcsb.mapviewer.model.map.species.field.SpeciesWithModificationResidue; +import lcsb.mapviewer.utils.ZIndexPopulator; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -348,7 +347,6 @@ public class ApplySimpleLayoutModelCommand extends ApplyLayoutModelCommand { line.setStartPoint(startPoint); } modifier.setLine(line); - new ModifierTypeUtils().updateLineEndPoint(modifier); } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/ImportOnly.java b/model-command/src/main/java/lcsb/mapviewer/utils/ImportOnly.java similarity index 80% rename from converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/ImportOnly.java rename to model-command/src/main/java/lcsb/mapviewer/utils/ImportOnly.java index 3f62862dcf..98d3aa6713 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/ImportOnly.java +++ b/model-command/src/main/java/lcsb/mapviewer/utils/ImportOnly.java @@ -1,11 +1,11 @@ -package lcsb.mapviewer.converter.model.celldesigner.annotation; - -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; +package lcsb.mapviewer.utils; import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target(FIELD) public @interface ImportOnly { diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteField.java b/model-command/src/main/java/lcsb/mapviewer/utils/NoteField.java similarity index 91% rename from converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteField.java rename to model-command/src/main/java/lcsb/mapviewer/utils/NoteField.java index d24ff4c4be..fc71274156 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteField.java +++ b/model-command/src/main/java/lcsb/mapviewer/utils/NoteField.java @@ -1,4 +1,4 @@ -package lcsb.mapviewer.converter.model.celldesigner.annotation; +package lcsb.mapviewer.utils; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.Drawable; @@ -10,9 +10,8 @@ import lcsb.mapviewer.model.map.species.Species; /** * Describes structural information that appears in the cell designer notes. - * + * * @author Piotr Gawron - * */ public enum NoteField { /** @@ -151,12 +150,12 @@ public enum NoteField { /** * Name used in the notes to distinguish fields. */ - private String commonName; + private final String commonName; /** * What object class can have this field. */ - private Class<? extends Drawable> clazz; + private final Class<? extends Drawable> clazz; /** * What {@link MiriamType} is associated with the field. @@ -165,11 +164,9 @@ public enum NoteField { /** * Default constructor. - * - * @param name - * {@link #commonName} - * @param clazz - * {@link #clazz} + * + * @param name {@link #commonName} + * @param clazz {@link #clazz} */ NoteField(final String name, final Class<? extends Drawable> clazz) { this.commonName = name; @@ -178,13 +175,10 @@ public enum NoteField { /** * Default constructor. - * - * @param name - * {@link #commonName} - * @param clazz - * {@link #clazz} - * @param type - * {@link #miriamType} + * + * @param name {@link #commonName} + * @param clazz {@link #clazz} + * @param type {@link #miriamType} */ NoteField(final String name, final Class<? extends Drawable> clazz, final MiriamType type) { this(name, clazz); diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParser.java b/model-command/src/main/java/lcsb/mapviewer/utils/RestAnnotationParser.java similarity index 88% rename from converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParser.java rename to model-command/src/main/java/lcsb/mapviewer/utils/RestAnnotationParser.java index 9c0db8c9f4..675807a38a 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParser.java +++ b/model-command/src/main/java/lcsb/mapviewer/utils/RestAnnotationParser.java @@ -1,20 +1,4 @@ -package lcsb.mapviewer.converter.model.celldesigner.annotation; - -import java.awt.Color; -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.text.StringEscapeUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.w3c.dom.Node; +package lcsb.mapviewer.utils; import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.comparator.DoubleComparator; @@ -26,8 +10,6 @@ import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.common.geometry.ColorParser; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; -import lcsb.mapviewer.converter.model.celldesigner.CommonXmlParser; import lcsb.mapviewer.model.LogMarker; import lcsb.mapviewer.model.ProjectLogEntryType; import lcsb.mapviewer.model.map.BioEntity; @@ -40,38 +22,68 @@ import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; import lcsb.mapviewer.modelutils.map.ElementUtils; +import org.apache.commons.text.StringEscapeUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.Node; + +import java.awt.Color; +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * This class is a converter of annotation provided by lcsb in raw text format * into set of MiriamData that can be used later on. - * + * * @author Piotr Gawron - * */ public class RestAnnotationParser { + public static final Set<MiriamRelationType> RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER; + + static { + Set<MiriamRelationType> types = new HashSet<>(); + types.addAll(Arrays.asList(MiriamRelationType.values())); + types.remove(MiriamRelationType.BQ_MODEL_IS_DERIVED_FROM); + types.remove(MiriamRelationType.BQ_BIOL_HAS_PROPERTY); + types.remove(MiriamRelationType.BQ_BIOL_IS_PROPERTY_OF); + types.remove(MiriamRelationType.BQ_MODEL_IS_INSTANCE_OF); + types.remove(MiriamRelationType.BQ_MODEL_HAS_INSTANCE); + types.remove(MiriamRelationType.BQ_BIOL_HAS_TAXON); + RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER = Collections.unmodifiableSet(types); + } + /** * Default class logger. */ - private static Logger logger = LogManager.getLogger(); + private static final Logger logger = LogManager.getLogger(); /** * Pattern used to find rdf node in string xml. */ - private Pattern rdfNodePattern = Pattern.compile("(?<=<rdf:RDF)([\\s\\S]*?)(?=</rdf:RDF>)"); + private final Pattern rdfNodePattern = Pattern.compile("(?<=<rdf:RDF)([\\s\\S]*?)(?=</rdf:RDF>)"); /** * Parser used for parsing annotations in rdf format. */ - private XmlAnnotationParser xmlAnnotationParser; + private final XmlAnnotationParser xmlAnnotationParser; /** * Class used for some simple operations on {@link BioEntity} elements. */ - private ElementUtils elementUtils = new ElementUtils(); + private final ElementUtils elementUtils = new ElementUtils(); public RestAnnotationParser() { - xmlAnnotationParser = new XmlAnnotationParser(CommonXmlParser.RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); + xmlAnnotationParser = new XmlAnnotationParser(RELATION_TYPES_SUPPORTED_BY_CELL_DESIGNER); } /** @@ -79,8 +91,7 @@ public class RestAnnotationParser { * Parsing has been prepared based on the information provided by Kazuhiro * Fujita, kaf@sbi.jp. * - * @param annotationString - * - string with data to parse + * @param annotationString - string with data to parse * @return list of {@link MiriamData annotations} */ public Set<MiriamData> getMiriamData(final String annotationString) { @@ -110,8 +121,7 @@ public class RestAnnotationParser { /** * Creates note string with structural information about element. * - * @param element - * element for which notes are created + * @param element element for which notes are created * @return note string with structural information about element */ public String createAnnotationString(final Element element) { @@ -121,11 +131,9 @@ public class RestAnnotationParser { /** * Creates note string with structural information about element. * - * @param element - * element for which notes are created - * @param forceFullInfo - * when true annotation string will contain information about empty - * fields + * @param element element for which notes are created + * @param forceFullInfo when true annotation string will contain information about empty + * fields * @return note string with structural information about element */ public String createAnnotationString(final Element element, final boolean forceFullInfo) { @@ -219,10 +227,8 @@ public class RestAnnotationParser { * ... * </pre> * - * @param annotationString - * whole annotation string - * @param prefix - * prefix used for identifying line + * @param annotationString whole annotation string + * @param prefix prefix used for identifying line * @return value for the given type in structured annotation */ private String getParamByPrefix(final String annotationString, final String prefix) { @@ -248,8 +254,7 @@ public class RestAnnotationParser { /** * Returns list of symbols from the annotation string. * - * @param annotationString - * annotation string + * @param annotationString annotation string * @return list of symbol */ public List<String> getSynonyms(final String annotationString) { @@ -268,8 +273,7 @@ public class RestAnnotationParser { /** * Returns list of former symbols from the annotation string. * - * @param annotationString - * annotation string + * @param annotationString annotation string * @return list of former symbol */ public List<String> getFormerSymbols(final String annotationString) { @@ -290,10 +294,8 @@ public class RestAnnotationParser { * database_ID: idfield1, idfield2, ..., idfieldn<br> * into a vector of string ids. * - * @param line - * - a line to be parsed - * @param baseId - * - database string id + * @param line - a line to be parsed + * @param baseId - database string id * @return vector of string ids */ protected ArrayList<String> getIds(final String line, final String baseId) { @@ -316,12 +318,9 @@ public class RestAnnotationParser { /** * This method transform the vector of ids into a set of MiriamData. * - * @param type - * - relationtype of the annotaion ids - * @param miriamType - * {@link MiriamType type} of the reference resource - * @param ids - * - list of ids + * @param type - relationtype of the annotaion ids + * @param miriamType {@link MiriamType type} of the reference resource + * @param ids - list of ids * @return set of miriam data */ private Set<MiriamData> idsToData(final MiriamRelationType type, final MiriamType miriamType, final ArrayList<String> ids) { @@ -336,10 +335,8 @@ public class RestAnnotationParser { /** * Process element notes and assign structural information from it. * - * @param node - * node with notes about element - * @param element - * where the structural data should be put + * @param node node with notes about element + * @param element where the structural data should be put */ public void processNotes(final Node node, final BioEntity element) { String notes = getNotes(node); @@ -349,8 +346,7 @@ public class RestAnnotationParser { /** * Process notes and assign structural information from it. * - * @param element - * object with notes to be processed + * @param element object with notes to be processed */ public void processNotes(final Element element) { processNotes(element.getNotes(), element); @@ -359,16 +355,14 @@ public class RestAnnotationParser { /** * Process notes and assign structural information from it. * - * @param notes - * notes about element - * @param object - * where the structural data should be put + * @param notes notes about element + * @param object where the structural data should be put */ public void processNotes(final String notes, final Drawable object) { StringBuilder annotations = new StringBuilder(); String[] string = notes.split("\n"); - StringBuilder newNotes = new StringBuilder(""); + StringBuilder newNotes = new StringBuilder(); for (final String string2 : string) { boolean remove = false; for (final NoteField field : NoteField.values()) { @@ -434,8 +428,7 @@ public class RestAnnotationParser { /** * Transforms xml node into notes. * - * @param node - * xml node with notes + * @param node xml node with notes * @return string with notes */ public String getNotes(final Node node) { @@ -465,10 +458,8 @@ public class RestAnnotationParser { /** * Assigns synonyms to the element from notes string. * - * @param element - * element to which data should be put to - * @param annotationString - * notes string + * @param element element to which data should be put to + * @param annotationString notes string */ private void setSynonyms(final BioEntity element, final String annotationString) { List<String> synonyms = getSynonyms(annotationString); @@ -493,10 +484,8 @@ public class RestAnnotationParser { /** * Assigns list of symbols to the element from notes string. * - * @param element - * element to which data should be put to - * @param annotationString - * notes string + * @param element element to which data should be put to + * @param annotationString notes string */ private void setFormerSymbolsToSpecies(final Element element, final String annotationString) { List<String> formerSymbols = getFormerSymbols(annotationString); @@ -517,10 +506,8 @@ public class RestAnnotationParser { /** * Assigns full name to the element from notes string. * - * @param element - * element to which data should be put to - * @param annotationString - * notes string + * @param element element to which data should be put to + * @param annotationString notes string */ private void setFullNameToSpecies(final Element element, final String annotationString) { StringComparator stringComparator = new StringComparator(); @@ -543,10 +530,8 @@ public class RestAnnotationParser { /** * Assigns abbreviation to the element from notes string. * - * @param element - * element to which data should be put to - * @param annotationString - * notes string + * @param element element to which data should be put to + * @param annotationString notes string */ private void setAbbreviation(final BioEntity element, final String annotationString) { StringComparator stringComparator = new StringComparator(); @@ -569,10 +554,8 @@ public class RestAnnotationParser { /** * Assigns subsystem to the reaction from notes string. * - * @param element - * element to which data should be put to - * @param annotationString - * notes string + * @param element element to which data should be put to + * @param annotationString notes string */ private void setSubsystemToReaction(final Reaction element, final String annotationString) { StringComparator stringComparator = new StringComparator(); @@ -591,10 +574,8 @@ public class RestAnnotationParser { /** * Assigns gene protein reaction to the reaction from notes string. * - * @param element - * element to which data should be put to - * @param annotationString - * notes string + * @param element element to which data should be put to + * @param annotationString notes string */ private void setGeneProteinReactionToReaction(final Reaction element, final String annotationString) { StringComparator stringComparator = new StringComparator(); @@ -613,10 +594,8 @@ public class RestAnnotationParser { /** * Assigns formula to the element from notes string. * - * @param element - * element to which data should be put to - * @param annotationString - * notes string + * @param element element to which data should be put to + * @param annotationString notes string */ private void setFormula(final BioEntity element, final String annotationString) { StringComparator stringComparator = new StringComparator(); @@ -642,10 +621,8 @@ public class RestAnnotationParser { /** * Assigns mechanical confidence score to the reaction from notes string. * - * @param element - * element to which data should be put to - * @param annotationString - * notes string + * @param element element to which data should be put to + * @param annotationString notes string */ private void setMechanicalConfidenceScoreToReaction(final Reaction element, final String annotationString) { IntegerComparator integerComparator = new IntegerComparator(); @@ -666,10 +643,8 @@ public class RestAnnotationParser { /** * Assigns charge to the element from notes string. * - * @param element - * element to which data should be put to - * @param annotationString - * notes string + * @param element element to which data should be put to + * @param annotationString notes string */ private void setCharge(final Species element, final String annotationString) { IntegerComparator integerComparator = new IntegerComparator(); @@ -693,10 +668,8 @@ public class RestAnnotationParser { /** * Assigns lower bound to the reaction from notes string. * - * @param element - * element to which data should be put to - * @param annotationString - * notes string + * @param element element to which data should be put to + * @param annotationString notes string */ private void setLowerBoundToReaction(final Reaction element, final String annotationString) { DoubleComparator doubleComparator = new DoubleComparator(); @@ -716,10 +689,8 @@ public class RestAnnotationParser { /** * Assigns upper bound to the reaction from notes string. * - * @param element - * element to which data should be put to - * @param annotationString - * notes string + * @param element element to which data should be put to + * @param annotationString notes string */ private void setUpperBoundToReaction(final Reaction element, final String annotationString) { DoubleComparator doubleComparator = new DoubleComparator(); @@ -739,10 +710,8 @@ public class RestAnnotationParser { /** * Assigns symbol to the element from notes string. * - * @param element - * element to which data should be put to - * @param annotationString - * notes string + * @param element element to which data should be put to + * @param annotationString notes string */ private void setSymbol(final BioEntity element, final String annotationString) { String symbol = getSymbol(annotationString); @@ -764,10 +733,8 @@ public class RestAnnotationParser { /** * Assigns semanticZoomingLevel to the element from notes string. * - * @param element - * element to which data should be put to - * @param annotationString - * notes string + * @param element element to which data should be put to + * @param annotationString notes string */ private void setSemanticZoomLevelVisibility(final BioEntity element, final String annotationString) { String zoomLevelVisibility = getParamByPrefix(annotationString, @@ -819,10 +786,8 @@ public class RestAnnotationParser { * data from these sources should be merged. So, this method in fact merges * notes in the element and description extracted from notes string. * - * @param element - * element to which data should be put to - * @param annotationString - * notes string + * @param element element to which data should be put to + * @param annotationString notes string */ private void setNotes(final BioEntity element, final String annotationString) { String description = getDescription(annotationString); @@ -832,7 +797,7 @@ public class RestAnnotationParser { if (element.getNotes().trim().equals("")) { element.setNotes(description); } else if (element.getNotes().contains(description)) { - return; + // } else { element.setNotes(element.getNotes().trim() + "\n" + description + "\n"); } @@ -887,10 +852,8 @@ public class RestAnnotationParser { * Process RDF description from notes, removes it from the description and * adds appropriate information to miriam data set. * - * @param element - * notes of this element will be processed - * @throws InvalidXmlSchemaException - * thrown when there is a problem with xml + * @param element notes of this element will be processed + * @throws InvalidXmlSchemaException thrown when there is a problem with xml */ void processRdfDescription(final BioEntity element) throws InvalidXmlSchemaException { String notes = element.getNotes(); diff --git a/converter/src/main/java/lcsb/mapviewer/converter/annotation/XmlAnnotationParser.java b/model-command/src/main/java/lcsb/mapviewer/utils/XmlAnnotationParser.java similarity index 99% rename from converter/src/main/java/lcsb/mapviewer/converter/annotation/XmlAnnotationParser.java rename to model-command/src/main/java/lcsb/mapviewer/utils/XmlAnnotationParser.java index 8f4b496202..421b161d5c 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/annotation/XmlAnnotationParser.java +++ b/model-command/src/main/java/lcsb/mapviewer/utils/XmlAnnotationParser.java @@ -1,4 +1,4 @@ -package lcsb.mapviewer.converter.annotation; +package lcsb.mapviewer.utils; import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidArgumentException; diff --git a/converter/src/main/java/lcsb/mapviewer/converter/ZIndexPopulator.java b/model-command/src/main/java/lcsb/mapviewer/utils/ZIndexPopulator.java similarity index 91% rename from converter/src/main/java/lcsb/mapviewer/converter/ZIndexPopulator.java rename to model-command/src/main/java/lcsb/mapviewer/utils/ZIndexPopulator.java index bad89a1306..3be218d856 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/ZIndexPopulator.java +++ b/model-command/src/main/java/lcsb/mapviewer/utils/ZIndexPopulator.java @@ -1,13 +1,4 @@ -package lcsb.mapviewer.converter; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.List; -import java.util.Set; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +package lcsb.mapviewer.utils; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.comparator.DoubleComparator; @@ -22,22 +13,29 @@ import lcsb.mapviewer.model.map.species.Species; import lcsb.mapviewer.model.map.species.field.ModificationResidue; import lcsb.mapviewer.model.map.species.field.SpeciesWithModificationResidue; import lcsb.mapviewer.model.map.species.field.StructuralState; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.List; +import java.util.Set; /** * This util class populate with z-index data if necessary. - * - * @author Piotr Gawron * + * @author Piotr Gawron */ public class ZIndexPopulator { @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(); + private static final Logger logger = LogManager.getLogger(); - private static DoubleComparator DOUBLE_COMPARATOR = new DoubleComparator(Configuration.EPSILON); - private static StringComparator STRING_COMPARATOR = new StringComparator(); + private static final DoubleComparator DOUBLE_COMPARATOR = new DoubleComparator(Configuration.EPSILON); + private static final StringComparator STRING_COMPARATOR = new StringComparator(); - private static Comparator<Drawable> COMPARATOR = new Comparator<Drawable>() { + private static final Comparator<Drawable> COMPARATOR = new Comparator<Drawable>() { @Override public int compare(final Drawable o1, final Drawable o2) { if (o1 instanceof StructuralState) { diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/ColorModelCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/ColorModelCommandTest.java index fac16a48f9..5d2fdaadc9 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/ColorModelCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/ColorModelCommandTest.java @@ -1,20 +1,5 @@ package lcsb.mapviewer.commands; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; @@ -31,10 +16,25 @@ import lcsb.mapviewer.model.map.species.Protein; import lcsb.mapviewer.model.map.species.field.TranscriptionSite; import lcsb.mapviewer.model.overlay.DataOverlayEntry; import lcsb.mapviewer.model.overlay.GenericDataOverlayEntry; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; public class ColorModelCommandTest extends CommandTestFunctions { - private ColorExtractor colorExtractor = new ColorExtractor(Color.RED, Color.GREEN, Color.BLUE, Color.WHITE); + private final ColorExtractor colorExtractor = new ColorExtractor(Color.RED, Color.GREEN, Color.BLUE, Color.WHITE); @Before public void setUp() throws Exception { @@ -45,10 +45,185 @@ public class ColorModelCommandTest extends CommandTestFunctions { } @Test - public void testColorFullModel() throws Exception { + public void testAliasMatchWithInvalidElementId() throws Exception { + GenericDataOverlayEntry colorSchema = new GenericDataOverlayEntry(); + colorSchema.setName(null); + colorSchema.setElementId("1"); + + BioEntity protein = new GenericProtein("id"); + protein.setName("test"); + + List<DataOverlayEntry> schemas = new ArrayList<>(); + schemas.add(colorSchema); + + ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); + + assertFalse(factory.match(protein, colorSchema)); + + colorSchema.setElementId(null); + assertTrue(factory.match(protein, colorSchema)); + } + + @Test + public void testSpeciesMatchWithProteinType() throws Exception { + GenericDataOverlayEntry colorSchema = new GenericDataOverlayEntry(); + colorSchema.setName("s1"); + colorSchema.addType(Protein.class); + + GenericProtein species = new GenericProtein("id"); + species.setName("s1"); + + List<DataOverlayEntry> schemas = new ArrayList<>(); + schemas.add(colorSchema); + + ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); + + assertTrue(factory.match(species, colorSchema)); + } + + @Test + public void testSpeciesMatchWithMiriamData() throws Exception { + GenericDataOverlayEntry colorSchema = new GenericDataOverlayEntry(); + colorSchema.setName("s1"); + colorSchema.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); + + GenericDataOverlayEntry colorSchema2 = new GenericDataOverlayEntry(); + colorSchema2.setName("s1"); + colorSchema2.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "PARK7")); + + GenericProtein species = new GenericProtein("id"); + species.setName("s1"); + species.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); + + List<DataOverlayEntry> schemas = new ArrayList<>(); + schemas.add(colorSchema); + + ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); + + assertTrue(factory.match(species, colorSchema)); + assertFalse(factory.match(species, colorSchema2)); + } + + @Test + public void testSpeciesMatchWithMiriamDataDifferentAnnotator() throws Exception { + GenericDataOverlayEntry colorSchema = new GenericDataOverlayEntry(); + colorSchema.setName("s1"); + colorSchema.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); + + GenericProtein species = new GenericProtein("id"); + species.setName("s1"); + species.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA", Object.class)); + + List<DataOverlayEntry> schemas = new ArrayList<>(); + schemas.add(colorSchema); + + ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); + + assertTrue(factory.match(species, colorSchema)); + } + + @Test + public void testReactionMatchWithProteinMiriamData() throws Exception { + GenericDataOverlayEntry colorSchema = new GenericDataOverlayEntry(); + colorSchema.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); + + Reaction reaction = new Reaction("re"); + + List<DataOverlayEntry> schemas = new ArrayList<>(); + schemas.add(colorSchema); + + ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); + + assertFalse(factory.match(reaction, colorSchema)); + } + + @Test + public void testReactionMatchWithMiriamData() throws Exception { + GenericDataOverlayEntry colorSchema = new GenericDataOverlayEntry(); + colorSchema.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); + + Reaction reaction = new Reaction("re"); + reaction.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); + + List<DataOverlayEntry> schemas = new ArrayList<>(); + schemas.add(colorSchema); + + ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); + + assertTrue(factory.match(reaction, colorSchema)); + } + + + @Test + public void testGetModifiedElements() throws Exception { + Reaction reaction = new Reaction("re"); + reaction.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); + + Model model = new ModelFullIndexed(null); + model.addReaction(reaction); + + GenericDataOverlayEntry colorSchema = new GenericDataOverlayEntry(); + colorSchema.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); + + List<DataOverlayEntry> schemas = new ArrayList<>(); + schemas.add(colorSchema); + + ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); + + assertNotNull(factory.getModifiedElements().get(reaction)); + } + + @Test + public void testApplyColorToReaction() throws Exception { + Model model = createSimpleModel(); + Protein protein1 = createProteinWithLayout(); + Protein protein2 = createProteinWithLayout(); + model.addElement(protein1); + model.addElement(protein2); + Reaction reaction = createReactionWithLayout(protein1, protein1); + reaction.setIdReaction("re1"); + model.addReaction(reaction); + + DataOverlayEntry schema = new GenericDataOverlayEntry(); + schema.setElementId("re1"); + schema.setColor(Color.YELLOW); + schema.setName(null); + + ColorModelCommand factory = new ColorModelCommand(model, new ArrayList<>(), colorExtractor); + + factory.applyColor(reaction, schema); + + assertEquals(Color.YELLOW, reaction.getLine().getColor()); + } + + @Test + public void testColorTranscriptionFactor() { + Model model = new ModelFullIndexed(null); + + Gene gene = createGene(); + TranscriptionSite site = new TranscriptionSite(); + site.setBorderColor(Color.YELLOW); + gene.addTranscriptionSite(site); + model.addElement(gene); + + ColorModelCommand factory = new ColorModelCommand(model, new ArrayList<>(), colorExtractor); + factory.execute(); + + assertEquals(Color.BLACK, site.getBorderColor()); + } + + + @Test + public void testColorFullModel() { ModelComparator comparator = new ModelComparator(); - Model model = getModelForFile("testFiles/sample.xml", false); - Model model2 = getModelForFile("testFiles/sample.xml", false); + Model model = createSimpleModel(); + GenericProtein protein = createProteinWithLayout(); + protein.setElementId("sa14"); + protein.setName("CNC"); + model.addElement(protein); + + Model model2 = copyModel(model); + Model coloredModel = new CopyCommand(model).execute(); List<DataOverlayEntry> schemas = new ArrayList<>(); @@ -58,20 +233,32 @@ public class ColorModelCommandTest extends CommandTestFunctions { schemas.add(schema); ColorModelCommand factory = new ColorModelCommand(coloredModel, schemas, colorExtractor); - assertFalse(Color.RED.equals(coloredModel.getElementByElementId("sa14").getFillColor())); + assertNotEquals(Color.RED, coloredModel.getElementByElementId("sa14").getFillColor()); factory.execute(); assertEquals(0, comparator.compare(model, model2)); - assertFalse(comparator.compare(model, coloredModel) == 0); + assertNotEquals(0, comparator.compare(model, coloredModel)); assertEquals(Color.RED, coloredModel.getElementByElementId("sa14").getFillColor()); } + private Model copyModel(final Model model) { + return new CopyCommand(model).execute(); + } + @Test public void testColoring2() throws Exception { - Model model = getModelForFile("testFiles/coloring_model.xml", true); + Model model = createSimpleModel(); + GenericProtein protein = createProteinWithLayout(); + protein.addMiriamData(new MiriamData(MiriamType.HGNC, "11138")); + model.addElement(protein); + + Gene gene = createGene(); + gene.addMiriamData(new MiriamData(MiriamType.CHEBI, "CHEBI:15377")); + model.addElement(gene); + Collection<DataOverlayEntry> schemas = new ArrayList<>(); DataOverlayEntry schema = new GenericDataOverlayEntry(); schema.addMiriamData(new MiriamData(MiriamType.HGNC, "11138")); @@ -94,7 +281,12 @@ public class ColorModelCommandTest extends CommandTestFunctions { @Test public void testColorTheSameElementTwiceUsingDifferentSelector() throws Exception { - Model model = getModelForFile("testFiles/coloring_model.xml", true); + Model model = createSimpleModel(); + GenericProtein protein = createProteinWithLayout(); + protein.setName("SNCA"); + protein.addMiriamData(new MiriamData(MiriamType.HGNC, "11138")); + model.addElement(protein); + Collection<DataOverlayEntry> schemas = new ArrayList<>(); DataOverlayEntry schema = new GenericDataOverlayEntry(); schema.addMiriamData(new MiriamData(MiriamType.HGNC, "11138")); @@ -108,66 +300,92 @@ public class ColorModelCommandTest extends CommandTestFunctions { ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); Map<BioEntity, DataOverlayEntry> modifiedElements = factory.getModifiedElements(); - assertEquals(1, modifiedElements.keySet().size()); + assertEquals(1, modifiedElements.size()); } @Test public void testReactionColoring1() throws Exception { - Model model = getModelForFile("testFiles/reactions_to_color.xml", false); - Reaction re4 = model.getReactionByReactionId("re4"); - Collection<DataOverlayEntry> schemas = new ArrayList<DataOverlayEntry>(); + Model model = createSimpleModel(); + Protein protein1 = createProteinWithLayout(); + Protein protein2 = createProteinWithLayout(); + model.addElement(protein1); + model.addElement(protein2); + Reaction reaction = createReactionWithLayout(protein1, protein1); + reaction.getNodes().get(0).getLine().setColor(Color.RED); + model.addReaction(reaction); + + Collection<DataOverlayEntry> schemas = new ArrayList<>(); ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - assertFalse(Color.BLACK.equals(re4.getNodes().get(0).getLine().getColor())); + assertNotEquals(Color.BLACK, reaction.getNodes().get(0).getLine().getColor()); factory.execute(); - re4 = model.getReactionByReactionId("re4"); + reaction = model.getReactionByReactionId(reaction.getIdReaction()); - assertEquals(Color.BLACK, re4.getNodes().get(0).getLine().getColor()); + assertEquals(Color.BLACK, reaction.getNodes().get(0).getLine().getColor()); } @Test public void testReactionColoring2() throws Exception { - Model model = getModelForFile("testFiles/reactions_to_color.xml", false); - Reaction re1 = model.getReactionByReactionId("re1"); + Model model = createSimpleModel(); + Protein protein1 = createProteinWithLayout(); + Protein protein2 = createProteinWithLayout(); + model.addElement(protein1); + model.addElement(protein2); + Reaction reaction = createReactionWithLayout(protein1, protein1); + model.addReaction(reaction); + Collection<DataOverlayEntry> schemas = new ArrayList<DataOverlayEntry>(); DataOverlayEntry schema = new GenericDataOverlayEntry(); - schema.setElementId("re1"); + schema.setElementId(reaction.getIdReaction()); schema.setColor(Color.RED); schemas.add(schema); ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - assertEquals(Color.BLACK, re1.getNodes().get(0).getLine().getColor()); + assertEquals(Color.BLACK, reaction.getNodes().get(0).getLine().getColor()); factory.execute(); - re1 = model.getReactionByReactionId("re1"); + reaction = model.getReactionByReactionId(reaction.getIdReaction()); - assertEquals(Color.RED, re1.getNodes().get(0).getLine().getColor()); + assertEquals(Color.RED, reaction.getNodes().get(0).getLine().getColor()); } @Test public void testReactionColoring3() throws Exception { - Model model = getModelForFile("testFiles/reactions_to_color.xml", false); - Reaction re2 = model.getReactionByReactionId("re2"); + Model model = createSimpleModel(); + Protein protein1 = createProteinWithLayout(); + Protein protein2 = createProteinWithLayout(); + model.addElement(protein1); + model.addElement(protein2); + Reaction reaction = createReactionWithLayout(protein1, protein1); + model.addReaction(reaction); + Collection<DataOverlayEntry> schemas = new ArrayList<DataOverlayEntry>(); DataOverlayEntry schema = new GenericDataOverlayEntry(); - schema.setElementId("re2"); + schema.setElementId(reaction.getIdReaction()); schema.setValue(-1.0); schemas.add(schema); ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - assertEquals(Color.BLACK, re2.getNodes().get(0).getLine().getColor()); + assertEquals(Color.BLACK, reaction.getNodes().get(0).getLine().getColor()); factory.execute(); - re2 = model.getReactionByReactionId("re2"); + reaction = model.getReactionByReactionId(reaction.getIdReaction()); - assertEquals(Color.RED, re2.getNodes().get(0).getLine().getColor()); + assertEquals(Color.RED, reaction.getNodes().get(0).getLine().getColor()); } @Test public void testReactionColoring4() throws Exception { - Model model = getModelForFile("testFiles/reactions_to_color.xml", false); - Reaction re3 = model.getReactionByReactionId("re3"); + Model model = createSimpleModel(); + Protein protein1 = createProteinWithLayout(); + Protein protein2 = createProteinWithLayout(); + model.addElement(protein1); + model.addElement(protein2); + Reaction reaction = createReactionWithLayout(protein1, protein1); + reaction.addMiriamData(new MiriamData(MiriamType.PUBMED, "12345")); + model.addReaction(reaction); + Collection<DataOverlayEntry> schemas = new ArrayList<DataOverlayEntry>(); DataOverlayEntry schema = new GenericDataOverlayEntry(); schema.addMiriamData(new MiriamData(MiriamType.PUBMED, "12345")); @@ -176,18 +394,22 @@ public class ColorModelCommandTest extends CommandTestFunctions { ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - assertEquals(Color.BLACK, re3.getNodes().get(0).getLine().getColor()); + assertEquals(Color.BLACK, reaction.getNodes().get(0).getLine().getColor()); factory.execute(); - re3 = model.getReactionByReactionId("re3"); + reaction = model.getReactionByReactionId(reaction.getIdReaction()); - assertEquals(Color.RED, re3.getNodes().get(0).getLine().getColor()); + assertEquals(Color.RED, reaction.getNodes().get(0).getLine().getColor()); } @Test public void testColoringComplexModel() throws Exception { - Model model = getModelForFile("testFiles/sample.xml", false); - Model model2 = getModelForFile("testFiles/sample.xml", false); + Model model = createSimpleModel(); + Model model2 = createSimpleModel(); + + Protein protein1 = createProteinWithLayout(); + protein1.setFillColor(Color.PINK); + model2.addElement(protein1); model.addSubmodelConnection(new ModelSubmodelConnection(model2, SubmodelType.UNKNOWN, "BLA")); @@ -198,15 +420,20 @@ public class ColorModelCommandTest extends CommandTestFunctions { Model coloredModel2 = coloredModel.getSubmodelConnections().iterator().next().getSubmodel().getModel(); Model coloredModel3 = coloredModel.getSubmodelByConnectionName("BLA"); - assertFalse( - coloredModel2.getElementByElementId("sa2").getFillColor().equals(model2.getElementByElementId("sa2").getFillColor())); - assertFalse( - coloredModel3.getElementByElementId("sa2").getFillColor().equals(model2.getElementByElementId("sa2").getFillColor())); + assertNotEquals(coloredModel2.getElementByElementId(protein1.getElementId()).getFillColor(), model2.getElementByElementId(protein1.getElementId()).getFillColor()); + assertNotEquals(coloredModel3.getElementByElementId(protein1.getElementId()).getFillColor(), model2.getElementByElementId(protein1.getElementId()).getFillColor()); } @Test - public void testColoredAliases() throws Exception { - Model model = getModelForFile("testFiles/sample.xml", false); + public void testColoredAliases() { + Model model = createSimpleModel(); + Protein p1 = createProtein(); + p1.setName("CNC"); + model.addElement(p1); + Protein protein = createProtein(); + protein.setName("BDH1"); + model.addElement(protein); + Collection<DataOverlayEntry> schemas = new ArrayList<>(); DataOverlayEntry schema = new GenericDataOverlayEntry(); schema.setName("CNC"); @@ -227,10 +454,17 @@ public class ColorModelCommandTest extends CommandTestFunctions { @Test public void testColoredReactions() throws Exception { - Model model = getModelForFile("testFiles/sample.xml", false); + Model model = createSimpleModel(); + Protein protein1 = createProteinWithLayout(); + Protein protein2 = createProteinWithLayout(); + model.addElement(protein1); + model.addElement(protein2); + Reaction reaction = createReactionWithLayout(protein1, protein1); + model.addReaction(reaction); + Collection<DataOverlayEntry> schemas = new ArrayList<>(); DataOverlayEntry schema = new GenericDataOverlayEntry(); - schema.setElementId("re1"); + schema.setElementId(reaction.getIdReaction()); schema.setLineWidth(3.0); schema.setColor(Color.BLUE); schema.setName("not matching name"); @@ -244,10 +478,17 @@ public class ColorModelCommandTest extends CommandTestFunctions { @Test public void testColoredReactions2() throws Exception { - Model model = getModelForFile("testFiles/sample.xml", false); + Model model = createSimpleModel(); + Protein protein1 = createProteinWithLayout(); + Protein protein2 = createProteinWithLayout(); + model.addElement(protein1); + model.addElement(protein2); + Reaction reaction = createReactionWithLayout(protein1, protein1); + model.addReaction(reaction); + Collection<DataOverlayEntry> schemas = new ArrayList<>(); DataOverlayEntry schema = new GenericDataOverlayEntry(); - schema.setElementId("re1"); + schema.setElementId(reaction.getIdReaction()); schema.setLineWidth(3.0); schema.setColor(Color.BLUE); schema.setName(null); @@ -259,126 +500,23 @@ public class ColorModelCommandTest extends CommandTestFunctions { assertEquals(1, map.size()); for (Map.Entry<BioEntity, DataOverlayEntry> entry : map.entrySet()) { assertTrue(entry.getKey() instanceof Reaction); - assertEquals("re1", ((Reaction) entry.getKey()).getIdReaction()); + assertEquals(reaction.getIdReaction(), ((Reaction) entry.getKey()).getIdReaction()); assertEquals(entry.getValue(), schema); } } - @Test - public void testAliasMatchWithInvalidElementId() throws Exception { - GenericDataOverlayEntry colorSchema = new GenericDataOverlayEntry(); - colorSchema.setName(null); - colorSchema.setElementId("1"); - - BioEntity protein = new GenericProtein("id"); - protein.setName("test"); - - List<DataOverlayEntry> schemas = new ArrayList<>(); - schemas.add(colorSchema); - - ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); - - assertFalse(factory.match(protein, colorSchema)); - - colorSchema.setElementId(null); - assertTrue(factory.match(protein, colorSchema)); - } - - @Test - public void testSpeciesMatchWithProteinType() throws Exception { - GenericDataOverlayEntry colorSchema = new GenericDataOverlayEntry(); - colorSchema.setName("s1"); - colorSchema.addType(Protein.class); - - GenericProtein species = new GenericProtein("id"); - species.setName("s1"); - - List<DataOverlayEntry> schemas = new ArrayList<>(); - schemas.add(colorSchema); - - ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); - - assertTrue(factory.match(species, colorSchema)); - } - - @Test - public void testSpeciesMatchWithMiriamData() throws Exception { - GenericDataOverlayEntry colorSchema = new GenericDataOverlayEntry(); - colorSchema.setName("s1"); - colorSchema.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); - - GenericDataOverlayEntry colorSchema2 = new GenericDataOverlayEntry(); - colorSchema2.setName("s1"); - colorSchema2.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "PARK7")); - - GenericProtein species = new GenericProtein("id"); - species.setName("s1"); - species.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); - - List<DataOverlayEntry> schemas = new ArrayList<>(); - schemas.add(colorSchema); - - ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); - - assertTrue(factory.match(species, colorSchema)); - assertFalse(factory.match(species, colorSchema2)); - } - - @Test - public void testSpeciesMatchWithMiriamDataDifferentAnnotator() throws Exception { - GenericDataOverlayEntry colorSchema = new GenericDataOverlayEntry(); - colorSchema.setName("s1"); - colorSchema.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); - - GenericProtein species = new GenericProtein("id"); - species.setName("s1"); - species.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA", Object.class)); - - List<DataOverlayEntry> schemas = new ArrayList<>(); - schemas.add(colorSchema); - - ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); - - assertTrue(factory.match(species, colorSchema)); - } - - @Test - public void testReactionMatchWithProteinMiriamData() throws Exception { - GenericDataOverlayEntry colorSchema = new GenericDataOverlayEntry(); - colorSchema.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); - - Reaction reaction = new Reaction("re"); - - List<DataOverlayEntry> schemas = new ArrayList<>(); - schemas.add(colorSchema); - - ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); - - assertFalse(factory.match(reaction, colorSchema)); - } - - @Test - public void testReactionMatchWithMiriamData() throws Exception { - GenericDataOverlayEntry colorSchema = new GenericDataOverlayEntry(); - colorSchema.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); - - Reaction reaction = new Reaction("re"); - reaction.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); - - List<DataOverlayEntry> schemas = new ArrayList<>(); - schemas.add(colorSchema); - - ColorModelCommand factory = new ColorModelCommand(new ModelFullIndexed(null), schemas, colorExtractor); - - assertTrue(factory.match(reaction, colorSchema)); - } - @Test public void testReactionColoringWithModelNotMatching() throws Exception { - Model model = getModelForFile("testFiles/reactions_to_color.xml", false); + Model model = createSimpleModel(); + Protein protein1 = createProteinWithLayout(); + Protein protein2 = createProteinWithLayout(); + model.addElement(protein1); + model.addElement(protein2); + Reaction reaction = createReactionWithLayout(protein1, protein1); + model.addReaction(reaction); DataOverlayEntry schema = new GenericDataOverlayEntry(); - schema.setElementId("re4"); + schema.setElementId(reaction.getIdReaction()); schema.setName(null); schema.setModelName(model.getName() + "XXX"); @@ -387,15 +525,21 @@ public class ColorModelCommandTest extends CommandTestFunctions { ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); Map<BioEntity, DataOverlayEntry> map = factory.getModifiedElements(); - assertEquals(0, map.values().size()); + assertEquals(0, map.size()); } @Test public void testReactionColoringWithModelMatch() throws Exception { - Model model = getModelForFile("testFiles/reactions_to_color.xml", false); + Model model = createSimpleModel(); + Protein protein1 = createProteinWithLayout(); + Protein protein2 = createProteinWithLayout(); + model.addElement(protein1); + model.addElement(protein2); + Reaction reaction = createReactionWithLayout(protein1, protein1); + model.addReaction(reaction); DataOverlayEntry schema = new GenericDataOverlayEntry(); - schema.setElementId("re4"); + schema.setElementId(reaction.getIdReaction()); schema.setName(null); schema.setModelName(model.getName()); @@ -404,12 +548,15 @@ public class ColorModelCommandTest extends CommandTestFunctions { ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); Map<BioEntity, DataOverlayEntry> map = factory.getModifiedElements(); - assertEquals(1, map.values().size()); + assertEquals(1, map.size()); } @Test public void testAliasColoringWithModelNotMatching() throws Exception { - Model model = getModelForFile("testFiles/sample.xml", false); + Model model = createSimpleModel(); + Protein p1 = createProtein(); + p1.setName("CNC"); + model.addElement(p1); DataOverlayEntry schema = new GenericDataOverlayEntry(); schema.setName("CNC"); @@ -420,12 +567,15 @@ public class ColorModelCommandTest extends CommandTestFunctions { ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); Map<BioEntity, DataOverlayEntry> map = factory.getModifiedElements(); - assertEquals(0, map.values().size()); + assertEquals(0, map.size()); } @Test public void testAliasColoringWithModelMatch() throws Exception { - Model model = getModelForFile("testFiles/sample.xml", false); + Model model = createSimpleModel(); + Protein p1 = createProtein(); + p1.setName("CNC"); + model.addElement(p1); DataOverlayEntry schema = new GenericDataOverlayEntry(); schema.setName("CNC"); @@ -436,11 +586,13 @@ public class ColorModelCommandTest extends CommandTestFunctions { ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); Map<BioEntity, DataOverlayEntry> map = factory.getModifiedElements(); - assertEquals(1, map.values().size()); + assertEquals(1, map.size()); } - public void testAliasColoringWithUnknownElementSourceId() throws Exception { - Model model = getModelForFile("testFiles/sample.xml", false); + @Test + public void testAliasColoringWithUnknownElementSourceId() { + Model model = createSimpleModel(); + model.addElement(createProtein()); DataOverlayEntry schema = new GenericDataOverlayEntry(); schema.setElementId("xxx"); @@ -450,12 +602,13 @@ public class ColorModelCommandTest extends CommandTestFunctions { ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); Map<BioEntity, DataOverlayEntry> map = factory.getModifiedElements(); - assertEquals(0, map.values().size()); + assertEquals(0, map.size()); } @Test public void testAliasColoringWithElementIdMatch() throws Exception { - Model model = getModelForFile("testFiles/sample.xml", false); + Model model = createSimpleModel(); + model.addElement(createProtein()); DataOverlayEntry schema = new GenericDataOverlayEntry(); schema.setElementId(model.getElements().iterator().next().getElementId()); @@ -465,59 +618,7 @@ public class ColorModelCommandTest extends CommandTestFunctions { ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); Map<BioEntity, DataOverlayEntry> map = factory.getModifiedElements(); - assertEquals(1, map.values().size()); - } - - @Test - public void testGetModifiedElements() throws Exception { - Reaction reaction = new Reaction("re"); - reaction.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); - - Model model = new ModelFullIndexed(null); - model.addReaction(reaction); - - GenericDataOverlayEntry colorSchema = new GenericDataOverlayEntry(); - colorSchema.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); - - List<DataOverlayEntry> schemas = new ArrayList<>(); - schemas.add(colorSchema); - - ColorModelCommand factory = new ColorModelCommand(model, schemas, colorExtractor); - - assertNotNull(factory.getModifiedElements().get(reaction)); - } - - @Test - public void testApplyColorToReaction() throws Exception { - Model model = getModelForFile("testFiles/sample.xml", false); - Reaction re4 = model.getReactionByReactionId("re1"); - - DataOverlayEntry schema = new GenericDataOverlayEntry(); - schema.setElementId("re1"); - schema.setColor(Color.YELLOW); - schema.setName(null); - - ColorModelCommand factory = new ColorModelCommand(model, new ArrayList<>(), colorExtractor); - - factory.applyColor(re4, schema); - - assertEquals(Color.YELLOW, re4.getLine().getColor()); - } - - @Test - public void testColorTranscriptionFactor() { - Model model = new ModelFullIndexed(null); - - Gene gene = createGene(); - TranscriptionSite site = new TranscriptionSite(); - site.setBorderColor(Color.YELLOW); - gene.addTranscriptionSite(site); - model.addElement(gene); - - ColorModelCommand factory = new ColorModelCommand(model, new ArrayList<>(), colorExtractor); - factory.execute(); - - assertEquals(Color.BLACK, site.getBorderColor()); + assertEquals(1, map.size()); } } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/CommandTestFunctions.java b/model-command/src/test/java/lcsb/mapviewer/commands/CommandTestFunctions.java index e02274c2ff..3b9ab3f51b 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/CommandTestFunctions.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/CommandTestFunctions.java @@ -1,14 +1,11 @@ package lcsb.mapviewer.commands; import lcsb.mapviewer.common.Configuration; +import lcsb.mapviewer.common.tests.TestUtils; import lcsb.mapviewer.common.tests.UnitTestFailedWatcher; -import lcsb.mapviewer.converter.ConverterParams; -import lcsb.mapviewer.converter.InvalidInputDataExecption; -import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; import lcsb.mapviewer.model.graphics.HorizontalAlign; +import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.graphics.VerticalAlign; -import lcsb.mapviewer.model.map.Drawable; -import lcsb.mapviewer.model.map.InconsistentModelException; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; import lcsb.mapviewer.model.map.reaction.Product; @@ -24,15 +21,13 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Rule; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; +import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public abstract class CommandTestFunctions { +public abstract class CommandTestFunctions extends TestUtils { private static final Map<String, Model> models = new HashMap<>(); protected static final double EPSILON = Configuration.EPSILON; @@ -43,27 +38,9 @@ public abstract class CommandTestFunctions { private int counter; - protected Model getModelForFile(final String fileName, final boolean fromCache) throws Exception { - if (!fromCache) { - logger.debug("File without cache: " + fileName); - final Model result = new CellDesignerXmlParser().createModel(new ConverterParams().filename(fileName)); - result.setName("Unknown"); - return result; - } - Model result = models.get(fileName); - if (result == null) { - logger.debug("File to cache: " + fileName); - - final CellDesignerXmlParser parser = new CellDesignerXmlParser(); - result = parser.createModel(new ConverterParams().filename(fileName).sizeAutoAdjust(false)); - result.setName("Unknown"); - models.put(fileName, result); - } - return result; - } - protected Model createSimpleModel() { final Model model = new ModelFullIndexed(null); + model.setName(faker.name().fullName()); final GenericProtein alias = new GenericProtein("alias_id"); assignCoordinates(alias); @@ -89,22 +66,6 @@ public abstract class CommandTestFunctions { return model; } - protected Model serializeViaCellDesigner(final Model original) - throws InconsistentModelException, InvalidInputDataExecption { - final CellDesignerXmlParser parser = new CellDesignerXmlParser(); - final String xmlString = parser.model2String(original); - final InputStream stream = new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8)); - final Model result = parser.createModel(new ConverterParams().inputStream(stream).sizeAutoAdjust(false)); - - for (final Drawable bioEntity : original.getDrawables()) { - bioEntity.setZ(null); - } - for (final Drawable bioEntity : result.getDrawables()) { - bioEntity.setZ(null); - } - return result; - } - protected Reaction createReaction(final Protein protein, final Protein protein2) { final Reaction reaction = new TransportReaction("" + counter++); reaction.addReactant(new Reactant(protein)); @@ -112,6 +73,18 @@ public abstract class CommandTestFunctions { return reaction; } + protected Reaction createReactionWithLayout(final Protein protein, final Protein protein2) { + final Reaction reaction = new TransportReaction("" + counter++); + Reactant reactant = new Reactant(protein); + reactant.setLine(new PolylineData(new Point2D.Double(protein.getX(), protein.getY()), protein.getCenter())); + Product product = new Product(protein2); + product.setLine(new PolylineData(new Point2D.Double(protein2.getX(), protein2.getY()), protein2.getCenter())); + reaction.addReactant(reactant); + reaction.addProduct(product); + reaction.setLine(new PolylineData(protein.getCenter(), protein2.getCenter())); + return reaction; + } + protected GenericProtein createProtein() { final GenericProtein result = new GenericProtein("" + counter++); result.setWidth((Double) null); @@ -121,6 +94,15 @@ public abstract class CommandTestFunctions { return result; } + protected GenericProtein createProteinWithLayout() { + final GenericProtein result = createProtein(); + result.setWidth(faker.number().numberBetween(100, 200)); + result.setHeight(faker.number().numberBetween(100, 200)); + result.setX(faker.number().numberBetween(100, 200)); + result.setY(faker.number().numberBetween(100, 200)); + return result; + } + protected Gene createGene() { final Gene result = new Gene("" + counter++); return result; diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/CopyCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/CopyCommandTest.java index c9d4eeb036..a75ff5b35a 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/CopyCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/CopyCommandTest.java @@ -5,8 +5,6 @@ import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.compartment.SquareCompartment; -import lcsb.mapviewer.model.map.kinetics.SbmlFunction; -import lcsb.mapviewer.model.map.kinetics.SbmlParameter; import lcsb.mapviewer.model.map.layout.graphics.Layer; import lcsb.mapviewer.model.map.model.Author; import lcsb.mapviewer.model.map.model.ElementSubmodelConnection; @@ -38,7 +36,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; public class CopyCommandTest extends CommandTestFunctions { @@ -54,38 +51,6 @@ public class CopyCommandTest extends CommandTestFunctions { private int counter = 0; - @Test - public void testCopyModel() throws Exception { - Model model = getModelForFile("testFiles/sample.xml", false); - Model copy = new CopyCommand(model).execute(); - - assertEquals(0, comparator.compare(model, copy)); - } - - @Test - public void testCopyModelWithKinetics() throws Exception { - Model model = getModelForFile("testFiles/kinetics_with_compartment.xml", false); - Model copy = new CopyCommand(model).execute(); - - assertEquals(0, comparator.compare(model, copy)); - for (final Reaction reaction : copy.getReactions()) { - if (reaction.getKinetics() != null) { - for (final Element element : reaction.getKinetics().getElements()) { - assertTrue("Element in the copy doesn't belong to copy", copy.getElements().contains(element)); - } - for (final SbmlFunction function : reaction.getKinetics().getFunctions()) { - assertTrue("Function in the copy doesn't belong to copy", copy.getFunctions().contains(function)); - } - for (final SbmlParameter parameter : reaction.getKinetics().getParameters()) { - if (parameter.getParameterId().equals("k2")) { - assertTrue("Global parameter in the function copy doesn't belong to copy", - copy.getParameters().contains(parameter)); - } - } - } - } - } - @Test public void testCopyCustomModel() { Model model = new ModelFullIndexed(null); @@ -122,45 +87,6 @@ public class CopyCommandTest extends CommandTestFunctions { assertEquals(0, comparator.compare(model, copy)); } - @Test - public void testCopyModel3() throws Exception { - Model model = getModelForFile("testFiles/complex_with_state.xml", true); - - Model copy = new CopyCommand(model).execute(); - - Model copy2 = serializeViaCellDesigner(copy); - - // check if after conversion to xml everything works - assertEquals(0, comparator.compare(copy, copy2)); - } - - @Test - public void testCopyModel4() throws Exception { - Model model = getModelForFile("testFiles/problematic_description.xml", true); - - Model copy = new CopyCommand(model).execute(); - - Model copy2 = serializeViaCellDesigner(copy); - - // check if after conversion to xml everything works - assertEquals(0, comparator.compare(copy, copy2)); - } - - @Test - public void testCopyModelWithArtificialAliases() throws Exception { - Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); - new CreateHierarchyCommand(model, 2, 2).execute(); - - Model copy = new CopyCommand(model).execute(); - - Model copy2 = serializeViaCellDesigner(copy); - - new CreateHierarchyCommand(copy2, 2, 2).execute(); - - // check if after conversion to xml everything works - assertEquals(0, comparator.compare(copy, copy2)); - } - @Test public void testCopyModelWithSubmodels() throws Exception { Model model = getModel(); @@ -389,16 +315,4 @@ public class CopyCommandTest extends CommandTestFunctions { } } - - @Test - public void testCopyModelWithProject() throws Exception { - Model originalModel = getModelForFile("testFiles/sample.xml", false); - Project project = new Project(); - project.addModel(originalModel); - - Model colorModel = new CopyCommand(originalModel).execute(); - - assertNotEquals(originalModel.getProject(), colorModel.getProject()); - } - } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/CreateHierarchyCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/CreateHierarchyCommandTest.java index 323d0ad0eb..246adc24a1 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/CreateHierarchyCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/CreateHierarchyCommandTest.java @@ -1,38 +1,21 @@ package lcsb.mapviewer.commands; -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 java.awt.Color; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.converter.ConverterParams; -import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; -import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.compartment.PathwayCompartment; import lcsb.mapviewer.model.map.layout.graphics.Layer; import lcsb.mapviewer.model.map.layout.graphics.LayerRect; import lcsb.mapviewer.model.map.layout.graphics.LayerText; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.modelutils.map.ElementUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.awt.Color; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; public class CreateHierarchyCommandTest extends CommandTestFunctions { @@ -45,268 +28,7 @@ public class CreateHierarchyCommandTest extends CommandTestFunctions { } @Test - public void testCyclicComplexes() throws Exception { - Model model = getModelForFile("testFiles/cyclic_hierarchy_problem.xml", false); - - new CreateHierarchyCommand(model, 8, 80).execute(); - - Species alias = model.getElementByElementId("sa5033"); - - Set<Element> parents = new HashSet<Element>(); - while (alias.getComplex() != null) { - assertFalse("Cyclic nesting", parents.contains(alias.getComplex())); - alias = alias.getComplex(); - parents.add(alias); - } - - Set<String> levels = new HashSet<>(); - for (final Element a : model.getElements()) { - levels.add(a.getVisibilityLevel()); - } - assertTrue(levels.size() > 2); - } - - @Test - public void testCreateHierachy() throws Exception { - Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); - - new CreateHierarchyCommand(model, 2, 2).execute(); - // check if second call will throw an exception... - new CreateHierarchyCommand(model, 2, 2).execute(); - } - - @Test - public void testCreateHierachy2() throws Exception { - Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); - - new CreateHierarchyCommand(model, 2, 2).execute(); - - boolean artifitial = false; - for (final Compartment a : model.getCompartments()) { - if (a instanceof PathwayCompartment) { - artifitial = true; - } - } - assertTrue("No hierarchical structure element found", artifitial); - } - - @Test - public void testRecreateHierachy() throws Exception { - Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); - - int aliasSize0 = model.getCompartments().size(); - - new CreateHierarchyCommand(model, 2, 2).execute(); - - int aliasSize = model.getCompartments().size(); - - assertTrue(aliasSize0 != aliasSize); - new CreateHierarchyCommand(model, 2, 2).execute(); - - int aliasSize2 = model.getCompartments().size(); - - assertEquals(aliasSize, aliasSize2); - } - - @Test - public void testParenting() throws Exception { - Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); - - new CreateHierarchyCommand(model, 2, 2).execute(); - - assertFalse(model.getElementByElementId("sa1").getCompartment() instanceof PathwayCompartment); - } - - @Test - public void testCreateComponentsMinVisibility() throws Exception { - double zoomFactor = 39.0625; - int levels = 6; - - Model model = getModelForFile("testFiles/other_full/GSTP1 subnetwork_220214.xml", false); - - new CreateHierarchyCommand(model, levels, zoomFactor).execute(); - - for (final Compartment compartment : model.getCompartments()) { - if (compartment.getCompartment() == null) { - int visibilityLevel = Integer.valueOf(compartment.getVisibilityLevel()); - assertTrue("Alias " + compartment.getElementId() + " is not visible at levels highers than " - + compartment.getVisibilityLevel(), visibilityLevel <= 1); - } - } - - for (final Species species : model.getSpeciesList()) { - if (species.getCompartment() == null) { - int visibilityLevel = Integer.valueOf(species.getVisibilityLevel()); - assertTrue("Alias " + species.getElementId() + " is not visible at levels highers than " - + species.getVisibilityLevel(), visibilityLevel <= 1); - } - } - } - - @Test - public void testCreateComponentsMaxVisibility() throws Exception { - double zoomFactor = 39.0625; - int levels = 6; - - Model model = getModelForFile("testFiles/other_full/GSTP1 subnetwork_220214.xml", false); - - new CreateHierarchyCommand(model, levels, zoomFactor).execute(); - - for (final Element element : model.getElements()) { - int visibilityLevel = Integer.valueOf(element.getVisibilityLevel()); - assertTrue("Alias " + element.getElementId() + " is not visible even at the bottom level (visibility: " - + element.getVisibilityLevel() + ") ", visibilityLevel <= levels); - } - } - - @Test - public void testCompactComplexesInNestedView() throws Exception { - Model model = getModelForFile("testFiles/problematic/compact_complex_view_problem.xml", false); - Element alias = model.getElementByElementId("sa1"); - Object parent1 = alias.getCompartment(); - new CreateHierarchyCommand(model, 3, 16).execute(); - Object parent2 = alias.getCompartment(); - assertEquals(parent1, parent2); - } - - @Test(expected = InvalidStateException.class) - public void testRecallHierachyCreation() throws Exception { - Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); - - CreateHierarchyCommand command = new CreateHierarchyCommand(model, 2, 2); - command.execute(); - command.execute(); - } - - @Test - public void testClear() throws Exception { - Model model = getModelForFile("testFiles/artifitial_compartments.xml", false); - - CreateHierarchyCommand command = new CreateHierarchyCommand(model, 2, 2); - command.clean(); - for (final Element alias : model.getElements()) { - assertNull(alias.getCompartment()); - } - for (final Compartment alias : model.getCompartments()) { - assertNull(alias.getCompartment()); - assertTrue(alias.getElements().isEmpty()); - } - } - - @Test - public void testNestedProblem() throws Exception { - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser - .createModel(new ConverterParams().filename("testFiles/nested_test.xml").sizeAutoAdjust(true)); - - double zoomFactor = Math.max(model.getHeight(), model.getWidth()) / (256); - int zoomLevels = (int) Math.ceil(Math.log(zoomFactor) / Math.log(2)); - - CreateHierarchyCommand command = new CreateHierarchyCommand(model, zoomLevels, zoomFactor); - command.execute(); - - for (final Element alias : model.getElements()) { - Element parentAlias = alias.getCompartment(); - if (parentAlias != null) { - int parentVisibilityLevel = Integer.valueOf(parentAlias.getVisibilityLevel()); - int aliasVisibilityLevel = Integer.valueOf(alias.getVisibilityLevel()); - assertTrue(aliasVisibilityLevel >= parentVisibilityLevel); - } - if (alias instanceof Species) { - parentAlias = ((Species) alias).getComplex(); - if (parentAlias != null) { - int parentVisibilityLevel = Integer.valueOf(parentAlias.getVisibilityLevel()); - int aliasVisibilityLevel = Integer.valueOf(alias.getVisibilityLevel()); - assertTrue(aliasVisibilityLevel >= parentVisibilityLevel); - } - } - } - } - - @Test - public void testDisconnectedChildInComplex() throws Exception { - Model model = getModelForFile("testFiles/problematic/disconnected_child_in_complex.xml", false); - - new CreateHierarchyCommand(model, 8, 80).execute(); - - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - String xmlString = parser.model2String(model); - - InputStream stream = new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8)); - - parser.createModel(new ConverterParams().inputStream(stream)); - } - - @Test - public void testHierarchyWithCustomSemanticZooming() throws Exception { - Model model = getModelForFile("testFiles/custom_semantic_zooming.xml", false); - - Map<Element, String> visibilityLevels = new HashMap<>(); - for (final Element element : model.getElements()) { - if (element.getVisibilityLevel() != null && !element.getVisibilityLevel().isEmpty()) { - visibilityLevels.put(element, element.getVisibilityLevel()); - } - } - - new CreateHierarchyCommand(model, 4, 80).execute(); - - for (final Element element : model.getElements()) { - if (visibilityLevels.get(element) != null) { - assertEquals("Visibility level changed, but shouldn't", visibilityLevels.get(element), - element.getVisibilityLevel()); - } - } - } - - @Test - public void testHierarchyWithCustomSemanticZoomingPathwayLevels() throws Exception { - ElementUtils eu = new ElementUtils(); - Model model = getModelForFile("testFiles/custom_semantic_zooming.xml", false); - - Map<Element, String> visibilityLevels = new HashMap<>(); - for (final Element element : model.getElements()) { - if (element.getVisibilityLevel() != null && !element.getVisibilityLevel().isEmpty()) { - visibilityLevels.put(element, element.getVisibilityLevel()); - } - } - - new CreateHierarchyCommand(model, 4, 80).execute(); - - for (final Element element : model.getElements()) { - if (visibilityLevels.get(element) == null) { - int visibilityLevel = Integer.parseInt(element.getVisibilityLevel()); - if (element.getCompartment() != null) { - int parentTransparency = Integer.parseInt(element.getCompartment().getTransparencyLevel()); - assertEquals( - eu.getElementTag(element) + eu.getElementTag(element.getCompartment()) - + "Element should be directly visible when parent is transparent", - parentTransparency, visibilityLevel); - } else if (element instanceof Species) { - int parentTransparency = Integer.parseInt(((Species) element).getComplex().getTransparencyLevel()); - assertEquals( - eu.getElementTag(element) + eu.getElementTag(((Species) element).getComplex()) - + "Element should be directly visible when parent is transparent", - parentTransparency, visibilityLevel); - } - } - } - } - - @Test - public void testLayerWithNotes() throws Exception { - Model model = getModelForFile("testFiles/layer_text_with_notes.xml", false); - - new CreateHierarchyCommand(model, 4, 80).execute(); - - PathwayCompartment pathway = (PathwayCompartment) model.getCompartments().get(0); - - assertEquals("test", pathway.getName()); - assertEquals("5", pathway.getVisibilityLevel()); - assertEquals((Integer) 11, pathway.getZ()); - } - - @Test - public void testCreatePathwayFromRectangle() throws Exception { + public void testCreatePathwayFromRectangle() { Model model = new ModelFullIndexed(null); Layer layer = new Layer(); diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/MoveElementsCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/MoveElementsCommandTest.java deleted file mode 100644 index 1af849f468..0000000000 --- a/model-command/src/test/java/lcsb/mapviewer/commands/MoveElementsCommandTest.java +++ /dev/null @@ -1,241 +0,0 @@ -package lcsb.mapviewer.commands; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; - -import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelComparator; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Element; - -public class MoveElementsCommandTest extends CommandTestFunctions { - - private ModelComparator modelComparator = new ModelComparator(); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testMoveAlias() throws Exception { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); - Model model2 = getModelForFile("testFiles/spliting_test_Case.xml", false); - Element alias = model.getElementByElementId("sa2"); - Element alias2 = model.getElementByElementId("sa1"); - double anotherAliasX = alias2.getX(); - double anotherAliasY = alias2.getY(); - - List<BioEntity> list = new ArrayList<>(); - list.add(alias); - double x = alias.getX(); - double y = alias.getY(); - - double dx = 10; - double dy = 2; - - // models should be equal before move - assertEquals(0, modelComparator.compare(model, model2)); - - MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, dx, dy); - moveCommand.execute(); - - // after move models should be different - assertTrue(0 != modelComparator.compare(model, model2)); - - // check new coordinates - assertEquals(x + dx, alias.getX(), Configuration.EPSILON); - assertEquals(y + dy, alias.getY(), Configuration.EPSILON); - - // and check if another alias didn't change coordinates - assertEquals(anotherAliasX, alias2.getX(), Configuration.EPSILON); - assertEquals(anotherAliasY, alias2.getY(), Configuration.EPSILON); - - list = new ArrayList<>(); - list.add(model2.getElementByElementId("sa2")); - MoveElementsCommand moveCommand2 = new MoveElementsCommand(model2, list, dx, dy); - moveCommand2.execute(); - - // if we perform the same operator on the second model then they should be - // equal - assertEquals(0, modelComparator.compare(model, model2)); - } - - @Test(expected = InvalidArgumentException.class) - public void testMoveSpecies() throws Exception { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); - List<BioEntity> list = new ArrayList<>(); - list.add(Mockito.mock(BioEntity.class)); - - MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, 10, 10); - moveCommand.execute(); - } - - @Test - public void testAliasWithReaction() throws Exception { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); - Model model2 = getModelForFile("testFiles/spliting_test_Case.xml", false); - Element alias = model.getElementByElementId("sa1"); - Element alias2 = model.getElementByElementId("sa2"); - double anotherAliasX = alias2.getX(); - double anotherAliasY = alias2.getY(); - Reaction reaction = model.getReactionByReactionId("re1"); - - List<BioEntity> list = new ArrayList<>(); - list.add(alias); - double x = reaction.getReactants().get(0).getLine().getStartPoint().getX(); - double y = reaction.getReactants().get(0).getLine().getStartPoint().getY(); - - double dx = 10; - double dy = 2; - - // models should be equal before move - assertEquals(0, modelComparator.compare(model, model2)); - - MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, dx, dy); - moveCommand.execute(); - - // after move models should be different - assertTrue(0 != modelComparator.compare(model, model2)); - - // check new coordinates of reaction - assertEquals(x + dx, reaction.getReactants().get(0).getLine().getStartPoint().getX(), Configuration.EPSILON); - assertEquals(y + dy, reaction.getReactants().get(0).getLine().getStartPoint().getY(), Configuration.EPSILON); - - // and check if another alias didn't change coordinates - assertEquals(anotherAliasX, alias2.getX(), Configuration.EPSILON); - assertEquals(anotherAliasY, alias2.getY(), Configuration.EPSILON); - - list = new ArrayList<>(); - list.add(model2.getElementByElementId("sa1")); - MoveElementsCommand moveCommand2 = new MoveElementsCommand(model2, list, dx, dy); - moveCommand2.execute(); - - // if we perform the same operator on the second model then they should be - // equal - assertEquals(0, modelComparator.compare(model, model2)); - } - - @Test - public void testMoveReaction() throws Exception { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); - Element alias2 = model.getElementByElementId("sa1"); - double anotherAliasX = alias2.getX(); - double anotherAliasY = alias2.getY(); - Reaction reaction = model.getReactionByReactionId("re1"); - - List<BioEntity> list = new ArrayList<>(); - list.add(reaction); - double x = reaction.getReactants().get(0).getLine().getStartPoint().getX(); - double y = reaction.getReactants().get(0).getLine().getStartPoint().getY(); - - double x2 = reaction.getReactants().get(0).getLine().getEndPoint().getX(); - double y2 = reaction.getReactants().get(0).getLine().getEndPoint().getY(); - - double dx = 10; - double dy = 2; - - MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, dx, dy); - moveCommand.execute(); - - // check new coordinates of reaction (point attached to alias shouldn't - // move, the one not attached should move) - assertEquals(x, reaction.getReactants().get(0).getLine().getStartPoint().getX(), Configuration.EPSILON); - assertEquals(y, reaction.getReactants().get(0).getLine().getStartPoint().getY(), Configuration.EPSILON); - assertEquals(x2 + dx, reaction.getReactants().get(0).getLine().getEndPoint().getX(), Configuration.EPSILON); - assertEquals(y2 + dy, reaction.getReactants().get(0).getLine().getEndPoint().getY(), Configuration.EPSILON); - - // and check if another alias didn't change coordinates - assertEquals(anotherAliasX, alias2.getX(), Configuration.EPSILON); - assertEquals(anotherAliasY, alias2.getY(), Configuration.EPSILON); - } - - @Test - public void testUndo() throws Exception { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); - Model model2 = getModelForFile("testFiles/spliting_test_Case.xml", false); - Element alias = model.getElementByElementId("sa2"); - - List<BioEntity> list = new ArrayList<>(); - list.add(alias); - - double dx = 10; - double dy = 2; - - // models should be equal before move - assertEquals(0, modelComparator.compare(model, model2)); - - MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, dx, dy); - moveCommand.execute(); - - // after move models should be different - assertTrue(0 != modelComparator.compare(model, model2)); - - // undo command - moveCommand.undo(); - - // after undo they should be the same again - assertEquals(0, modelComparator.compare(model, model2)); - - moveCommand.redo(); - - // after redo they should be different again - assertTrue(0 != modelComparator.compare(model, model2)); - } - - @Test - public void testGetAffectedRegion() throws Exception { - Model model = getModelForFile("testFiles/spliting_test_Case.xml", false); - Element alias = model.getElementByElementId("sa2"); - - List<BioEntity> list = new ArrayList<>(); - list.add(alias); - double x = alias.getX(); - double y = alias.getY(); - - double dx = 10; - double dy = 2; - - double minx = x; - double maxx = alias.getWidth() + x + dx; - - double miny = y; - double maxy = alias.getHeight() + y + dy; - - MoveElementsCommand moveCommand = new MoveElementsCommand(model, list, dx, dy); - assertNull(moveCommand.getAffectedRegion()); - moveCommand.execute(); - assertNotNull(moveCommand.getAffectedRegion()); - Rectangle2D affectedRegion = moveCommand.getAffectedRegion(); - assertEquals(minx, affectedRegion.getX(), Configuration.EPSILON); - assertEquals(miny, affectedRegion.getY(), Configuration.EPSILON); - assertEquals(maxx, affectedRegion.getX() + affectedRegion.getWidth(), Configuration.EPSILON); - assertEquals(maxy, affectedRegion.getY() + affectedRegion.getHeight(), Configuration.EPSILON); - - moveCommand.undo(); - - affectedRegion = moveCommand.getAffectedRegion(); - assertEquals(minx, affectedRegion.getX(), Configuration.EPSILON); - assertEquals(miny, affectedRegion.getY(), Configuration.EPSILON); - assertEquals(maxx, affectedRegion.getX() + affectedRegion.getWidth(), Configuration.EPSILON); - assertEquals(maxy, affectedRegion.getY() + affectedRegion.getHeight(), Configuration.EPSILON); - } - -} diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteFieldTest.java b/model-command/src/test/java/lcsb/mapviewer/utils/NoteFieldTest.java similarity index 85% rename from converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteFieldTest.java rename to model-command/src/test/java/lcsb/mapviewer/utils/NoteFieldTest.java index ebdc23cfce..70f45afb46 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteFieldTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/utils/NoteFieldTest.java @@ -1,12 +1,12 @@ -package lcsb.mapviewer.converter.model.celldesigner.annotation; - -import static org.junit.Assert.assertNotNull; +package lcsb.mapviewer.utils; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertNotNull; + public class NoteFieldTest { @AfterClass @@ -22,7 +22,7 @@ public class NoteFieldTest { } @Test - public void testVallues() { + public void testValues() { for (final NoteField field : NoteField.values()) { assertNotNull(NoteField.valueOf(field.toString())); assertNotNull(field.getClazz()); diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParserTest.java b/model-command/src/test/java/lcsb/mapviewer/utils/RestAnnotationParserTest.java similarity index 85% rename from converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParserTest.java rename to model-command/src/test/java/lcsb/mapviewer/utils/RestAnnotationParserTest.java index 1ab0102ac7..adf50fc910 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParserTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/utils/RestAnnotationParserTest.java @@ -1,19 +1,15 @@ -package lcsb.mapviewer.converter.model.celldesigner.annotation; +package lcsb.mapviewer.utils; -import lcsb.mapviewer.common.exception.InvalidArgumentException; +import lcsb.mapviewer.commands.CommandTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerElement; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Species; -import org.apache.xerces.dom.DocumentImpl; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -30,7 +26,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -public class RestAnnotationParserTest extends CellDesignerTestFunctions { +public class RestAnnotationParserTest extends CommandTestFunctions { @Before public void setUp() throws Exception { @@ -126,7 +122,7 @@ public class RestAnnotationParserTest extends CellDesignerTestFunctions { assertEquals(1, protein.getSynonyms().size()); assertEquals(1, protein.getFormerSymbols().size()); - assertEquals(6, getWarnings().size()); + Assert.assertEquals(6, getWarnings().size()); } @Test @@ -137,7 +133,7 @@ public class RestAnnotationParserTest extends CellDesignerTestFunctions { Species proteinAlias = new GenericProtein("id"); parser.processNotes(node.getFirstChild(), proteinAlias); - assertEquals(1, getWarnings().size()); + Assert.assertEquals(1, getWarnings().size()); } @Test @@ -156,26 +152,9 @@ public class RestAnnotationParserTest extends CellDesignerTestFunctions { parser.processNotes(node.getFirstChild(), reaction); - assertEquals(8, getWarnings().size()); + Assert.assertEquals(8, getWarnings().size()); } - @Test - public void testMoveAnnotationsFromNotes() throws Exception { - Model model = getModelForFile("testFiles/copyingAnnotationModel.xml"); - - Set<Element> elements = model.getElements(); - for (final Element element : elements) { - if (element.getName().equals("blabla")) { - assertEquals(2, element.getMiriamData().size()); - element.getMiriamData() - .add(new MiriamData(MiriamType.PUBMED, "12345")); - element.getMiriamData() - .add(new MiriamData(MiriamType.PUBMED, "333666")); - assertEquals(2, element.getMiriamData().size()); - } - assertFalse(element.getNotes().contains("rdf:RDF")); - } - } @Test public void testProcessRdfDescription() throws Exception { @@ -228,10 +207,9 @@ public class RestAnnotationParserTest extends CellDesignerTestFunctions { boolean importOnly = rap.isFieldAnnotated(field, ImportOnly.class); if (!deprecated && !importOnly) { - if (field.getClazz().isAssignableFrom(element.getClass()) - || CellDesignerElement.class.isAssignableFrom(field.getClazz())) { + if (field.getClazz().isAssignableFrom(element.getClass())) { assertTrue("Export string doesn't contain info about: " + field.getCommonName(), - str.indexOf(field.getCommonName()) >= 0); + str.contains(field.getCommonName())); } } else { assertEquals("Export string contains info about: " + field.getCommonName() + " but shouldn't", @@ -248,10 +226,9 @@ public class RestAnnotationParserTest extends CellDesignerTestFunctions { String str = rap.createAnnotationString(element, false); for (final NoteField field : NoteField.values()) { - if (field.getClazz().isAssignableFrom(element.getClass()) - || CellDesignerElement.class.isAssignableFrom(field.getClazz())) { + if (field.getClazz().isAssignableFrom(element.getClass())) { assertFalse("Export string contain info about: " + field.getCommonName() + ". But shouldn't", - str.indexOf(field.getCommonName()) >= 0); + str.contains(field.getCommonName())); } } @@ -264,16 +241,6 @@ public class RestAnnotationParserTest extends CellDesignerTestFunctions { assertEquals(0, rap.getFormerSymbols(null).size()); } - @Test(expected = InvalidArgumentException.class) - public void testGetNotesInvalid() throws Exception { - RestAnnotationParser rap = new RestAnnotationParser(); - - Document xmlDoc = new DocumentImpl(); - Node node = xmlDoc.createElement("bla"); - - rap.getNotes(node); - } - @Test public void testGetNotesWithMissingBody() throws Exception { RestAnnotationParser rap = new RestAnnotationParser(); @@ -324,7 +291,7 @@ public class RestAnnotationParserTest extends CellDesignerTestFunctions { parser.processNotes(str, new GenericProtein("id")); - assertEquals(1, getWarnings().size()); + Assert.assertEquals(1, getWarnings().size()); } @Test diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/WikipathwaysTestFunctions.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/WikipathwaysTestFunctions.java index 87aa9ea10f..141626a385 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/WikipathwaysTestFunctions.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/WikipathwaysTestFunctions.java @@ -5,7 +5,6 @@ import lcsb.mapviewer.common.tests.UnitTestFailedWatcher; import lcsb.mapviewer.converter.ConverterException; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.InvalidInputDataExecption; -import lcsb.mapviewer.converter.ZIndexPopulator; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; import lcsb.mapviewer.model.graphics.HorizontalAlign; import lcsb.mapviewer.model.graphics.PolylineData; @@ -23,6 +22,7 @@ import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Species; import lcsb.mapviewer.model.map.species.Unknown; import lcsb.mapviewer.model.map.species.field.StructuralState; +import lcsb.mapviewer.utils.ZIndexPopulator; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Rule; -- GitLab